diff --git a/docs/incident-nelldb-counter-conflict.md b/docs/incident-nelldb-counter-conflict.md new file mode 100644 index 000000000..6dcfdc22d --- /dev/null +++ b/docs/incident-nelldb-counter-conflict.md @@ -0,0 +1,200 @@ +# Total dispatch outage: `sdk: revision conflict` on every enqueue + +**Date:** 2026-08-05 +**Severity:** Complete blocker — no task can be queued, no event can be recorded. +**Status:** Fixed forward on v0.3.0. Tracked as `archie-core-7ma`. + +> **Correction.** An earlier draft of this document framed the cause as a +> long-standing namespace squat that had always been broken. It is a +> **regression**: commit `44f914c` bumped NellDB v0.2.5 → v0.3.0 touching only +> `go.mod`/`go.sum`, and `internal/nell` was never migrated. v0.2.5's +> `reindex()` indexed every record, so the read-modify-write worked; v0.3.0 +> added the `isInternalID` skip. The prefix choice was always unwise, but it +> was not a defect until the bump. + +## Symptom + +Every poll cycle, forever, surviving restarts: + +``` +INFO issue queued repo=sam/archie-core issue=8 +ERROR event sink insert failed err="sdk: revision conflict" +ERROR nats enqueue failed err="sdk: revision conflict" (x3, redelivered) +``` + +The same issue is re-queued every 60s because it is never successfully +written, so the next poll rediscovers it as new. `processNATSTask` +(`internal/daemon/daemon.go:600`) calls `msg.Nak()` on the error, so NATS +redelivers indefinitely — which is why the three failures repeat rather than +drain. No work is dispatched at all. + +## Root cause + +Archie stores its auto-increment counters under keys the NellDB SDK has +reserved for itself. + +`internal/nell/adapter.go:946,952`: + +```go +return a.nextCounter(ctx, a.tasks, "meta:task_id_counter") +return a.nextCounter(ctx, a.events, "meta:event_id_counter") +``` + +The SDK treats **any** id beginning `meta:` as its own bookkeeping +(`sdk/replicate.go:839-843`): + +```go +// isInternalID reports whether an id is one of the SDK's own bookkeeping +// records (meta:clock, meta:vector) that should not be replicated. +func isInternalID(id string) bool { + return len(id) >= 5 && id[:5] == "meta:" +} +``` + +`DocDB.reindex()` rebuilds the in-memory revision cache on open and **skips +every internal id** (`sdk/docdb.go:128-137`): + +```go +if isInternalID(rec.ID) { + continue // no entry written to d.revs +} +``` + +`DocDB.putIn` then rejects a document that carries a `_rev` for which the +cache has no entry (`sdk/docdb.go:213-217`): + +```go +curRev, exists := d.revs[nell.CompositeKey(collection, id)] +... +if incomingRev != "" && !exists { + return "", ErrConflict +} +``` + +### The sequence + +1. **Fresh database.** `nextCounter` does `Get` → `ErrNotFound` → creates the + doc with no `_rev` → `Put` succeeds and caches the new rev in memory. +2. **While the process stays up**, read-modify-write works: the rev is in + `d.revs`, so `Get`'s `_rev` matches. +3. **Restart.** `sdk.New` → `reindex()` → `ListAll` returns the counter record, + `isInternalID("meta:task_id_counter")` is true, the record is skipped, and + **no rev is cached**. +4. **Next counter increment.** `Get` returns the persisted doc *including* its + `_rev`; `Put` sees `incomingRev != "" && !exists` → `ErrConflict`. + +Step 4 is permanent. It affects `nextTaskID` (every `EnqueueIssue`) and +`nextEventID` (every `InsertEvent`) equally, which is exactly the pair of +errors in the log. The database is not corrupt — it is unwritable through this +code path, and reopening does not clear it. + +### Reproduction + +`internal/nell/counter_repro_test.go` (added, currently failing): + +``` +=== RUN TestCountersSurviveReopen + counter_repro_test.go:51: InsertEvent after reopen returned ErrConflict: + the event log is permanently unwritable: sdk: revision conflict +--- FAIL: TestCountersSurviveReopen (0.00s) +``` + +Open a store, insert one event and one issue, close, reopen, insert again. +Fails in 7ms with no daemon, no NATS and no forge involved. + +## Why it appeared now + +Nothing in the tool changes caused it. It triggers on the **first restart after +the counter documents are created**, so any deployment that has restarted since +the NellDB store was first written is in this state. A fresh database masks it +until the next restart, which is why it can look intermittent across +environments. + +## Second, latent defect + +The same namespace collision silently excludes both counters from +**replication**: `isInternalID` exists precisely to keep SDK bookkeeping from +being replicated between nodes. Two archied instances share a `bot_user`-keyed +node id per `docs/architecture` and the carina deployment runs two. Their task +and event ID counters therefore never converge, so both allocate from their own +sequence and produce **colliding task IDs**. This is masked today only because +the outage above stops any allocation from succeeding. + +## Fix (applied) + +Pinning back to v0.2.5 was rejected: `sdk.MessageRange` is v0.3.0-only, so a +revert would drag the session and message store back with it. + +**The counters moved out of the SDK's reserved namespace** — +`counter:task_id` and `counter:event_id`. This is the only change that fixes +both the outage and the replication exclusion. + +That fixes the replication **exclusion**, not allocation atomicity. The +increment is still a read-modify-write serialised only by the process-local +`Adapter.mu`, so two adapters or disconnected replicas writing one log can +still allocate the same id — and for events, a `Put` over the same +`event:` key would be resolved by LWW, silently dropping one. No +`sdk.Replicator` is wired today, so each log must have exactly one writing +adapter; a replicated deployment needs a distributed-atomic allocation scheme +first. + +1. `internal/nell/adapter.go` — change the two keys to a namespace archie owns, + e.g. `counter:task_id` and `counter:event_id`. + +2. **Migrate on open.** Existing databases hold the old documents and the value + in them is load-bearing: restarting the sequence at 1 would allocate IDs + that already belong to live tasks. The old doc is still *readable* — only + `Put` fails — so migration is a read of `next_id` from `meta:*` and a create + of the new key, once, in `newAdapter`/`OpenStore`. The old document is left + in place; it is inert and rewriting it is what fails. + +3. `isMetaKey` became `isReservedKey` and skips the counters too, so the 13 + scan sites (`Tasks`, `findTaskByID`, `StatusCounts`, `WorkflowStats`, + `StageStats`, `TokensByDay`, …) do not parse one as a task. The counter ids + are matched **exactly, not by prefix**: task keys are + `::`, so a `counter:` prefix rule would also match every + task in a repository owned by `counter` — enqueue would report success and + the task would then be invisible to `ClaimNext` and never run. + `internal/gateway/session_store.go` keeps its own copy; that store writes no + counters, so it is unaffected. + +4. Migration failure is **fatal at `OpenStore`**. Swallowing it would start a + fresh sequence from 1 and reissue IDs belonging to live tasks — two tasks + answering to one `/approve` is worse than refusing to start. + +5. Tests in `internal/nell/counter_repro_test.go`: the regression (persisted log + → write → reopen → write again), a migration test asserting a seeded sequence + continues rather than restarting, a migration-failure test, and a + `counter`-owned-repo test pinning the exact-match rule. + +### Also fixed here + +`Adapter.EnqueueIssue` accepted an `identity` argument and silently discarded +it — the document literal had no `identity` field, so every forge-polled task +was unattributed while `internal/store` (SQLite) recorded it correctly. That +broke multi-identity dispatch and any per-identity view of the queue. + +### Rejected alternative + +Stripping `_rev` before `Put` in `nextCounter` would make the write succeed +(the SDK continues the chain from the current local rev when `_rev` is empty) +and is a one-line change. It is the wrong fix: it leaves archie squatting on a +reserved prefix, leaves the counters excluded from replication, and converts a +loud failure into silent last-write-wins on the ID sequence. + +## Unrelated but worth noting + +`cmd/archied/main.go:309`, the event sink, drops an event on error: + +```go +id, err := st.InsertEvent(context.Background(), e) +if err != nil { + log.Error("event sink insert failed", "err", err) + continue +} +``` + +There is no retry and no dead-letter, and `web.Broadcast(e)` never runs, so the +dashboard silently misses the event too. Small blast radius next to the outage +above — audit and UI rather than task state — but it is real loss, and unlike +the enqueue path there is no NATS redelivery to save it. diff --git a/internal/nell/adapter.go b/internal/nell/adapter.go index 617aa5ea3..bc647bd6f 100644 --- a/internal/nell/adapter.go +++ b/internal/nell/adapter.go @@ -53,7 +53,12 @@ func OpenStore(path, nodeID string) (store.TaskStore, error) { if err != nil { return nil, fmt.Errorf("nell: open log: %w", err) } - return newAdapter(st, nodeID), nil + a, err := openAdapter(st, nodeID) + if err != nil { + _ = st.Close() + return nil, fmt.Errorf("nell: migrate counters: %w", err) + } + return a, nil } // OpenMemory creates an in-memory TaskStore backed by nell.MemoryStore, @@ -76,6 +81,15 @@ func newAdapter(st nell.Store, nodeID string) *Adapter { } } +func openAdapter(st nell.Store, nodeID string) (*Adapter, error) { + a := newAdapter(st, nodeID) + // Carry forward a pre-rename ID sequence before anything can allocate. + if err := a.migrateCounters(context.Background()); err != nil { + return nil, err + } + return a, nil +} + // Close shuts down the underlying store (flushes and closes the log file). func (a *Adapter) Close() error { return a.store.Close() @@ -131,8 +145,13 @@ func (a *Adapter) EnqueueIssue(ctx context.Context, owner, repo string, number i "park_reason": "", "retry_count": int64(0), "watch_comment_id": int64(0), - "created_at": nowRFC3339(), - "updated_at": nowRFC3339(), + // The identity whose poll found this issue. Dropping it here (as this + // did) left every forge-originated task unattributed, so multi-identity + // dispatch and any per-identity listing saw an empty queue. The SQLite + // store has always persisted it; this keeps the two in step. + "identity": identity, + "created_at": nowRFC3339(), + "updated_at": nowRFC3339(), } if _, err := a.tasks.Put(ctx, doc); err != nil { return false, fmt.Errorf("nell: enqueue: %w", err) @@ -209,7 +228,7 @@ func (a *Adapter) ClaimNext(ctx context.Context) (*store.Task, error) { // Scan for the oldest queued task (lowest task ID). var best *store.Task for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -373,7 +392,7 @@ func (a *Adapter) RecoverStale(ctx context.Context) (int64, error) { var count int64 for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -420,7 +439,7 @@ func (a *Adapter) OpenPRs(ctx context.Context) ([]store.Task, error) { } var out []store.Task for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -444,7 +463,7 @@ func (a *Adapter) ClearTerminalTasks(ctx context.Context) (int64, error) { } var count int64 for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -508,7 +527,7 @@ func (a *Adapter) EventsSince(ctx context.Context, sinceID int64, limit int) ([] } var out []events.Event for _, row := range all.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } e := docToEvent(row.Doc) @@ -532,7 +551,7 @@ func (a *Adapter) RecentEvents(ctx context.Context, limit int) ([]events.Event, } var out []events.Event for _, row := range all.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } e := docToEvent(row.Doc) @@ -553,7 +572,7 @@ func (a *Adapter) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, } var out []events.Event for _, row := range all.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } e := docToEvent(row.Doc) @@ -574,7 +593,7 @@ func (a *Adapter) Tasks(ctx context.Context, limit int) ([]store.Task, error) { } var out []store.Task for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -595,7 +614,7 @@ func (a *Adapter) StatusCounts(ctx context.Context) (map[string]int, error) { } counts := map[string]int{} for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -622,7 +641,7 @@ func (a *Adapter) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, erro agg := map[string]*acc{} for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -701,7 +720,7 @@ func (a *Adapter) StageStats(ctx context.Context) ([]store.StageStat, error) { agg := map[stageKey]*acc{} for _, row := range all.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } e := docToEvent(row.Doc) @@ -762,7 +781,7 @@ func (a *Adapter) TokensByDay(ctx context.Context, days int) ([]store.DayTokens, var dayKeys []string for _, row := range all.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } e := docToEvent(row.Doc) @@ -799,8 +818,25 @@ func taskKey(owner, repo string, number int) string { return fmt.Sprintf("%s:%s:%d", owner, repo, number) } -// isMetaKey returns true for internal meta documents (e.g. counters). -func isMetaKey(key string) bool { +// isReservedKey returns true for bookkeeping documents that share a collection +// with real records and must be skipped by every scan. +// +// The counter documents are matched by exact id, not by prefix. Task keys are +// "::", so a prefix rule would also match every task in a +// repository owned by "counter" -- EnqueueIssue would report success and the +// task would then be invisible to ClaimNext, Tasks and StatusCounts, never run +// and never be re-enqueued. Exact matching costs nothing and removes that whole +// class. +// +// "meta:" stays a prefix match: it covers the pre-rename counters plus the +// SDK's own meta:clock / meta:vector records, which do surface in AllDocs and +// would otherwise be parsed as tasks. It carries the same owner-named-"meta" +// caveat, which predates this change. +func isReservedKey(key string) bool { + switch key { + case taskCounterID, eventCounterID: + return true + } return strings.HasPrefix(key, "meta:") } @@ -927,7 +963,7 @@ func (a *Adapter) findTaskByID(ctx context.Context, taskID int64) (*store.Task, return nil, err } for _, row := range result.Rows { - if row.Doc == nil || isMetaKey(row.ID) { + if row.Doc == nil || isReservedKey(row.ID) { continue } t := docToTask(row.Doc) @@ -940,34 +976,116 @@ func (a *Adapter) findTaskByID(ctx context.Context, taskID int64) (*store.Task, // ── Auto-increment counters ───────────────────────────────────────────────── +// Counter document keys. +// +// These deliberately do NOT use a "meta:" prefix. The SDK reserves that prefix +// for its own bookkeeping (meta:clock, meta:vector) and matches it by prefix, +// not by exact name: sdk.isInternalID is `id[:5] == "meta:"`. Two consequences +// followed from squatting on it, and both were live defects: +// +// - DocDB.reindex skips internal ids when rebuilding the in-memory rev cache +// on open, while the record itself stays in the log. After a restart, Get +// returned the counter complete with its _rev but the cache had no entry, +// and putIn rejects exactly that pairing with ErrConflict. Every task +// enqueue and every event insert failed, permanently, for the life of the +// database. +// - isInternalID exists to keep SDK bookkeeping out of replication, so the +// counters were silently excluded from it. Two instances sharing a log +// would have allocated colliding task IDs. +// +// Renaming fixes both. Do not move these back under "meta:". +// +// Renaming does NOT make allocation multi-writer safe. The increment is a +// read-modify-write serialised only by Adapter.mu, which is process-local: two +// adapters or disconnected replicas can still allocate the same id, and an +// event write to the same "event:" key would then be resolved by LWW, +// silently dropping one. Nothing in archie wires an sdk.Replicator today, so +// each log must have exactly one writing adapter; a replicated deployment +// needs a different, distributed-atomic allocation scheme. +const ( + counterPrefix = "counter:" + taskCounterID = counterPrefix + "task_id" + eventCounterID = counterPrefix + "event_id" + + // Legacy keys, read once by migrateCounters and never written again. + legacyTaskCounterID = "meta:task_id_counter" + legacyEventCounterID = "meta:event_id_counter" +) + +// migrateCounters seeds the counters from their pre-rename documents. +// +// The old documents are readable -- only writing them fails -- and the value +// in them is load-bearing: starting a fresh sequence at 1 would hand out IDs +// that already belong to live tasks and events. The old document is left in +// place because removing it is the operation that cannot succeed; scans skip +// it via isReservedKey. +// +// Runs at open, before any caller can allocate. A missing legacy counter is +// normal for a fresh install; any other read or write failure aborts opening +// the store so allocation cannot silently restart at one. +func (a *Adapter) migrateCounters(ctx context.Context) error { + migrate := func(db *sdk.DocDB, current, legacy string) error { + doc, err := db.Get(ctx, current) + if err == nil { + if next := intField(doc, "next_id"); next < 1 { + return fmt.Errorf("current counter %q has invalid next_id %d", current, next) + } + return nil // already migrated + } + if !errors.Is(err, sdk.ErrNotFound) { + return fmt.Errorf("read current counter %q: %w", current, err) + } + old, err := db.Get(ctx, legacy) + if errors.Is(err, sdk.ErrNotFound) { + return nil // fresh database, nothing to carry over + } + if err != nil { + return fmt.Errorf("read legacy counter %q: %w", legacy, err) + } + next := intField(old, "next_id") + if next < 1 { + return fmt.Errorf("legacy counter %q has invalid next_id %d", legacy, next) + } + // A new document, so no _rev is carried across from the old one. + if _, err := db.Put(ctx, sdk.Doc{sdk.FieldID: current, "next_id": next}); err != nil { + return fmt.Errorf("write current counter %q: %w", current, err) + } + return nil + } + if err := migrate(a.tasks, taskCounterID, legacyTaskCounterID); err != nil { + return err + } + return migrate(a.events, eventCounterID, legacyEventCounterID) +} + // nextTaskID atomically reads and increments the task ID counter. // Must be called under a.mu. func (a *Adapter) nextTaskID(ctx context.Context) (int64, error) { - return a.nextCounter(ctx, a.tasks, "meta:task_id_counter") + return a.nextCounter(ctx, a.tasks, taskCounterID, legacyTaskCounterID) } // nextEventID atomically reads and increments the event ID counter. // Must be called under a.mu. func (a *Adapter) nextEventID(ctx context.Context) (int64, error) { - return a.nextCounter(ctx, a.events, "meta:event_id_counter") + return a.nextCounter(ctx, a.events, eventCounterID, legacyEventCounterID) } // nextCounter implements the read-modify-write for a counter doc. +// If eager migration failed, it retries from the legacy counter rather than +// restarting at one and reissuing an existing ID. // Must be called under a.mu so that no two callers race on the _rev. -func (a *Adapter) nextCounter(ctx context.Context, db *sdk.DocDB, metaKey string) (int64, error) { - doc, err := db.Get(ctx, metaKey) +func (a *Adapter) nextCounter(ctx context.Context, db *sdk.DocDB, counterID, legacyID string) (int64, error) { + doc, err := db.Get(ctx, counterID) + if errors.Is(err, sdk.ErrNotFound) { + return initializeCounter(ctx, db, counterID, legacyID) + } if err != nil { - if errors.Is(err, sdk.ErrNotFound) { - // First use: initialise to 2 (next call returns 1). - doc = sdk.Doc{sdk.FieldID: metaKey, "next_id": int64(2)} - if _, err := db.Put(ctx, doc); err != nil { - return 0, err - } - return 1, nil - } return 0, err } next := intField(doc, "next_id") + if next < 1 { + return 0, fmt.Errorf("nell: counter %q has invalid next_id %d", counterID, next) + } doc["next_id"] = next + 1 if _, err := db.Put(ctx, doc); err != nil { return 0, err @@ -975,6 +1093,29 @@ func (a *Adapter) nextCounter(ctx context.Context, db *sdk.DocDB, metaKey string return next, nil } +func initializeCounter(ctx context.Context, db *sdk.DocDB, counterID, legacyID string) (int64, error) { + legacy, err := db.Get(ctx, legacyID) + if err == nil { + next := intField(legacy, "next_id") + if next < 1 { + return 0, fmt.Errorf("nell: legacy counter %q has invalid next_id %d", legacyID, next) + } + if _, err := db.Put(ctx, sdk.Doc{sdk.FieldID: counterID, "next_id": next + 1}); err != nil { + return 0, fmt.Errorf("nell: migrate counter %q: %w", legacyID, err) + } + return next, nil + } + if !errors.Is(err, sdk.ErrNotFound) { + return 0, fmt.Errorf("nell: read legacy counter %q: %w", legacyID, err) + } + + // First use: initialise to 2 (next call returns 1). + if _, err := db.Put(ctx, sdk.Doc{sdk.FieldID: counterID, "next_id": int64(2)}); err != nil { + return 0, err + } + return 1, nil +} + // ── Type-safe doc accessors ────────────────────────────────────────────────── // strField extracts a string from a Doc by key. Returns "" when missing. diff --git a/internal/nell/counter_repro_test.go b/internal/nell/counter_repro_test.go new file mode 100644 index 000000000..0968f8332 --- /dev/null +++ b/internal/nell/counter_repro_test.go @@ -0,0 +1,472 @@ +package nell + +import ( + "errors" + "path/filepath" + "strings" + "testing" + + nell "github.com/samcharles93/NellDB" + "github.com/samcharles93/NellDB/logstore" + "github.com/samcharles93/NellDB/sdk" + + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/store" +) + +// TestCountersSurviveReopen reproduces a total dispatch outage. +// +// The adapter's auto-increment counters live at "meta:task_id_counter" and +// "meta:event_id_counter". The SDK reserves the "meta:" prefix for its own +// bookkeeping (meta:clock, meta:vector) and skips those ids when reindex() +// rebuilds the in-memory rev cache on open. The record itself is still in the +// log, so after a restart Get returns the counter doc complete with its _rev +// while the rev cache has no entry for it -- and DocDB.putIn rejects exactly +// that combination ("incomingRev != \"\" && !exists") with ErrConflict. +// +// The effect is permanent and survives restarts: every EnqueueIssue and every +// InsertEvent fails, so no task is ever written and no work is dispatched. +func TestCountersSurviveReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "archie.db") + + first, err := OpenStore(path, "test-node") + if err != nil { + t.Fatal(err) + } + firstEventID, err := first.InsertEvent(t.Context(), events.Event{Kind: "test", Detail: "first"}) + if err != nil { + t.Fatalf("first InsertEvent on a fresh store: %v", err) + } + if firstEventID != 1 { + t.Fatalf("first event ID = %d, want 1 from a fresh store", firstEventID) + } + if _, err := first.EnqueueIssue(t.Context(), "acme", "app", 1, "one", "", "", ""); err != nil { + t.Fatalf("first EnqueueIssue on a fresh store: %v", err) + } + firstTask := mustTaskByIssue(t, first, "acme", "app", 1) + if firstTask.ID != 1 { + t.Fatalf("first task ID = %d, want 1 from a fresh store", firstTask.ID) + } + if err := first.Close(); err != nil { + t.Fatal(err) + } + + // Reopen, exactly as a daemon restart does. + second, err := OpenStore(path, "test-node") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = second.Close() }) + + secondEventID, err := second.InsertEvent(t.Context(), events.Event{Kind: "test", Detail: "after restart"}) + if err != nil { + if errors.Is(err, sdk.ErrConflict) { + t.Fatalf("InsertEvent after reopen returned ErrConflict: the event log is permanently unwritable: %v", err) + } + t.Fatalf("InsertEvent after reopen: %v", err) + } + if secondEventID != 2 { + t.Fatalf("second event ID = %d, want 2 (sequence must continue across reopen, not restart)", secondEventID) + } + + if _, err := second.EnqueueIssue(t.Context(), "acme", "app", 2, "two", "", "", ""); err != nil { + if errors.Is(err, sdk.ErrConflict) { + t.Fatalf("EnqueueIssue after reopen returned ErrConflict: no task can ever be queued again: %v", err) + } + t.Fatalf("EnqueueIssue after reopen: %v", err) + } + secondTask := mustTaskByIssue(t, second, "acme", "app", 2) + if secondTask.ID != 2 { + t.Fatalf("second task ID = %d, want 2 (sequence must continue across reopen, not restart)", secondTask.ID) + } + + // Both events must survive: a sequence that restarted at 1 would have + // overwritten event:1 via the same "event:" key, and EventsSince + // would return one event instead of two. + got, err := second.EventsSince(t.Context(), 0, 10) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 { + t.Fatalf("EventsSince returned %d events, want 2 (the pre-reopen event must not be overwritten)", len(got)) + } + if got[0].ID != 1 || got[0].Detail != "first" || got[1].ID != 2 || got[1].Detail != "after restart" { + t.Fatalf("events after reopen = %+v, want IDs 1 and 2 with their original details", got) + } +} + +func mustTaskByIssue(t *testing.T, st store.TaskStore, owner, repo string, number int) *store.Task { + t.Helper() + task, err := st.TaskByIssue(t.Context(), owner, repo, number) + if err != nil { + t.Fatal(err) + } + if task == nil { + t.Fatalf("TaskByIssue(%s, %s, %d) returned nothing", owner, repo, number) + } + return task +} + +// TestCounterMigrationContinuesSequence covers the upgrade path for a database +// written before the counters moved off the "meta:" prefix. +// +// The old document's next_id is load-bearing: restarting the sequence at 1 +// would hand out IDs that already belong to live tasks, so two different tasks +// would answer to the same /approve. The old document cannot be rewritten -- +// that is the failure this whole change exists to fix -- so migration reads it +// and seeds the new key. +func TestCounterMigrationContinuesSequence(t *testing.T) { + const seededNextID = 42 + + path := filepath.Join(t.TempDir(), "archie.db") + + // Seed a log in the pre-rename shape. A first Put carries no _rev, which + // is the one write to a "meta:" document that still succeeds. + seed, err := logstore.OpenLog(path, "test-node") + if err != nil { + t.Fatal(err) + } + legacy := sdk.New(seed, "test-node", "tasks") + if _, err := legacy.Put(t.Context(), sdk.Doc{ + sdk.FieldID: "meta:task_id_counter", + "next_id": int64(seededNextID), + }); err != nil { + t.Fatal(err) + } + if err := seed.Close(); err != nil { + t.Fatal(err) + } + + st, err := OpenStore(path, "test-node") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + + if _, err := st.EnqueueIssue(t.Context(), "acme", "app", 7, "seven", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := st.TaskByIssue(t.Context(), "acme", "app", 7) + if err != nil { + t.Fatal(err) + } + if task == nil { + t.Fatal("TaskByIssue returned nothing for the task just enqueued") + } + if task.ID != seededNextID { + t.Errorf("task ID = %d, want %d carried over from the pre-rename counter", task.ID, seededNextID) + } +} + +func TestCounterMigrationFailurePreventsStoreOpening(t *testing.T) { + tests := []struct { + name string + legacyID string + currentID string + collection string + }{ + {name: "task counter", legacyID: legacyTaskCounterID, currentID: taskCounterID, collection: "tasks"}, + {name: "event counter", legacyID: legacyEventCounterID, currentID: eventCounterID, collection: "events"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + base := nell.NewMemoryStore("test-node") + t.Cleanup(func() { _ = base.Close() }) + legacy := sdk.New(base, "test-node", tc.collection) + if _, err := legacy.Put(t.Context(), sdk.Doc{ + sdk.FieldID: tc.legacyID, + "next_id": int64(42), + }); err != nil { + t.Fatal(err) + } + + // The current counter must be readable (NotFound is fine) so the + // migration reaches the write; only the write of the new key fails. + store := &failCounterMigrationStore{Store: base, failPutID: tc.currentID} + adapter, err := openAdapter(store, "test-node") + if err == nil { + _ = adapter.Close() + t.Fatal("openAdapter returned nil error after counter migration failed") + } + if !strings.Contains(err.Error(), "write current counter") { + t.Fatalf("openAdapter error = %v, want the migration write to fail", err) + } + if adapter != nil { + t.Fatal("openAdapter returned a usable adapter after counter migration failed") + } + }) + } +} + +// TestCounterMigrationReadFailurePreventsStoreOpening pins the fail-closed +// behaviour for reads, not just the migration write: if the current or legacy +// counter cannot be read, the store must not open and start allocating from a +// fresh sequence. +func TestCounterMigrationReadFailurePreventsStoreOpening(t *testing.T) { + for _, tc := range []struct { + name string + failID string + }{ + {name: "current counter read", failID: taskCounterID}, + {name: "legacy counter read", failID: legacyTaskCounterID}, + } { + t.Run(tc.name, func(t *testing.T) { + base := nell.NewMemoryStore("test-node") + t.Cleanup(func() { _ = base.Close() }) + + store := &failCounterMigrationStore{Store: base, failGetID: tc.failID} + adapter, err := openAdapter(store, "test-node") + if err == nil { + _ = adapter.Close() + t.Fatalf("openAdapter succeeded despite an injected %s failure", tc.failID) + } + if !strings.Contains(err.Error(), "read") { + t.Fatalf("openAdapter error = %v, want the counter read to fail", err) + } + if adapter != nil { + t.Fatal("openAdapter returned a usable adapter after a counter read failed") + } + }) + } +} + +// TestInvalidLegacyCounterPreventsStoreOpening: a legacy counter whose +// next_id is not a positive integer is corrupt and must refuse to open rather +// than hand out IDs that are already live. +func TestInvalidLegacyCounterPreventsStoreOpening(t *testing.T) { + base := nell.NewMemoryStore("test-node") + t.Cleanup(func() { _ = base.Close() }) + legacy := sdk.New(base, "test-node", "tasks") + if _, err := legacy.Put(t.Context(), sdk.Doc{ + sdk.FieldID: legacyTaskCounterID, + "next_id": int64(0), + }); err != nil { + t.Fatal(err) + } + + adapter, err := openAdapter(base, "test-node") + if err == nil { + _ = adapter.Close() + t.Fatal("openAdapter accepted a legacy counter with next_id < 1") + } +} + +// TestMalformedCurrentCounterFailsAllocation: a corrupted current counter +// (doc exists, but next_id is missing or not positive) must fail allocation +// with an error instead of emitting a zero/negative task ID. +func TestMalformedCurrentCounterFailsAllocation(t *testing.T) { + st := OpenMemory("test-node") + t.Cleanup(func() { _ = st.Close() }) + + adapter, ok := st.(*Adapter) + if !ok { + t.Fatal("OpenMemory returned a non-Adapter store") + } + if _, err := adapter.tasks.Put(t.Context(), sdk.Doc{ + sdk.FieldID: taskCounterID, + "next_id": int64(0), + }); err != nil { + t.Fatal(err) + } + + if _, err := st.EnqueueIssue(t.Context(), "acme", "app", 1, "one", "", "", ""); err == nil { + t.Fatal("EnqueueIssue succeeded with a malformed counter; it must fail rather than emit an invalid ID") + } +} + +// TestMalformedCurrentCounterPreventsStoreOpening: a persisted database whose +// current counter is already corrupt must fail closed at open, before any +// caller can allocate from it. +func TestMalformedCurrentCounterPreventsStoreOpening(t *testing.T) { + path := filepath.Join(t.TempDir(), "archie.db") + seedLegacyCounters(t, path, map[string]int64{ + taskCounterID: 0, + }) + + if _, err := OpenStore(path, "test-node"); err == nil { + t.Fatal("OpenStore accepted a current counter with next_id < 1") + } +} + +// TestCounterMigrationCoversBothCountersAndReopens checks the full upgrade +// path: both sequences carry forward, the legacy documents stay untouched, +// and a second reopen is a no-op rather than a re-migration. +func TestCounterMigrationCoversBothCountersAndReopens(t *testing.T) { + path := filepath.Join(t.TempDir(), "archie.db") + seedLegacyCounters(t, path, map[string]int64{ + legacyTaskCounterID: 42, + legacyEventCounterID: 100, + }) + + first, err := OpenStore(path, "test-node") + if err != nil { + t.Fatal(err) + } + if _, err := first.EnqueueIssue(t.Context(), "acme", "app", 7, "seven", "", "", ""); err != nil { + t.Fatal(err) + } + if task := mustTaskByIssue(t, first, "acme", "app", 7); task.ID != 42 { + t.Fatalf("task ID = %d, want 42 carried over from the pre-rename task counter", task.ID) + } + if id, err := first.InsertEvent(t.Context(), events.Event{Kind: "test", Detail: "migrated"}); err != nil { + t.Fatal(err) + } else if id != 100 { + t.Fatalf("event ID = %d, want 100 carried over from the pre-rename event counter", id) + } + adapter, ok := first.(*Adapter) + if !ok { + t.Fatal("OpenStore returned a non-Adapter store") + } + assertCounterDoc(t, adapter, "tasks", taskCounterID, 43) + assertCounterDoc(t, adapter, "events", eventCounterID, 101) + // Legacy documents are inert but must not be rewritten or deleted. + assertCounterDoc(t, adapter, "tasks", legacyTaskCounterID, 42) + assertCounterDoc(t, adapter, "events", legacyEventCounterID, 100) + if err := first.Close(); err != nil { + t.Fatal(err) + } + + second, err := OpenStore(path, "test-node") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = second.Close() }) + if _, err := second.EnqueueIssue(t.Context(), "acme", "app", 8, "eight", "", "", ""); err != nil { + t.Fatal(err) + } + if task := mustTaskByIssue(t, second, "acme", "app", 8); task.ID != 43 { + t.Fatalf("task ID after second reopen = %d, want 43 (migration must be idempotent)", task.ID) + } +} + +func seedLegacyCounters(t *testing.T, path string, counters map[string]int64) { + t.Helper() + seed, err := logstore.OpenLog(path, "test-node") + if err != nil { + t.Fatal(err) + } + tasks := sdk.New(seed, "test-node", "tasks") + events := sdk.New(seed, "test-node", "events") + for id, next := range counters { + db := tasks + switch id { + case legacyEventCounterID, eventCounterID: + db = events + } + if _, err := db.Put(t.Context(), sdk.Doc{sdk.FieldID: id, "next_id": next}); err != nil { + t.Fatal(err) + } + } + if err := seed.Close(); err != nil { + t.Fatal(err) + } +} + +func assertCounterDoc(t *testing.T, a *Adapter, collection, id string, wantNext int64) { + t.Helper() + var db *sdk.DocDB + switch collection { + case "tasks": + db = a.tasks + case "events": + db = a.events + default: + t.Fatalf("unknown collection %q", collection) + } + doc, err := db.Get(t.Context(), id) + if err != nil { + t.Fatalf("Get(%q, %q): %v", collection, id, err) + } + if next := intField(doc, "next_id"); next != wantNext { + t.Errorf("counter %s:%s next_id = %d, want %d", collection, id, next, wantNext) + } +} + +type failCounterMigrationStore struct { + nell.Store + failGetID string // Get on this id returns an injected error ("" = never) + failPutID string // Put of this id returns an injected error once ("" = never) + failed bool +} + +func (s *failCounterMigrationStore) Put(incoming nell.Record) (bool, nell.Record, error) { + if !s.failed && incoming.ID == s.failPutID { + s.failed = true + return false, nell.Record{}, errors.New("injected counter migration failure") + } + return s.Store.Put(incoming) +} + +func (s *failCounterMigrationStore) Get(collection, id string) (nell.Record, error) { + if id == s.failGetID { + return nell.Record{}, errors.New("injected counter read failure") + } + return s.Store.Get(collection, id) +} + +// TestTasksOwnedByCounterAreVisible guards the scan filter's blast radius. +// +// Task keys are "::", so matching bookkeeping documents by +// a "counter:" prefix would also match every task in a repository owned by +// "counter". EnqueueIssue would report success and the task would then be +// invisible to ClaimNext, Tasks and StatusCounts: never run, never re-enqueued, +// no error anywhere. +func TestTasksOwnedByCounterAreVisible(t *testing.T) { + st := OpenMemory("test-node") + t.Cleanup(func() { _ = st.Close() }) + + if _, err := st.EnqueueIssue(t.Context(), "counter", "app", 1, "counter-owned", "", "", ""); err != nil { + t.Fatal(err) + } + + tasks, err := st.Tasks(t.Context(), 10) + if err != nil { + t.Fatal(err) + } + if len(tasks) != 1 { + t.Fatalf("Tasks() returned %d tasks, want the one just enqueued", len(tasks)) + } + + claimed, err := st.ClaimNext(t.Context()) + if err != nil { + t.Fatal(err) + } + if claimed == nil { + t.Fatal("ClaimNext() skipped a queued task because its owner is named \"counter\"") + } +} + +// TestEnqueueIssuePersistsIdentity guards the field this adapter used to accept +// and silently drop, leaving every forge-polled task unattributed while the +// SQLite store recorded it. Multi-identity dispatch and per-identity listing +// both read it. +func TestEnqueueIssuePersistsIdentity(t *testing.T) { + tests := []struct { + name string + identity string + }{ + {name: "named identity", identity: "archie-two"}, + {name: "single-identity deployment", identity: ""}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + st := OpenMemory("test-node") + t.Cleanup(func() { _ = st.Close() }) + + if _, err := st.EnqueueIssue(t.Context(), "acme", "app", 3, "three", "", "", tc.identity); err != nil { + t.Fatal(err) + } + task, err := st.TaskByIssue(t.Context(), "acme", "app", 3) + if err != nil { + t.Fatal(err) + } + if task == nil { + t.Fatal("TaskByIssue returned nothing") + } + if task.Identity != tc.identity { + t.Errorf("Identity = %q, want %q", task.Identity, tc.identity) + } + }) + } +}