Repository navigation
feat(labeler): admin dead-letter retry and quarantine controls (W9.6 PR-3) - #2028
Conversation
…PR-3) Two admin-only endpoints act on the dead_letters status columns from PR-0: retry flips a new letter to retried, writes the resolving action, emits a dead-letter-retried event, and re-enqueues the job to the discovery queue on a deferred tail (the consumer's runKey dedup makes a double-drive converge); quarantine is a terminal reviewed state with no re-enqueue. Both guard on status='new' so a second concurrent action 409s rather than double-processing. The status health count now excludes resolved letters, a reviewer-visible list route paginates the queue, and the console gains a dead-letter view with admin-gated actions. Dead letters now persist the full discovery job so a retry can re-verify with the original cid. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
|
Scope checkThis PR changes 1,347 lines across 19 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
There was a problem hiding this comment.
Approach judgment
This is the right change, solving the right problem, in a way that fits EmDash's labeler architecture. W9.6 PR-3 wires the operator controls over the dead_letters status columns that PR-0 (migration 0005_operational_events.sql, already on the base branch) added — status (CHECK-constrained to new/retried/quarantined), resolved_at, resolved_by_action_id — with the matching idx_dead_letters_status index. Retry/quarantine are admin-only mutations through the existing guardMutation → commitMutation machinery (audit row + status='new'-guarded UPDATE + an ungated info operational event in one atomic db.batch), the read/list route is reviewer-gated with keyset pagination, and countDeadLetters correctly narrows to status='new'. The payload-deviation (writeDeadLetter now stores the full DiscoveryJob) is justified and self-contained: the only reader is the new readDeadLetterJob, the job is JSON-safe, and delete jobs carry cid: "" which isDiscoveryJob accepts, so delete dead letters remain retryable. The feature is backed by the approved RFC #694 and completes the W9.6 set; the code-only delta over PR-0's schema is the right scope.
What I checked
- At-most-once enqueue (T6). Traced both race shapes. Same-key replay:
guardMutationserves the stored descriptor and the handler returns it without re-deferring, so the enqueue runs once. Different-key concurrent race: both admins pass the guard and commit (distinctidempotency_key, no UNIQUE conflict), but only the winner'sWHERE status='new'UPDATE flips the row; both thendeferDeadLetterReenqueuewith their ownctx.actionId, and the loser's tail re-readsresolved_by_action_id(the winner's) and skips. Exactly onesendDiscoveryJob. The consumerrunKeydedup is the documented backstop. ✓ - Pre-commit rejections. Absent row (404 via
ReadGuardError) and already-resolved (409DEAD_LETTER_RESOLVED) throw beforecommitMutation, so a late/repeated request commits and enqueues nothing. ✓ - Authz. List route is reviewer-gated (
guardReadminRole: "reviewer"); the two actions arerequiredRole: "admin"and the path-id parse runs insideparseBody(after the role gate), so a non-admin is rejected before any id parsing. ✓ - Pagination.
id DESCkeyset on the monotonic autoincrement is a total order; cursor round-tripsid(used) +received_at(shape/validation only);limit+1fetch;parseCursorIdrejects non-positive/non-safe-integer; malformed cursor → 400. ✓ countDeadLettersnowWHERE status='new', served byidx_dead_letters_status. Test confirms retried/quarantined rows are excluded. ✓- Schema/FK.
resolved_by_action_id REFERENCES operator_actions(id)resolves within the batch (audit INSERT precedes the UPDATE). The loser's no-op UPDATE leavesresolved_by_action_iduntouched, so no orphan-FK risk. ✓ - Console.
DeadLetterActionsmirrors the establishedAutomationControlpattern (per-dialogulididempotency key reused across retries,onSuccessinvalidates both["dead-letters"]and["system-status"]— the latter matching the Dashboard's query key). The rawpayloadis excluded from serialization. ✓ - Types.
OperationalEventType(dead-letter-retried/-quarantined) andOperatorActionType(dlq-retry/dlq-quarantine) unions already include the new values. ✓ - Conventions. SQL is parameterized (no interpolation). i18n is n/a — the labeler console is deliberately un-localized (decision 2026-07-13) and the existing
Dashboard/Sidebar/AutomationControluse bare strings, so the new copy is consistent. Changeset is n/a (apps/labeleris unpublished). Both are correctly disclosed. ✓
One disclosed limitation I verified and agree with deferring
The PR description explicitly calls out, and I confirmed by tracing, the concurrent different-key two-admin race on one letter: the loser's commitMutation succeeds (distinct keys, no UNIQUE conflict), so its audit row + info event commit and it returns a 200 asserting "retried," even though its WHERE status='new' UPDATE matched zero rows and the winner is the one who flipped the row. The safety invariant (at-most-once enqueue) fully holds; the only effect is audit/event-accuracy for a two-admins-on-one-letter-in-the-same-moment case. Tightening it means either gating the event on the UPDATE match (touching PR-0's frozen operational-events.ts gate) or a post-commit winner re-read → 409. The author is deliberately folding this into the cross-PR incident-notification/audit-observability policy rather than settling it per-PR, which is a reasonable coherence call. I'm not filing it as a finding since it's already disclosed and consciously deferred; flagging it would only echo the PR description.
Conclusion
Clean, well-reasoned implementation of an approved feature, consistent with the W9.6 patterns and repo conventions, with good test coverage (happy paths, per-endpoint reviewer-403/unauth-401 zero-side-effect, the T6 rejections, exactly-one-enqueue, count exclusion, replay, and pagination). No bugs to fix.
ea31d76
into
feat/plugin-registry-labelling-service
What does this PR do?
W9.6 PR-3 — the admin-only dead-letter retry / quarantine controls, the final piece of W9.6. PR-0 added the
dead_lettersstatus columns (statusdefault'new',resolved_at,resolved_by_action_id); this PR wires the operator controls over them.POST /admin/api/dead-letters/:id/retry, admin-only): flips anewletter toretried, records the resolving action, and emits aninfodead-letter-retriedoperational event — all in onecommitMutationbatch with the audit row. A deferred tail then re-enqueues the letter's discovery job (off the response path); the consumer'srunKeydedup makes a double-drive converge, so a lost enqueue is recoverable by re-drivingretriedrows (the reconciliation sweep is out of scope, as the design notes)..../quarantine, admin-only): a terminal "reviewed, won't retry" flip toquarantinedwith adead-letter-quarantinedevent; no re-enqueue.status = 'new'— an already-resolved letter is a 409DEAD_LETTER_RESOLVEDrejected before any commit, so a late or repeated request commits and enqueues nothing. Under a concurrent race theWHERE status='new'UPDATE flips exactly once and the deferred tail re-readsresolved_by_action_id, so only the winner enqueues. Replay (same key) returns the stored descriptor without re-deferring.countDeadLettersnow filtersWHERE status = 'new', so retried/quarantined letters leave the/admin/api/statusdead-letter depth.id DESCkeyset,{items, nextCursor}); the actions are admin-only. The console gains a dead-letter queue view with admin-gated retry/quarantine buttons.Ingestion-path change (worth a look):
writeDeadLetternow persists the fullDiscoveryJobinstead of the bare jetstream record. A create/update dead letter's record carries no CID, so the old payload couldn't be faithfully re-verified on retry — the retry feature needs the whole job. It's code-only within the existing BLOB column; the only reader is the newreadDeadLetterJob, the job is all JSON-safe data (round-trips through bothJSONand the queue's structured clone), and it's public ATProto data (nothing sensitive in the blob).Adversarially reviewed by an independent Opus pass targeting the T6 races (sequential, concurrent, retry-vs-quarantine, replay), the payload deviation's round-trip, and authz: no blockers — the at-most-once-enqueue invariant holds under every constructed race. Two of its findings are addressed here: an observability log when a retry's payload doesn't decode (so a skipped re-enqueue isn't silent — matters only for any pre-PR staging row, since the labeler has never hit
main), and a reverted oxfmt-only churn hunk. Its INFO on replay asymmetry (a lost enqueue is recoverable only by the unbuilt sweep, not by API replay) is a conscious, design-consistent choice.For the batched decision (non-blocking)
One adversary finding I've deliberately not changed, because it's the same audit/event-accuracy theme as two open questions on #2026 and #2027 and should be decided as one policy: in a concurrent two-admin race on the same letter, the loser commits an audit row + an
infooperational event and returns a 200 asserting a status its zero-row UPDATE never applied. The safety invariant fully holds (at-most-once enqueue; the consumer dedups regardless), and it takes two admins acting on one letter within the same moment — but the loser's response and its (info-severity, non-paging) event misrepresent reality. Tightening it means either gating the event on the UPDATE matching (a change to PR-0's frozenoperational-events.tsgate) or a post-commit winner re-read → 409. I'll fold this into the incident-notification/audit-observability decisions to settle coherently rather than per-PR.W9.6 is feature-complete with this PR: takedown + publisher-compromised + ceremony (PR-1), the operational-event/outbox subsystem (PR-0), pause/resume (PR-2), and DLQ retry/quarantine (PR-3).
Stacked on the integration branch (W9.5 + PR-0/1/2 merged). Targets
feat/plugin-registry-labelling-service. Related to #1909 and RFC #694.Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.i18n n/a — the labeler console is deliberately not localized (decision 2026-07-13). Changeset n/a —
apps/labeleris a private, unpublished Worker app.AI-generated code disclosure
Screenshots / test output
pnpm --filter @emdash-cms/labeler test: worker 538 pass (28 files; new DLQ suite covers retry/quarantine happy paths, per-endpoint reviewer-403/unauth-401 zero-side-effect + reviewer-can-list, the T6 rejections, exactly-one-enqueue,countDeadLettersexclusion, replay, and pagination), console 35 pass (new dead-letter view + actions)console:buildsucceeds; lint: 0 diagnostics inapps/labelerhttps://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM