Repository navigation
feat(groomer): persist typed before/after snapshots for applied mutations (#1736) - #1770
itsmiso-ai wants to merge 5 commits into
Conversation
) 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.
joryirving
left a comment
There was a problem hiding this comment.
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.
-
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.
-
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.
-
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.
|
Review round addressed in 5623efa (head pushed, verified 1. Intended-vs-landed snapshots (BLOCKING) — lane/reason recording moved out of the applier entirely. 2. Scalar reason losing field identity (BLOCKING) — reasons are now per-column rows, 3. Partial/retry fidelity — 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: |
…une-closed (#1770 review)
joryirving
left a comment
There was a problem hiding this comment.
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:
-
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.
-
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.
Coordinator handoff (fix-pr round 2, head 4b0bc0c)Settled decisions this round (all three review threads addressed in 4b0bc0c):
Local checks (integrated head 4b0bc0c, cwd /workspace):
New/updated coverage: builder outcome pass-through ( 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. |
joryirving
left a comment
There was a problem hiding this comment.
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)
Handoff — re-review blockers at 4b0bc0c addressed in c56e385Re-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). 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 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 Local validation receipts (head c56e385, this lane): |
There was a problem hiding this comment.
{"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
Full PR review.
Analysis engine: MiniMax-M3.1-Flash (anthropic) — primary route · pr-reviewer-action v3.11.2
Findings (1 major)
| Severity | Location | Finding |
|---|---|---|
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:1830catches 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 UPDATEpre-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…
| } else { | ||
| await tx.groomingUndoSnapshot.delete({ where }); | ||
| } | ||
| } |
There was a problem hiding this comment.
Automated finding from AI PR review.
Reason: PR review: CHANGES_REQUESTED Worker executions: 4 Enqueue rows: 88 Enqueues by lane:
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.
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 |
What — Adds
GroomingUndoSnapshotpersistence for every landed grooming mutation (#1736).Closes #1736
Why — the trust gap
We cannot currently reconstruct what a groomer run actually changed.
appliedMutationssummarizes the run andAuditLogrecords 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)
GroomingUndoSnapshottable — 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 populatedoutcome— the application outcome at record time:applied,partialwhen a later step failed after this one landed, ornoopfor a landed local-only lane/reason move. The column never overstates the landing, on create or after a coalesce.provenance— fixedhosted-groomer, reserved for future automation sources; it is also a continuity precondition for coalescing.scripts/verify-add-grooming-undo-snapshot-migration.sqland a matching revert script.buildUndoSnapshots(diff, landedLabels, outcome)inmutation-applier.ts). Same-key coalescing is safe forlabelsby construction: the application key hashes the evidence digest, so maintainer label movement between attempts produces a different key and a different row.run.tslands the run's Issue update in a narrow transaction behind aSELECT ... FOR UPDATErow 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. Thelane/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 saysnoop.(applicationKey, stepName)row, the retry coalesces (keeps the originalbefore, refreshes after/outcome/groomingRunId) only when the storedafterequals 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.deleteIssueinissue-sync.ts) countsgroomingUndoSnapshotamong the live-state dependents and refuses the delete;POST /api/issues/prune-closedfirst expires snapshot rows older than its own cutoff on closed issues that are themselves past the cutoff (counted asexpiredUndoSnapshots), then deletes only issues withgroomingUndoSnapshots: { none: {} }, reportingskippedWithUndoSnapshots. 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
applicationKey. Other writers ofIssue.currentLane/reason columns (claim/status/operator routes) write no snapshots — the feature is scoped to hosted-groomer applications.FOR UPDATElock 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.beforesurvives a same-key retry only while the retry continues the stored landing (undoSnapshotCoalesces: storedafter== actual before at the locked read, same provenance); a broken chain deletes the row instead of absorbing it.labelsis exempt because the key binds the evidence digest — documented atundoSnapshotAfterData.outcomeis the application outcome at record time, on create and on coalesce (a step first recordedpartialis promoted by the landing that completed it) — never a hardcodedapplied, including on a noop application's landed local move.POST /api/issues/prune-closedand 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 recordsoutcome: "partial"; close-fail then resume keepsbefore, refreshes the after side, and promotes the outcome to the completing landing;undoSnapshotCoalescesaccepts only a continuing after-side with matching provenance; the store update payload carries outcome and neverbefore.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 UPDATEorder pinned; failure/coalescing round: noop lands its lane row withoutcome: "noop"; an intervening local write invalidates the stored same-key row; a continuous resume coalesces (beforekept,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,expiredUndoSnapshotsis reported, and the issue delete still refuses any issue carrying snapshots.issue-sync.test.ts: the excluded-reconcile guard countsgroomingUndoSnapshotamong the refused live-state dependents.npm run test7984 passed / 71 skipped (DB-gated, incl. the new file),npm run typecheckclean,npm run lintclean.Related — Builds on #1354 (hosted groomer), #1325 (typed mutation diff), #1542 (observe mode). Parent #1715. Follow-on: #1739 (undo endpoint and UI).