embedqueue

package
v0.11.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Constants

This section is empty.

Variables

View Source
var ErrCoordinatorLocked = errors.New("embedqueue: coordinator already running for this corpus")

ErrCoordinatorLocked is returned by AcquireCoordinatorLock when another live process already holds the corpus's coordinator lock. The caller MUST refuse to start a second coordinator for the corpus: two coordinators on one corpus each enqueue the same pending chunks and (with the default in-process MemBroker, which cannot dedup across processes) double-embed them (issue #435 C3).

View Source
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

func Run(ctx context.Context, cfg Config) error

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.

Each iteration drains up to BatchSize claimable jobs and embeds them grouped by index_kind in a SINGLE provider call per group (issue #435), so the distributed path batches through the provider exactly like the in-process loop instead of making one embed call per chunk. Ack/Nack stays per-lease, so at-least-once delivery, per-job attempt tracking, and dead-lettering are unchanged.

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.

func RunCoordinator added in v0.10.0

func RunCoordinator(ctx context.Context, coord *Coordinator, opts CoordinatorLoopOptions)

RunCoordinator drives coord.EnqueuePending on a fixed interval until ctx is cancelled (SPEC §8.7.1). Re-enqueuing is safe: an already-embedded chunk is no longer pending, and a duplicate job is idempotent at the embed layer (§8.7.3).

It owns the stall-detection the bare loop lacked (issue #435 C4): a transient enqueue error is reported via OnError and the loop keeps ticking (a momentary broker hiccup must not tear down embedding), but StallThreshold consecutive failures fire OnStall exactly once so a sustained failure surfaces a durable signal instead of a silently-idle daemon. A single success resets both the counter and the armed OnStall.

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

	// Status records terminal per-chunk failures so a job that can never succeed
	// stops being re-created (#709). Optional: with no StatusWriter the worker
	// still rejects what it must, but a permanently-failing chunk stays `pending`
	// and the coordinator keeps re-enqueuing it, so production wiring MUST set it.
	Status StatusWriter

	// CorpusID is the stable corpus identity (SPEC §5.5) THIS worker serves — the
	// same value the coordinator for that corpus stamps on its jobs. A job naming
	// any other corpus is rejected without being executed and without touching
	// this worker's store.
	//
	// Empty means "unbound": the worker accepts every job it is handed, which is
	// only safe on a broker it does not share with another corpus. Production
	// wiring always sets it, resolved from the shared metadata store the job's
	// chunk would be read from, so a worker's corpus binding and its data plane
	// can never disagree (#708).
	CorpusID string

	// LateChunking is THIS worker's resolved ingest.late_chunking flag (SPEC
	// §8.1.9 "Distributed workers"). On, the worker pools per document and MUST
	// fail a per-chunk job (Job.RepID == 0): token-embedding a whole document for
	// one chunk would break document ownership and cost one document embed per
	// chunk. Such a job is returned for redelivery and, on its final delivery,
	// recorded against the chunk with the reason, so an old per-chunk coordinator
	// paired with a pooling worker is visible rather than a silent stall.
	LateChunking bool

	// 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

	// BatchSize bounds how many jobs the worker leases and embeds per iteration
	// (SPEC §8.7, issue #435). The worker drains up to BatchSize claimable jobs,
	// groups them by index_kind, and embeds each group in a SINGLE provider call
	// via EmbedAndIndex — matching the in-process loop's batching instead of one
	// provider call per chunk. Non-positive defaults to 32 (the in-process
	// EmbeddingWorker default). A value of 1 restores the legacy one-at-a-time
	// behavior.
	BatchSize int

	// 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 MUST be the corpus's stable persisted identity (SPEC §5.5 —
	// identity.ResolveCorpusID), not a root path or any other incidental string.
	// It is what namespaces this corpus's jobs inside a broker several corpora
	// may share, and what a worker checks before it executes one. A coordinator
	// that leaves it empty can only be used against a broker it does not share
	// (#708).
	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
	// LateChunking is the resolved ingest.late_chunking flag (SPEC §8.1.9). On,
	// the coordinator enqueues one DOCUMENT job per representation carrying every
	// pending chunk of that representation (Job.RepID / Job.ChunkIDs) instead of
	// one job per chunk, so exactly one worker token-embeds the document and pools
	// all of its chunks. Source must then also implement RepPendingSource.
	LateChunking bool
}

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

func (c *Coordinator) EnqueuePending(ctx context.Context, indexKind string) (int, error)

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 corpus_id+chunk_id+index_kind, so repeated ticks never pile up duplicate live jobs and a chunk id that collides with another corpus's is still enqueued (SPEC §8.7.3, #708). 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 CoordinatorLock added in v0.10.0

type CoordinatorLock struct {
	// contains filtered or unexported fields
}

CoordinatorLock is a single-holder, cross-process advisory lock guarding a corpus's embedding coordinator (issue #435 C3, "detect + refuse"). It is a guard against the accidental double-`up` / restart-race case, NOT a full multi-node leader election (that lands with the standalone-worker deployment, #249): it only ensures at most one coordinator runs per corpus on a single host.

The default broker is in-process (MemBroker), so two daemons against the same corpus each get a PRIVATE queue and cannot coordinate through the broker at all; only a host-level lock (this) or the shared SQLite broker can catch that. The lock is taken on a file in the corpus state dir, so it also naturally releases if the holder process dies (the OS drops the advisory lock).

The concrete lock is OS-specific; see coordinator_lock_unix.go and coordinator_lock_other.go.

func AcquireCoordinatorLock added in v0.10.0

func AcquireCoordinatorLock(lockPath string) (*CoordinatorLock, error)

AcquireCoordinatorLock takes an exclusive, non-blocking advisory (flock) lock on lockPath, creating the file if absent. It returns ErrCoordinatorLocked when another process already holds it — the caller must then refuse to start a coordinator for this corpus (issue #435 C3). The returned lock is released by Release (or when the process exits and the OS drops the flock).

func (*CoordinatorLock) Release added in v0.10.0

func (l *CoordinatorLock) Release() error

Release drops the advisory lock and closes the lock file. It is safe to call once; a nil or already-released lock is a no-op.

type CoordinatorLoopOptions added in v0.10.0

type CoordinatorLoopOptions struct {
	// Interval is how often the loop re-enqueues the pending head. Non-positive
	// defaults to 2s.
	Interval time.Duration

	// StallThreshold is the number of CONSECUTIVE EnqueuePending failures after
	// which OnStall fires — the loop treats that many back-to-back failures as a
	// sustained stall (broker read-only / disk full), not a transient blip.
	// Non-positive defaults to 3.
	StallThreshold int

	// OnError, if set, is called on every enqueue failure (each tick). It is the
	// per-failure, best-effort notification hook. The loop invokes it SYNCHRONOUSLY
	// on its own goroutine, so the callback MUST be fast/non-blocking (or at most
	// context-bounded) — a callback that blocks indefinitely stalls the loop and
	// prevents further re-enqueues. Cancellation errors are not reported.
	OnError func(err error)

	// OnStall, if set, is called ONCE when the consecutive-failure count first
	// reaches StallThreshold, and not again until a later enqueue succeeds (which
	// resets the counter). It is the durable escalation signal for a sustained
	// stall — unlike OnError it is expected to guarantee delivery (e.g. a blocking,
	// context-aware channel send or a structured event), because otherwise
	// embedding makes no progress while the daemon still looks healthy (issue #435
	// C4). Like OnError it is invoked SYNCHRONOUSLY on the loop's goroutine, so it
	// too must be fast/non-blocking or at most context-bounded (a context-aware
	// blocking send is fine — it cannot outlive ctx). It receives the
	// consecutive-failure count and the latest error.
	OnStall func(consecutive int, err error)
}

CoordinatorLoopOptions configures RunCoordinator (SPEC §8.7.1; issue #435 C4).

type CorpusScopedBroker added in v0.10.0

type CorpusScopedBroker interface {
	Broker

	// LeaseForCorpus claims the next available job whose CorpusID equals
	// corpusID, ignoring every other corpus's jobs. An empty corpusID means "any
	// corpus" and is identical to Lease. Returns ErrNoJob when this corpus has no
	// claimable job, even if other corpora do.
	LeaseForCorpus(ctx context.Context, corpusID string, visibility time.Duration) (Lease, error)
}

CorpusScopedBroker is an OPTIONAL Broker capability: leasing only the jobs of one corpus (SPEC §8.7.2 corpus reference, §8.7.4 corpus isolation on shared infrastructure). Both built-in brokers implement it; the worker discovers it by type assertion, exactly like the store's optional capabilities, so an external adapter that predates it keeps working unchanged.

Worker-side rejection of a foreign corpus's job (worker.prepare) is the mandatory half of the isolation and stands on its own. This is the half that keeps a shared queue EFFICIENT as well as correct: without it, a worker that serves corpus B leases corpus A's jobs only to reject them, burning A's redelivery budget and eventually dead-lettering work that nothing was wrong with (#708).

type EmbeddedGuard added in v0.10.0

type EmbeddedGuard struct {
	// contains filtered or unexported fields
}

EmbeddedGuard makes the "count a chunk as embedded_ok" side effect fire at most once per (index_kind, chunk_id), even when a job is redelivered and re-embedded (SPEC §8.7.3; issue #435 C2).

The distributed path enqueues at-least-once: a lease expiry or a transient Nack redelivers an already-succeeded chunk, and the worker re-runs the exact in-process embed step. Vector writes are idempotent (keyed by chunk_id), but the step's per-upsert OnIndexedChunk hook fires on EVERY successful upsert, so a naive AddEmbeddedOK(1) in that hook inflates embedded_ok past chunks_total on redelivery. The guard gates the COUNT (not the embed) to the first success.

It is safe for concurrent use by the per-axis (text/code) embed hooks. The tracked set is bounded by the number of distinct embedded chunks, matching the corpus size — the same working-set the in-process loop already holds in memory.

func NewEmbeddedGuard added in v0.10.0

func NewEmbeddedGuard() *EmbeddedGuard

NewEmbeddedGuard returns a ready EmbeddedGuard.

func (*EmbeddedGuard) First added in v0.10.0

func (g *EmbeddedGuard) First(indexKind string, chunkID uint64) bool

First reports whether this is the first successful embed observed for (indexKind, chunkID). It returns true exactly once per pair; every later call for the same pair returns false. A caller wires it into the embed-success hook so the embedded_ok counter is incremented only on that first true, making the count idempotent across redelivery/retry (issue #435 C2).

A nil guard treats every call as first (true), so callers that never construct one keep the pre-guard behavior instead of panicking.

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

	// RepID and ChunkIDs turn the job into a DOCUMENT job: while
	// ingest.late_chunking is on, the coordinator enqueues one job per document
	// representation carrying every pending chunk of that representation, so
	// exactly one worker token-embeds the document and pools all of its chunks
	// from that single operation (document ownership). ChunkID is then the first
	// id in ChunkIDs and remains the broker's dedup key. Zero / empty on an
	// ordinary per-chunk job. A worker running the pooling path MUST fail a
	// per-chunk job (RepID == 0) rather than token-embed a whole document for one
	// chunk; 8.7.3 idempotency applies per document job, because a chunk's pooled
	// vector depends only on the document text and its own span.
	RepID    int64
	ChunkIDs []uint64
}

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.

func (Job) AllChunkIDs added in v0.10.0

func (j Job) AllChunkIDs() []uint64

AllChunkIDs returns every chunk id the job names: ChunkIDs for a document job, the single ChunkID otherwise. It is what a terminal failure is recorded against.

func (Job) IsDocument added in v0.10.0

func (j Job) IsDocument() bool

IsDocument reports whether the job is a late-chunking DOCUMENT job (one job per representation carrying every pending chunk), as opposed to a per-chunk job (SPEC §8.1.9 "Distributed workers").

func (Job) IsMedia

func (j Job) IsMedia() bool

IsMedia reports whether the job embeds non-text media (SPEC §8.1.7).

func (Job) Validate

func (j Job) Validate() error

Validate checks that a job carries the minimum identity needed to execute it.

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

	// Attempts is how many times this job has been delivered INCLUDING this
	// delivery, and MaxAttempts is the broker's redelivery budget (0 = the broker
	// does not bound it). Together they tell a worker whether a Nack it is about
	// to issue will REDELIVER the job or DEAD-LETTER it, which is the difference
	// between a failure the pool may still recover from and a terminal one the
	// chunk has to record (SPEC §8.7.3 failure handling; #709). Without them a
	// worker cannot distinguish the two and a permanently unexecutable job is
	// retried, dead-lettered, and then enqueued again forever.
	Attempts    int
	MaxAttempts int
}

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).

func (Lease) Final added in v0.10.0

func (l Lease) Final() bool

Final reports whether this delivery is the last one the broker will make: a Nack now dead-letters the job instead of redelivering it. A broker that does not bound redelivery (MaxAttempts <= 0) is never final.

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

func NewMemBroker(maxAttempts int) *MemBroker

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

func (b *MemBroker) Ack(_ context.Context, token string) error

Ack removes a leased job. An unknown/expired token is a no-op (it may have been reclaimed and redelivered).

func (*MemBroker) Close

func (b *MemBroker) Close() error

Close is a no-op for the in-process broker.

func (*MemBroker) Enqueue

func (b *MemBroker) Enqueue(_ context.Context, job Job) error

Enqueue appends a job to the pending FIFO.

func (*MemBroker) Lease

func (b *MemBroker) Lease(ctx context.Context, visibility time.Duration) (Lease, error)

Lease reclaims any expired in-flight jobs, then claims the first pending job whose notBefore has passed, from any corpus.

func (*MemBroker) LeaseForCorpus added in v0.10.0

func (b *MemBroker) LeaseForCorpus(_ context.Context, corpusID string, visibility time.Duration) (Lease, error)

LeaseForCorpus claims the first claimable pending job belonging to corpusID (SPEC §8.7.2 corpus reference). An empty corpusID claims from any corpus, which is what Lease does.

func (*MemBroker) Nack

func (b *MemBroker) Nack(_ context.Context, token string, retryAfter time.Duration) error

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.

func (*MemBroker) SetClock

func (b *MemBroker) SetClock(now func() time.Time)

SetClock overrides the broker's clock for deterministic lease-expiry tests.

func (*MemBroker) Stats

func (b *MemBroker) Stats(_ context.Context) (Stats, error)

Stats reports queue depth, reclaiming expired leases first so InFlight is accurate.

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 RepPendingSource added in v0.10.0

type RepPendingSource interface {
	PendingChunkTasksByRep(ctx context.Context, repID int64, indexKind string) ([]model.ChunkTask, error)
}

RepPendingSource is the read the coordinator needs under late chunking (SPEC §8.1.9 "Distributed workers"): EVERY pending chunk of one representation, not the page NextPending happens to return, so a document job never misses a pending chunk of its document. The metadata store satisfies it via PendingChunkTasksByRep. A coordinator with LateChunking on requires it.

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

func NewSQLiteBroker(ctx context.Context, path string, maxAttempts int) (*SQLiteBroker, error)

NewSQLiteBroker opens (or creates) a SQLite-backed queue at path. maxAttempts bounds redelivery before dead-lettering (non-positive defaults to 5).

func NewSQLiteBrokerWithDB

func NewSQLiteBrokerWithDB(ctx context.Context, db *sql.DB, maxAttempts int) (*SQLiteBroker, error)

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

func (b *SQLiteBroker) Lease(ctx context.Context, visibility time.Duration) (Lease, error)

Lease reclaims expired leases, then atomically claims the oldest claimable pending job, from any corpus.

func (*SQLiteBroker) LeaseForCorpus added in v0.10.0

func (b *SQLiteBroker) LeaseForCorpus(ctx context.Context, corpusID string, visibility time.Duration) (Lease, error)

LeaseForCorpus claims the oldest claimable pending job belonging to corpusID, leaving every other corpus's jobs for the workers that serve them (SPEC §8.7.2, §8.7.4). An empty corpusID claims from any corpus, which is what Lease does.

func (*SQLiteBroker) Nack

func (b *SQLiteBroker) Nack(ctx context.Context, token string, retryAfter time.Duration) error

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.

func (*SQLiteBroker) Stats

func (b *SQLiteBroker) Stats(ctx context.Context) (Stats, error)

Stats reports queue depth, reclaiming expired leases first so in-flight counts are accurate.

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 StatusWriter added in v0.10.0

type StatusWriter interface {
	MarkFailedWithCategory(ctx context.Context, labels []uint64, category, reason string) error
}

StatusWriter records a TERMINAL per-chunk embedding failure (SPEC §5.3 embedding_status=error, §7.7 per-document/per-chunk errors). The metadata store satisfies it via MarkFailedWithCategory, the same entry point the in-process embedding loop uses, so a distributed failure lands in `dir2mcp status` / `doctor` in the exact shape an in-process one does.

It exists because dead-lettering a job is not, by itself, a terminal outcome for the CHUNK: the broker forgets the job, the chunk stays `pending`, and the coordinator's next tick mints a fresh job with a fresh retry budget. Recording the failure against the chunk is what stops that loop (#709).

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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL