Skip to content

feat(groomer): persist typed before/after snapshots for applied mutations (#1736) - #1770

Open
itsmiso-ai wants to merge 5 commits into
mainfrom
courier/misospace/dispatch/issue-1736
Open

itsmiso-ai wants to merge 5 commits into
mainfrom
courier/misospace/dispatch/issue-1736

Conversation

@itsmiso-ai

@itsmiso-ai itsmiso-ai commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

What — Adds GroomingUndoSnapshot persistence for every landed grooming mutation (#1736).

Closes #1736

Why — the trust gap

We cannot currently reconstruct what a groomer run actually changed. appliedMutations summarizes the run and AuditLog records label transitions, but there is no durable, per-mutation before/after store that an operator can query to reverse a bad automated action. Without it, "the groomer changed my board" incidents are argued from run prose instead of facts. This adds the persistence layer only; interactive undo and operator-facing revert are #1739.

How it works (after the #1770 review rounds)

  • GroomingUndoSnapshot table — one row per (applicationKey, stepName) with typed columns, not one JSON blob:
    • stepName — "labels", "lane", or "reason:<column>" (one row per persisted reason column, so field identity survives even when identical text moves between columns)
    • labelsBefore[]/labelsAfter[], laneBefore/laneAfter, reasonBefore/reasonAfter — only the matching pair is populated
    • outcome — the application outcome at record time: applied, partial when a later step failed after this one landed, or noop for a landed local-only lane/reason move. The column never overstates the landing, on create or after a coalesce.
    • provenance — fixed hosted-groomer, reserved for future automation sources; it is also a continuity precondition for coalescing.
    • Migration ships with scripts/verify-add-grooming-undo-snapshot-migration.sql and a matching revert script.
  • Two writers, each recording only what it confirms:
    • The applier records the label-set row at its own confirmed GitHub write, carrying the real application outcome (buildUndoSnapshots(diff, landedLabels, outcome) in mutation-applier.ts). Same-key coalescing is safe for labels by construction: the application key hashes the evidence digest, so maintainer label movement between attempts produces a different key and a different row.
    • run.ts lands the run's Issue update in a narrow transaction behind a SELECT ... FOR UPDATE row lock — the pre-state is read under that lock, so it is exactly what the update replaced, and an unknown pre-state aborts the write (retryable) instead of recording an unknown as empty. The lane/reason:<column> rows are then recorded in a separate best-effort transaction (updateIssueWithUndoSnapshots): the optional undo record can never roll the ordinary Issue write back (a rolled-back lane write would be lost outright, because the finalized application's same-key retry takes the replay branch and does not repeat it). A snapshot failure leaves the dimension's undo unavailable — omitted, never fabricated. These rows carry the application outcome (applied/partial/noop); a landed move on a noop apply says noop.
    • A dimension is recorded only when the write actually moves it: a noop records nothing for dimensions it does not move, and a reason whose payload keeps the column records nothing for it.
  • Continuity-gated coalesce, not blind upsert: for an existing (applicationKey, stepName) row, the retry coalesces (keeps the original before, refreshes after/outcome/groomingRunId) only when the stored after equals the actual pre-state of this landing and the provenance matches (undoSnapshotCoalesces). A local-only column can move under the same key without moving the evidence digest (a maintainer edit), so the old blind after-side upsert could retain an obsolete undo target; when continuity is broken the row is deleted instead — undo for that dimension becomes unavailable rather than silently skipping the intervening decision.
  • Undo rows are never silently cascade-deleted, and never held forever: the guarded sync prune (Reconcile excluded-label issues at sync: prune zombie cache rows #1587, deleteIssue in issue-sync.ts) counts groomingUndoSnapshot among the live-state dependents and refuses the delete; POST /api/issues/prune-closed first expires snapshot rows older than its own cutoff on closed issues that are themselves past the cutoff (counted as expiredUndoSnapshots), then deletes only issues with groomingUndoSnapshots: { none: {} }, reporting skippedWithUndoSnapshots. A held issue is therefore reclaimed once its newest snapshot ages out, and the sync guard then stops refusing it too.

Invariants this change keeps, and every path that enforces them

  1. Only the two write-confirmed writers insert rows (applier at its confirmed GitHub label write; run.ts after the committed, locked Issue update), keyed by the groomer's applicationKey. Other writers of Issue.currentLane/reason columns (claim/status/operator routes) write no snapshots — the feature is scoped to hosted-groomer applications.
  2. A row only ever describes a landed write. Lane/reason rows are recorded after their transaction commits, from the pre-state read under the same FOR UPDATE lock that serialized the update; labels rows are recorded at the confirmed remote write. Failed/dry/observe applications persist nothing; a snapshot-store failure persists nothing rather than a half-truth.
  3. Coalesce requires continuity: before survives a same-key retry only while the retry continues the stored landing (undoSnapshotCoalesces: stored after == actual before at the locked read, same provenance); a broken chain deletes the row instead of absorbing it. labels is exempt because the key binds the evidence digest — documented at undoSnapshotAfterData.
  4. The optional undo record never breaks the ordinary write: the applier's labels recording is best-effort (a store failure cannot undo a landed write), and run.ts records snapshots outside the Issue transaction with the failure swallowed to a warning. A same-key retry of an application whose snapshot attempt failed finds the lane/reason writes already landed (the replay branch needs no repair).
  5. outcome is the application outcome at record time, on create and on coalesce (a step first recorded partial is promoted by the landing that completed it) — never a hardcoded applied, including on a noop application's landed local move.
  6. Live undo state is never silently cascade-deleted: POST /api/issues/prune-closed and the guarded sync prune (Reconcile excluded-label issues at sync: prune zombie cache rows #1587) are the only Issue-row deletion paths in the app; both refuse while snapshots exist, and the retention route is what ages snapshots out — explicitly, counted, and only for closed issues past the same cutoff.

Configuration — None. No env vars, no rollout mode; snapshots are a side effect of applied grooming.

Test plan

  • mutation-applier.test.ts: typed snapshot builder is labels-only and passes the application outcome through; no rows for noop, failed-write, or replay; a partial records outcome: "partial"; close-fail then resume keeps before, refreshes the after side, and promotes the outcome to the completing landing; undoSnapshotCoalesces accepts only a continuing after-side with matching provenance; the store update payload carries outcome and never before.
  • run.test.ts: run-level undo rows recorded from the row the write replaced (not selection), none for dry/observe/failed applications, per-field reason rows, unknown pre-state aborts, remote labels + failed local write leaves only the confirmed remote effect, FOR UPDATE order pinned; failure/coalescing round: noop lands its lane row with outcome: "noop"; an intervening local write invalidates the stored same-key row; a continuous resume coalesces (before kept, after/outcome/run refreshed); a provenance mismatch refuses to coalesce; an injected snapshot-store failure keeps the Issue update committed and a later exact-key replay preserves the transition with nothing fabricated.
  • undo-snapshots.integration.test.ts (new, RUN_DB_INTEGRATION=1): against real PostgreSQL — per-column rows from the actual pre-state, continuous same-key coalesce, intervening-write invalidation with the update still landing, and a proxy-injected snapshot-store failure leaving the committed Issue update intact with no rows.
  • prune-closed/route.test.ts: expiry runs before the delete with the closed-and-due filter, expiredUndoSnapshots is reported, and the issue delete still refuses any issue carrying snapshots.
  • issue-sync.test.ts: the excluded-reconcile guard counts groomingUndoSnapshot among the refused live-state dependents.
  • CI exercises the migration on a copy of the production schema with seeded Issues. Local validation on the integrated head c56e385: npm run test 7984 passed / 71 skipped (DB-gated, incl. the new file), npm run typecheck clean, npm run lint clean.

Related — Builds on #1354 (hosted groomer), #1325 (typed mutation diff), #1542 (observe mode). Parent #1715. Follow-on: #1739 (undo endpoint and UI).

)

The hosted groomer lets a plan run again (auto mode), but a run only stores
the labels it tried to write and the final outcome — not the exact pre-state an
operator would need to roll a change back. Record that pre-state.

Add a GroomingUndoSnapshot table: one typed before/after row per landed step of
an application whose outcome is `applied` or `partial` — the label set, the lane
(Issue.currentLane), and the verdict's persisted reason. Keyed by
(applicationKey, stepName) so a re-apply never duplicates a row, and nullable
before/after columns render an application with no captured pre-state as
"unavailable" rather than a wrong value.

The applier records snapshots at the single outcome choke point, so a noop, a
failed write, or a replay records nothing, and a dry-run/observe plan never
reaches it. The run threads the lane/reason before/after it owns (the applier
cannot see those columns); a mark_* verdict that carries no text keeps its prior
owned column, and the snapshot mirrors the write instead of the raw verdict.
Recording is best-effort: a store failure never undoes a landed write.

Additive migration only, and GroomingUndoSnapshot is classified as a guarded
dependent in the #1587 excluded-reconcile prune so a snapshot is never silently
cascade-deleted.

No behavior change to the plan, selection, or GitHub writes. The undo/preview
endpoint that reads these rows lands in a later issue.
its-saffron[bot]

This comment was marked as outdated.

@joryirving joryirving left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review at 54203da against #1736 and parent #1715. Saffron approved and 15/15 exact-head checks are green, but the persisted undo facts are not yet trustworthy.

  1. BLOCKING — lane/reason snapshots describe intended writes, not landed writes. mutation-applier.ts:1374 onward records them before returning to run.ts; the actual Issue update is after the application finalizes (run.ts:1470-1500, 1563-1566). If labels land but the Issue.update fails (or the process stops before it), the snapshot still claims lane/reason outcome=applied. Conversely the applier's noop path records nothing even though the fresh run still writes lane/reasons afterward. The new applier-only tests explicitly assert a lane snapshot without any local write, and a noop with no snapshot even for a lane transition. Capture the actual pre-state at the local writer, not candidate.currentLane from selection, and record only confirmed local changes, preferably atomically with that existing DB write using a narrow transaction/conditional update. If provenance or pre-state cannot be established, leave unavailable, not an applied snapshot. Respect the issue's no-undo-for-noop contract by distinguishing actual noops from real local-only effects (or explicitly mark local-only changes unsupported); do not change unrelated grooming behavior. Regression: real runner with successful remote labels and failed local update retains only confirmed remote effects, and successful local transition captures actual before/after; exercise a changed lane between selection and write.

  2. BLOCKING — scalar reasonBefore/reasonAfter loses the identity and values of the fields being inverted. run.ts:1119-1170 coalesces needsInfoReason, blockedReason and notReadyReason; buildUndoSnapshots compares strings only. For example blockedReason='waiting for X' -> needsInfoReason='waiting for X' clears blockedReason and sets needsInfoReason but emits no reason snapshot. If multiple previous columns exist, only one is captured. The stored pair cannot distinguish these states or restore the exact touched fields. Store the bounded typed before/after reason tuple or per-field snapshots with field identity, using the actual Issue update data (including exact null/unchanged semantics). A null/missing read is unavailable, not evidence of three nulls. Test same-text field transition, legacy multiple populated fields, clearing reasons and failed pre-state read.

  3. Partial/retry fidelity: the aggregate labels row keyed by (applicationKey, 'labels') is insert-only. A partial attempt can land the initial label set and then fail later (e.g. close/done_label); a same-key resume can land further label effects while skipDuplicates retains only the earlier post-state. Demonstrate that the original before and confirmed later effects remain accurately represented, or explicitly mark ambiguous/unsupported partial groups unavailable. Do not claim full inverse coverage from an outdated snapshot. Keep this scoped to the existing application ledger and confirmed reversible metadata; no new undo endpoint or generic event framework.

Add real run-level applied/failed/observe coverage (Saffron also noted missing observe coverage) and existing-data migration coverage requested by #1736. No local tests run. The issue's purpose is exact, undo-consumable facts, so the first two are correctness blockers even though no undo consumer ships yet.

…n field (#1770 review)

The first cut recorded lane/reason snapshots inside the applier from a
selection-time context, so the persisted facts described intended writes:
labels could land while the later Issue.update failed, and an applier
noop recorded nothing even though the run still moved the lane. A scalar
reasonBefore/reasonAfter also collapsed the three reason columns into
one coalesced text, losing field identity, and the insert-only labels
row kept a stale post-state across a partial-then-completed retry.

- run.ts now lands its Issue update and the lane/reason snapshots in one
  narrow transaction: the pre-state is read at the write, only changed
  dimensions are recorded, and an unreadable pre-state aborts the write
  instead of recording an unknown as an empty one.
- reason snapshots are per-column rows (reason:<column>) derived from the
  real update payload, so an identical text moving between columns is
  two rows and legacy multi-populated rows clear field-identified.
- the applier records only its own confirmed label write; the snapshot
  row is upserted keyed by (applicationKey, stepName), refreshing the
  after side so the before stays the original pre-state.
- run-level coverage: lane move vs selection state, noop-with-lane-move,
  field identity, remote-landed/local-failed, failed pre-read, dry-run
  and observe silence; partial-retry refresh at the applier; CI
  existing-data migration exercise for the new table.
@itsmiso-ai

Copy link
Copy Markdown
Collaborator Author

Review round addressed in 5623efa (head pushed, verified git ls-remote matches).

1. Intended-vs-landed snapshots (BLOCKING) — lane/reason recording moved out of the applier entirely. run.ts now lands the Issue update and the lane/reason snapshot rows in one narrow transaction (updateIssueWithUndoSnapshots): pre-state is read in-transaction, only dimensions the update actually changed are written, an unreadable pre-state aborts the write (retryable) rather than recording an unknown as empty. The applier keeps only the labels dimension, recorded at its own confirmed GitHub write. The selection-time candidate.currentLane guess is gone. Tests: lane move vs selection state; noop application with a real lane move (previously recorded nothing); remote labels landed + local update failed → only the confirmed remote effect remains.

2. Scalar reason losing field identity (BLOCKING) — reasons are now per-column rows, stepName = reason:<column>, derived from the real issueData payload (so the payload's set-or-keep null semantics are the snapshot's semantics). A blockedReason→needsInfoReason move of identical text records two rows; a legacy row with several populated columns records each cleared column separately. Tests cover all of those plus the failed pre-read.

3. Partial/retry fidelity — createMany(skipDuplicates) replaced with an upsert keyed by (applicationKey, stepName) whose update payload carries only the after side + groomingRunId; before is never rewritten, so a partial-then-resumed application shows the original pre-state and the final confirmed label set. Test: close-fail → resume run, asserting labelsBefore unchanged and labelsAfter following the done_label landing.

4. Run-level + migration coverage — added run-level applied/noop/failed/observe/dry-run cases above (the eval harness fake gained the transaction surface), and a CI existing-data exercise for the migration on a copy of the production schema (seeded Issues, rewind, first real deploy, verify back-fill-free create + surviving rows + unique/cascade behavior).

Local checks on the integrated head: npm test 7972 passed / 68 skipped / 1 todo; npm run typecheck clean; npm run lint clean. CI and the dedicated PR reviewer remain pending — not claimed green here.

its-saffron[bot]

This comment was marked as outdated.

@joryirving joryirving left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent re-review at 4b0bc0c. The original premature local snapshot and flattened reason defects are addressed by per-field rows and the locked transaction. The new migration and run-level coverage are welcome. Two remaining correctness blockers:

  1. The after-only upsert silently conflates discontinuous local writes on same-key partial resume. computeApplicationKey binds GitHub evidence and desired intent, not currentLane or the three local reason columns. A partial application commits lane A->B with snapshot A/B; an intervening maintainer lane write sets C without altering GitHub evidence; a same-key partial resume writes C->B. updateIssueWithUndoSnapshots locks and reads C correctly, but its upsert retains A and overwrites the run id, falsely asserting that the latest mutation replaced A. The final live B matches the snapshot, so drift-checking the final post-state cannot detect this lost intervening decision. Same problem for each reason field. Before coalescing a retry, require continuity (stored after equals actual new before and appropriate provenance), otherwise invalidate/mark unavailable the ambiguous dimension/group; do not silently retain an obsolete undo target. Test real same-key partial resume with intervening local lane/reason mutation and continuous resume. A narrow refusal/unavailable design is fine; no new undo engine.

  2. New transactional snapshot write failures can strand the ordinary groomer's local write: applyGroomingMutations finalizes the application as applied (including noop) before updateIssueWithUndoSnapshots; snapshot upsert failure now rolls back the whole Issue update. Next same-key run takes the existing replay branch, which explicitly does not replay lane/reason writes. The PR claims retryable rollback, but the replay path does not retry that local mutation. This introduces a new failure source for core grooming unrelated to the optional undo record. Preserve pre-existing local-write behavior on unavailable snapshot recording (omit/unavailable, never fabricate) or prove a narrowly fenced recovery path that cannot overwrite later operator decisions. Test injected snapshot upsert failure after remote application finalized, then exact-key retry; confirm truthful receipt and no lost lane/reason transition. Do not add broad recovery machinery simply for undo.

Also, label after-only upsert does not update outcome (partial remains partial after successful resume); document whether conservative partial is intentional or make outcome accurately describe its defined scope. Test actual store rather than only mock aggregation. No local tests run.

@itsmiso-ai

Copy link
Copy Markdown
Collaborator Author

Coordinator handoff (fix-pr round 2, head 4b0bc0c)

Settled decisions this round (all three review threads addressed in 4b0bc0c):

  1. Labels snapshot outcome — buildUndoSnapshots(diff, landedLabels, outcome) persists the real application outcome; a partial application's row says partial, never a hardcoded applied. Schema comment updated (comment-only; no migration change).
  2. Pre-state race — updateIssueWithUndoSnapshots takes SELECT ... FOR UPDATE on the Issue row as the transaction's first statement, so the lane/reason before is exactly what the update replaced under READ COMMITTED. Same lock mode/pattern as the guarded sync prune (Reconcile excluded-label issues at sync: prune zombie cache rows #1587). Deadlock surface is a single row acquired first; the applier path never locks the Issue row.
  3. prune-closed cascade — the bulk delete now filters groomingUndoSnapshots: { none: {} } (undo rows are live state, mirroring the deleteIssue guard) and the response reports skippedWithUndoSnapshots. Verified repo-wide: the sync prune and this route are the only Issue-row deletion paths.

Local checks (integrated head 4b0bc0c, cwd /workspace):

  • npm run typecheck — clean
  • npm run lint (--max-warnings=0) — clean
  • npm run test — 284 files / 7974 passed, 68 skipped (DB-gated *.integration.test.ts files run in the CI Database-integration job)
  • npx prisma validate — valid
  • Eval-harness fake client gained the $queryRaw no-op (in-memory rows need no locking); corpus suite green (106 passed)

New/updated coverage: builder outcome pass-through (applied + partial); partial application records outcome: "partial"; transaction order lock → pre-read → update with the lock mode pinned (incl. not FOR NO KEY UPDATE); prune-closed delete filter + skipped count.

Remaining external verification: CI on this head (15 exact-head checks re-run); the PR reviewer's re-review of the three threads; the migration verify job. PR body lists the invariants and every enforcing path.

its-saffron[bot]

This comment was marked as outdated.

@joryirving joryirving left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-confirming the independent review at exact current head 4b0bc0c after reading the coordinator handoff (issuecomment-7430430057) and the latest Saffron approval. The handoff addresses findings on the earlier 5623efa head, including row locking, prune-closed and partial outcome recording. Those fixes were already included in my review of 4b0bc0c. No new commit addresses review 6199856108. The two blockers remain: (1) same-key partial resume can coalesce discontinuous local lane/reason changes across an intervening operator edit, retaining an obsolete undo target even though final post-state matches; require continuity or mark the ambiguous snapshot unavailable; (2) snapshot upsert failure rolls back ordinary Issue update after application finalization, while exact-key replay does not recover lane/reason writes. Avoid introducing that new failure mode or demonstrate narrowly fenced recovery. Regression requirements and conservative partial-outcome note remain as in review 6199856108. Please address these rather than repeating the already resolved earlier findings. No local tests run.

…do recording, bounded snapshot retention (#1770 review)
@itsmiso-ai

Copy link
Copy Markdown
Collaborator Author

Handoff — re-review blockers at 4b0bc0c addressed in c56e385

Re-based onto current main (83e42c2) and settled both correctness blockers from the independent re-review, plus the outcome and retention minors and the new AI findings (each fixed in its own thread). No new undo engine; no new env vars.

Blocker 1 — silent conflation on same-key partial resume (lane/reason). updateIssueWithUndoSnapshots (run.ts) no longer blind-upserts. The record pass reads the stored (applicationKey, stepName) row and coalesces only when continuity holds — stored after equals the actual pre-state of this landing (captured under the FOR UPDATE lock) and the row carries the same provenance (undoSnapshotCoalesces, mutation-applier.ts). When continuity is broken by an intervening local write, the obsolete row is deleted — undo for that dimension becomes unavailable rather than silently retaining A as the undo target across a maintainer's C. labels stays continuity-exempt by construction (the key hashes the evidence digest, so same-key cannot span maintainer label movement) — documented at undoSnapshotAfterData. Tested: intervening-write invalidation, continuous resume keeping the original before while refreshing after/outcome/run, provenance refusal (run.test.ts), undoSnapshotCoalesces unit pairs (mutation-applier.test.ts), and against real PostgreSQL in the new undo-snapshots.integration.test.ts.

Blocker 2 — snapshot-write failure stranding the ordinary write. The lane/reason rows are now recorded after the locked Issue transaction commits, in their own best-effort transaction with the failure swallowed to a warning. The Issue update is never rolled back by optional undo state (that rollback lost the lane/reason move outright, since the finalized application's same-key retry replays without repeating local writes), and truthfulness is preserved in the direction that matters: rows are written only from a committed landing, and a failure records nothing — omitted, never fabricated. Tested: injected snapshot-store failure after remote finalization, then the exact-key replay — run succeeds, lane transition persists, no row fabricated (run.test.ts); proxy-injected real-store failure commits the Issue update with no rows (integration file). The locked transaction is also strictly narrower than before (lock + pre-state read + update), which is the answer recorded on the transaction-timeout info thread.

Minor — coalesce outcome and hardcoded applied. undoSnapshotAfterData carries outcome, so a labels/lane step first recorded partial is promoted by the landing that completed it (store test asserts the update payload has outcome and never before), and the noop-apply lane row now persists noop instead of applied (thread reply + test). Conservative staleness is gone rather than documented.

Settled decisions for the next reviewer: delete-on-discontinuity (invalidation = no row, since #1739 is the consumer and an absent row already means "undo unavailable"); expiry horizon for snapshots = the existing DISPATCH_CLOSED_ISSUE_RETENTION_DAYS cutoff, applied only to snapshots on closed issues that are themselves past it; snapshot failure = warn + omit (no durable failure ledger for an observation table).

Local validation receipts (head c56e385, this lane): npm run test 7984 passed / 71 skipped (DB-gated) / 1 todo · npm run typecheck clean · npm run lint clean. The new integration file runs in CI's database-integration job (RUN_DB_INTEGRATION=1); no Postgres in this lane, so its three scenarios carry mock-level twins locally. CI on this head was still queued at push time — explicitly pending, not claimed green. Independent review deferred to the dedicated PR reviewer per lane policy.

@its-saffron its-saffron Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

{"schema":"review-handoff/v1","review_id":"0dd3096706c8a97b","head_sha":"c56e385971f344235233fad0c929f90111052b3f","verdict":"request_changes","review_result":"issues","required_checks":"complete","items":[{"id":"6e95192d9e0b64055fe2d8a100a69d89ca4c251a7fe824158e1aa838f4fd7476","severity":"major","category":"bug","path":"src/lib/groomer/run.ts","line":1830,"message":"A best-effort snapshot transaction can commit lane/reason changes while permanently omitting their undo rows, violating #1736’s per-landed-step snapshot guarantee with no exact-key recovery path."}],"items_total":1,"items_truncated":false,"unresolved_requirement_ids":[],"unresolved_requirement_ids_total":0,"unresolved_requirement_ids_truncated":false,"unresolved_requirement_ids_source_total":0,"unresolved_required_checks":[],"unresolved_required_checks_total":0,"unresolved_required_checks_truncated":false,"unresolved_required_checks_source_total":0,"unresolved_review_obligations":[],"unresolved_review_obligations_total":0,"unresolved_review_obligations_truncated":false,"derived_obligation_state":null}

AI Automated Review

⚠️ Automated recommendation: REQUEST CHANGES

Full PR review.

Analysis engine: MiniMax-M3.1-Flash (anthropic) — primary route · pr-reviewer-action v3.11.2

Findings (1 major)

Severity Location Finding
⚠️ Major src/lib/groomer/run.ts:1830 A best-effort snapshot transaction can commit lane/reason changes while permanently omitting their undo rows, violating PR 1736’s per-landed-step snapshot guarantee with no exact-key recovery path.

Recommendation: request changes. The migration and normal snapshot paths are sound, but one reachable persistence failure leaves landed lane/reason changes without the undo rows required by PR 1736.

  • src/lib/groomer/run.ts:1830 catches snapshot-transaction failure after the Issue update has committed. The resulting run can land lane and reason mutations while permanently omitting their snapshots; because the application is already finalized, the exact-key replay does not repeat the local write or repair the missing rows. This violates PR 1736’s requirement that each landed step have a corresponding snapshot.

Linked Issue Fit

  • The typed schema, landed-step recording, observe/failed suppression, continuity handling, and additive migration satisfy the remaining PR 1736 criteria.
  • The failure-isolation behavior conflicts with the central acceptance criterion that every landed label/lane step have correct before/after snapshots.

Tool Harness Findings

  • The harness confirmed the FOR UPDATE pre-state read, continuity-gated coalescing, and post-commit snapshot transaction.
  • review migration for data loss risk — satisfied: the migration only creates a table, indexes, and an Issue foreign key; existing Issue rows are verified to survive.
  • test migration on a copy of production schema — satisfied: CI creates a compatibility copy, deploys the production-shaped schema, seeds representative rows, rewinds the migration record, and verifies the real deployment at the current head.

Outstanding Human Change Requests

  • @​joryirving's change request (4b0bc0c, head moved since) judged addressed at this head: The current head implements continuity-gated coalescing that deletes an obsolete same-key row when the stored after-side differs from the actual pre-state, and separates the best-effort snapshot transaction from the committed Issue update so snapshot failure cannot roll back the ordinary write (`sr…

Comment thread src/lib/groomer/run.ts
} else {
await tx.groomingUndoSnapshot.delete({ where });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Major (bug): A best-effort snapshot transaction can commit lane/reason changes while permanently omitting their undo rows, violating PR 1736’s per-landed-step snapshot guarantee with no exact-key recovery path.

Automated finding from AI PR review.

@its-saffron

its-saffron Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ This PR fix item has been marked as BLOCKED and needs human attention.

Reason: PR review: CHANGES_REQUESTED

Worker executions: 4

Enqueue rows: 88

Enqueues by lane:

  • NORMAL: 88

Final failure: coordinator failed

Last attempt: Independent review at 54203da against #1736 and parent #1715. Saffron approved and 15/15 exact-head checks are green, but the persisted undo facts are not yet trustworthy.

  1. BLOCKING — lane/reason snapshots describe intended writes, not landed writes. mutation-applier.ts:1374 onward records them before returning to run.ts; the actual Issue update is after the application finalizes (run.ts:1470-1500, 1563-1566). If labels land but the Issue.update fails (or the process stops before it), the snapshot still claims lane/reason outcome=applied. Conversely the applier's noop path records nothing even though the fresh run still writes lane/reasons afterward. The new applier-only tests explicitly assert a lane snapshot without any local write, and a noop with no snapshot even for a lane transition. Capture the actual pre-state at the local writer, not candidate.currentLane from selection, and record only confirmed local changes, preferably atomically with that existing DB write using a narrow transaction/conditional update. If provenance or pre-state cannot be established, leave unavailable, not an applied snapshot. Respect the issue's no-undo-for-noop contract by distinguishing actual noops from real local-only effects (or explicitly mark local-only changes unsupported); do not change unrelated grooming behavior. Regression: real runner with successful remote labels and failed local update retains only confirmed remote effects, and successful local transition captures actual before/after; exercise a changed lane between selection and write.

  2. BLOCKING — scalar reasonBefore/reasonAfter loses the identity and values of the fields being inverted. run.ts:1119-1170 coalesces needsInfoReason, blockedReason and notReadyReason; buildUndoSnapshots compares strings only. For example blockedReason='waiting for X' -> needsInfoReason='waiting for X' clears blockedReason and sets needsInfoReason but emits no reason snapshot. If multiple previous columns exist, only one is captured. The stored pair cannot distinguish these states or restore the exact touched fields. Store the bounded typed before/after reason tuple or per-field snapshots with field identity, using the actual Issue update data (including exact null/unchanged semantics). A null/missing read is unavailable, not evidence of three nulls. Test same-text field transition, legacy multiple populated fields, clearing reasons and failed pre-state read.

  3. Partial/retry fidelity: the aggregate labels row keyed by (applicationKey, 'labels') is insert-only. A partial attempt can land the initial label set and then fail later (e.g. close/done_label); a same-key resume can land further label effects while skipDuplicates retains only the earlier post-state. Demonstrate that the original before and confirmed later effects remain accurately represented, or explicitly mark ambiguous/unsupported partial groups unavailable. Do not claim full inverse coverage from an outdated snapshot. Keep this scoped to the existing application ledger and confirmed reversible metadata; no new undo endpoint or generic event framework.

Add real run-level applied/failed/observe coverage (Saffron also noted missing observe coverage) and existing-data migration coverage requested by #1736. No local tests run. The issue's purpose is exact, undo-consumable facts, so the first two are correctness blockers even though no undo consumer ships yet.

Decision needed: The worker ended this PR-fix attempt needing a human decision; review the diagnostic and decide how to proceed.

Evidence: coordinator failed

Latest note: coordinator failed

Posted automatically by Dispatch on 2026-12-05T03:57:50.087Z

@its-saffron its-saffron Bot added the needs-human Human input or decision is required. label Dec 5, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-human Human input or decision is required.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Persist typed before/after snapshots for applied groomer mutations

2 participants