Documentation
¶
Overview ¶
Package embedqueue implements the optional distributed-embedding job queue (SPEC §8.7): a coordinator enqueues embedding jobs for pending chunks and one or more stateless embed-workers lease those jobs, read the referenced corpus bytes directly via CorpusFS (§7.10), embed via the configured provider, and write the resulting vectors + chunk status back to a shared store.
The package is additive and off by default. The single-binary default keeps running the in-process embedding loop (internal/index.EmbeddingWorker) with no broker; the distributed mode is the degenerate-case generalization where the transport is an external broker and embedding compute lives on separate hosts.
The broker transport is implementation-defined (SPEC §8.7.4): this package ships the Broker interface plus a default, dependency-free implementation (in-process and SQLite-backed, both pure-Go) sufficient for the single-node degenerate case and for tests. External-broker adapters (NATS/Redis/SQS) plug in behind the Broker interface without touching the coordinator or worker.
Index ¶
- Variables
- func Run(ctx context.Context, cfg Config) error
- type Broker
- type Config
- type Coordinator
- type Embedder
- type Job
- type Lease
- type MemBroker
- func (b *MemBroker) Ack(_ context.Context, token string) error
- func (b *MemBroker) Close() error
- func (b *MemBroker) Enqueue(_ context.Context, job Job) error
- func (b *MemBroker) Lease(_ context.Context, visibility time.Duration) (Lease, error)
- func (b *MemBroker) Nack(_ context.Context, token string, retryAfter time.Duration) error
- func (b *MemBroker) SetClock(now func() time.Time)
- func (b *MemBroker) Stats(_ context.Context) (Stats, error)
- type PendingSource
- type SQLiteBroker
- func (b *SQLiteBroker) Ack(ctx context.Context, token string) error
- func (b *SQLiteBroker) Close() error
- func (b *SQLiteBroker) Enqueue(ctx context.Context, job Job) error
- func (b *SQLiteBroker) Lease(ctx context.Context, visibility time.Duration) (Lease, error)
- func (b *SQLiteBroker) Nack(ctx context.Context, token string, retryAfter time.Duration) error
- func (b *SQLiteBroker) SetClock(now func() time.Time)
- func (b *SQLiteBroker) Stats(ctx context.Context) (Stats, error)
- type Span
- type Stats
- type TaskFetcher
Constants ¶
This section is empty.
Variables ¶
var ErrNoJob = errors.New("embedqueue: no job available")
ErrNoJob is returned by Broker.Lease when no job is currently available. It is not a failure — the worker run-loop treats it as "queue empty, back off and retry" rather than an error to surface.
Functions ¶
func Run ¶
Run is the distributed embed-worker run-loop (SPEC §8.7.1). It leases jobs, reads the authoritative chunk via the shared store, enforces per-job embed identity, embeds via the shared in-process embedding path, and Acks on success or Nacks (redelivery / dead-letter) on transient failure. It blocks until ctx is cancelled and returns ctx.Err() then.
It is exported as a reusable function because follow-up #249 wraps it in a CLI subcommand; #249 (the subcommand) is out of scope here.
Types ¶
type Broker ¶
type Broker interface {
// Enqueue adds a job to the queue. Enqueuing a job whose chunk_id is already
// queued is allowed (at-least-once delivery is assumed) and idempotent at the
// embedding layer because vector writes are keyed by chunk_id (§8.7.3).
Enqueue(ctx context.Context, job Job) error
// Lease claims the next available job and returns it with a lease token and
// deadline. The job is hidden from other workers until the lease expires or
// the worker Acks/Nacks it. Returns ErrNoJob when the queue is empty.
Lease(ctx context.Context, visibility time.Duration) (Lease, error)
// Ack marks a leased job done; it is removed from the queue. Acking an
// expired/unknown lease token is a no-op (the job may have been redelivered).
Ack(ctx context.Context, token string) error
// Nack returns a leased job for redelivery. If the job has already been
// delivered maxAttempts times it is moved to the dead-letter store instead of
// being requeued (SPEC §8.7.3 dead-lettering). retryAfter delays the next
// delivery; zero makes the job immediately re-claimable.
Nack(ctx context.Context, token string, retryAfter time.Duration) error
// Stats reports queue depth for observability and for tests/coordinator
// drain-detection. It never blocks on in-flight work.
Stats(ctx context.Context) (Stats, error)
// Close releases any resources the broker holds.
Close() error
}
Broker is the implementation-defined transport that carries embedding jobs from the coordinator to the workers (SPEC §8.7.4). Any queue providing at-least-once delivery, a redelivery/visibility mechanism, and a dead-letter path satisfies the contract — NATS, Redis, SQS, or the default in-process / SQLite-backed implementations shipped in this package.
Implementations MUST be safe for concurrent use by the coordinator (Enqueue) and many workers (Lease/Ack/Nack) at once.
type Config ¶
type Config struct {
// Broker is the queue the worker leases jobs from.
Broker Broker
// Fetcher loads the authoritative chunk task for a leased job.
Fetcher TaskFetcher
// Embedders maps an index kind ("text"/"code") to the embed→index→mark step
// for that axis. A job whose index_kind has no embedder is dead-lettered
// (misconfiguration, never a vector in the wrong space).
Embedders map[string]Embedder
// EmbedIdentity is THIS worker's configured embed identity (SPEC §8.1.4). A
// job whose EmbedIdentity differs is rejected (Nacked for redelivery /
// dead-lettering) rather than embedded, preserving the single-space invariant
// across a heterogeneous pool (§8.7.3, §6.4).
EmbedIdentity string
// LeaseDuration is the visibility timeout for a leased job. Non-positive
// defaults to 30s.
LeaseDuration time.Duration
// PollInterval is how long the loop waits after an empty queue before leasing
// again. Non-positive defaults to 500ms.
PollInterval time.Duration
// RetryAfter delays redelivery of a Nacked (transiently failed) job.
// Non-positive defaults to 2s.
RetryAfter time.Duration
// Logger is optional; nil routes to the standard log package. The worker logs
// only job ids and error categories — never broker credentials, media bytes,
// or presigned URLs.
Logger *log.Logger
}
Config configures a distributed embed-worker run-loop (SPEC §8.7.1, the embed-worker / compute-plane role). All fields except the optional Logger and the tuning knobs are required.
type Coordinator ¶
type Coordinator struct {
Source PendingSource
Broker Broker
CorpusID string
SourceKind string
EmbedIdentity string
// BatchSize bounds how many pending chunks are read per drain pass. A
// non-positive value defaults to 256.
BatchSize int
}
Coordinator enqueues embedding jobs for pending chunks (SPEC §8.7.1). It owns no embedding compute — it only translates the store's pending chunks into broker jobs bound to the current corpus reference and embed identity (§8.7.2). It is opt-in: the in-process loop remains the default and this type is only constructed when distributed mode is enabled.
func (*Coordinator) EnqueuePending ¶
EnqueuePending enqueues the currently-pending chunks of indexKind ("text"/ "code", or "" for both) into the broker and returns the number of jobs submitted. NextPending keeps returning the same pending head until those chunks leave the pending state (a worker marks them ok/error out-of-band), and the interface has no offset cursor, so one call enqueues the head it observes — NOT necessarily the entire backlog. The coordinator loop (runCoordinatorLoop) calls this on a ticker, so as the head drains the next pending chunks are picked up; the broker dedups by chunk_id+index_kind, so repeated ticks never pile up duplicate live jobs (SPEC §8.7.3). Re-running is always safe: an already- embedded chunk is no longer pending, and a duplicate job is idempotent at the embed layer (vector writes keyed by chunk_id).
type Embedder ¶
type Embedder interface {
EmbedAndIndex(ctx context.Context, indexKind string, tasks []model.ChunkTask) (int, error)
}
Embedder is the embed→index→mark step the worker reuses. It is satisfied by *index.EmbeddingWorker.EmbedAndIndex, so the distributed worker shares the exact embed/media-load/index/mark logic of the in-process loop rather than duplicating it (idempotent, keyed by chunk_id — §8.7.3).
type Job ¶
type Job struct {
// CorpusID is the stable corpus identity (SPEC §5.5) the chunk belongs to.
// It scopes the shared Tier-C collection/namespace and lets a worker reject
// a job for a corpus it is not configured to serve.
CorpusID string
// Source is the corpus source binding (SPEC §7.8) — "local", "nfs", or "s3"
// — that tells the worker which CorpusFS backend to read bytes through.
Source string
// ChunkID is the chunk's stable id and ANN label (SPEC §5.3). Vector writes
// are keyed by it, which is what makes redelivery idempotent (§8.7.3).
ChunkID uint64
// IndexKind routes the write to the correct axis: "text" or "code" (§6.1).
IndexKind string
// TextHash is the chunk's content hash (SPEC §5.3) for a text chunk. It lets
// a worker detect a stale job whose chunk text changed since enqueue.
TextHash string
// Modality is "" / "text" for a text chunk, or "image"/"audio"/"video"/"pdf"
// for a media chunk (SPEC §8.1.7).
Modality string
// RelPath is the corpus rel_path of the source media for a media chunk; the
// worker reads those bytes via CorpusFS. Empty for text chunks.
RelPath string
// Span is the media chunk's window (SPEC §5.4): the page for a PDF chunk or
// the time window for an audio/video chunk, so the worker fetches and windows
// the exact bytes via CorpusFS range reads. Zero for text chunks.
Span Span
// EmbedIdentity is the corpus-lifetime embed identity
// (provider|text_model|code_model|text_dim|code_dim|multimodal) the
// coordinator enqueued the job under. A worker whose configured embed
// provider does not match this MUST reject the job rather than write a vector
// from the wrong vector space (SPEC §8.7.3, §6.4).
EmbedIdentity string
}
Job is one unit of embedding work (SPEC §8.7.2). It identifies its work precisely enough that any worker can execute it WITHOUT coordinator-relayed payload bytes: the worker reads the referenced corpus bytes directly via CorpusFS (§7.10).
A Job carries no secret material (no broker credentials, no presigned URLs, no media bytes) so it is safe to serialize onto a broker and to log by ID.
type Lease ¶
type Lease struct {
// Job is the leased unit of work.
Job Job
// Token identifies this lease to Ack/Nack. It is opaque to the worker.
Token string
// Deadline is when the lease expires and the job becomes re-claimable. A
// worker SHOULD finish (Ack/Nack) before it; a worker that observes the
// deadline has passed MUST treat its in-flight write as possibly raced by a
// redelivery (idempotency, keyed by chunk_id, makes that safe — §8.7.3).
Deadline time.Time
}
Lease is a claimed job plus the opaque token a worker uses to Ack or Nack it. A lease is held for a broker-defined visibility timeout; if the worker neither Acks nor Nacks before the lease expires the job becomes re-claimable by another worker (SPEC §8.7.3 lease expiry / at-least-once delivery).
type MemBroker ¶
type MemBroker struct {
// contains filtered or unexported fields
}
MemBroker is the default dependency-free, in-process Broker (SPEC §8.7.4). It is the degenerate single-node case: the coordinator and workers share one process and one queue with no external broker. It implements the full contract — at-least-once delivery, lease/visibility expiry, redelivery, and a dead-letter store — so it exercises the same worker code path a real broker would, which is exactly what the single-binary default and the test suite need.
MemBroker is safe for concurrent Enqueue/Lease/Ack/Nack.
func NewMemBroker ¶
NewMemBroker returns an in-process broker. maxAttempts bounds redelivery: a job Nacked after being delivered maxAttempts times is dead-lettered (SPEC §8.7.3). A non-positive maxAttempts defaults to 5.
func (*MemBroker) Ack ¶
Ack removes a leased job. An unknown/expired token is a no-op (it may have been reclaimed and redelivered).
func (*MemBroker) Lease ¶
Lease reclaims any expired in-flight jobs, then claims the first pending job whose notBefore has passed.
func (*MemBroker) Nack ¶
Nack returns a leased job for redelivery, or dead-letters it once it has exhausted maxAttempts (SPEC §8.7.3). An unknown/expired token is a no-op.
type PendingSource ¶
type PendingSource interface {
NextPending(ctx context.Context, limit int, indexKind string) ([]model.ChunkTask, error)
}
PendingSource is the read side of the chunk store the coordinator drains: it returns chunks whose embedding_status is "pending" (SPEC §5.3). The metadata store (internal/store.SQLiteStore) already satisfies it via NextPending, so the coordinator reuses the exact pending-selection the in-process loop uses.
type SQLiteBroker ¶
type SQLiteBroker struct {
// contains filtered or unexported fields
}
SQLiteBroker is the default persistent Broker (SPEC §8.7.4): a dependency-free, pure-Go (CGO_ENABLED=0, §6.5) broker backed by a SQLite table reusing the same modernc.org/sqlite driver the metadata store already uses. It survives a coordinator restart (jobs are durable) and, when pointed at a shared SQLite file on an NFS-reachable path, lets a single-host-plus-NFS worker pool drain a queue without an external broker. A cross-machine pool over a real network broker plugs in behind the Broker interface instead.
Lease/visibility, redelivery, and dead-lettering are implemented with the notBefore/deadline/attempts columns; an expired lease is reclaimed lazily on the next Lease (SPEC §8.7.3 lease expiry).
func NewSQLiteBroker ¶
NewSQLiteBroker opens (or creates) a SQLite-backed queue at path. maxAttempts bounds redelivery before dead-lettering (non-positive defaults to 5).
func NewSQLiteBrokerWithDB ¶
NewSQLiteBrokerWithDB wraps an already-open *sql.DB (e.g. shared with the metadata store). The caller retains ownership of db; Close does not close it.
func (*SQLiteBroker) Ack ¶
func (b *SQLiteBroker) Ack(ctx context.Context, token string) error
Ack deletes the leased job. An unknown/expired token deletes nothing.
func (*SQLiteBroker) Close ¶
func (b *SQLiteBroker) Close() error
Close closes the underlying DB only when the broker owns it.
func (*SQLiteBroker) Enqueue ¶
func (b *SQLiteBroker) Enqueue(ctx context.Context, job Job) error
Enqueue inserts a job in the pending state.
func (*SQLiteBroker) Lease ¶
Lease reclaims expired leases, then atomically claims the oldest claimable pending job.
func (*SQLiteBroker) Nack ¶
Nack requeues the leased job, or dead-letters it once attempts reach maxAttempts (SPEC §8.7.3). An unknown/expired token is a no-op.
func (*SQLiteBroker) SetClock ¶
func (b *SQLiteBroker) SetClock(now func() time.Time)
SetClock overrides the broker's clock for deterministic lease-expiry tests.
type Span ¶
type Span struct {
// Kind is "page" for a PDF page chunk or "time" for an audio/video window.
Kind string
// Page is the 1-based page number for a "page" span.
Page int
// StartMS/EndMS bound a "time" span window in milliseconds.
StartMS int
EndMS int
}
Span is the media-chunk window carried on a Job (SPEC §5.4). It mirrors the scalar fields of model.Span needed to re-fetch and window media bytes, kept local so the broker payload has no dependency on the model package and stays a flat, serialization-friendly shape.
type Stats ¶
type Stats struct {
// Pending is the number of jobs available to be leased.
Pending int
// InFlight is the number of jobs currently leased (not yet Acked/Nacked and
// not yet expired).
InFlight int
// DeadLettered is the number of jobs that exhausted their retries.
DeadLettered int
}
Stats is a point-in-time view of the queue (SPEC §8.7.4 observability).
type TaskFetcher ¶
type TaskFetcher interface {
ChunkTaskByID(ctx context.Context, chunkID uint64) (model.ChunkTask, string, error)
}
TaskFetcher loads the authoritative chunk task for a leased job from the shared store (SPEC §8.7.4 — chunk metadata/status lives in a store reachable by all workers). The metadata store satisfies it via ChunkTaskByID, which returns model.ErrNotFound for a missing or tombstoned chunk so the worker can skip it (tombstone safety, §8.7.3 / §6.6).