Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): serialize checkpoint restores with pending turns #10608

Closedsaphid(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/10608/headopened View on GitHub

Latest head 118cdf618b is rebased on current upstream main (b1e223e2b0), preserving this fix through the upstream rewind changes (#11338, #11358). All 424 focused tests pass; server, client-runtime, and contracts typechecks pass; scoped lint and format are clean.

What Changed

Checkpoint restore now changes only paths owned by the selected checkpoints instead of broadly cleaning the worktree. Capture, restore, and provider-start work are serialized so a restore cannot race a later turn into the filesystem or provider history.

The same checkpoint boundary preserves every accepted queued message through concurrent and failed reverts. Pending and provider-submitted starts carry durable message/turn correlation through projection rebuilds, restart, steering, acknowledgement/runtime reordering, stale unrelated session events, and skewed client timestamps. Revert now deletes only concrete turns beyond its checkpoint boundary, leaving queued placeholder identities and their accepted order intact. A request-scoped rendezvous handles the narrow case where a provider lifecycle completes before its durable start acknowledgement; legacy event replay does not enroll or accumulate historical turns.

Provider-accepted starts now keep retrying their durable acknowledgement without sending the prompt again. Startup cleanup attempts every submitted entry even if one correlated failure activity cannot be persisted. If any entry fails, it keeps the session nonterminal so that entry remains retryable on the next restart; successfully persisted entries still clear independently. When cleanup succeeds, restart persists each correlated failure before making the session terminal, and server/client projections clear only that submitted identity.

This is one dependent checkpoint/revert correctness boundary despite the 38-file diff. The original scoped Git fix exposed loss windows in the event, SQL projection, reactor, startup reconciliation, and client read-model paths; splitting those layers would knowingly leave accepted work deletable, reorderable, or replayable between PRs. The independent restart snapshot query remains split into stacked PR #10611.

Why

The Linux core nightly reproduced R08 deleting unrelated.txt, a user file outside the agent checkpoint. Focused red tests then reproduced checkpoint capture racing index restore, queued messages disappearing or changing order during revert, provider starts replaying after restart, stale terminal events clearing newer work, failed-turn files surviving restore, startup snapshot/subscription gaps, acknowledgement/runtime races permanently blocking later settle or revert commands, acknowledgement dispatch failing twice after one successful provider send, one failed startup cleanup preventing later submitted starts from clearing, and an acknowledged orphan remaining submitted after its session became terminal.

The repaired model quiesces checkpoint work before later provider starts, scopes Git restore to checkpoint-owned paths, and keeps request correlation state until the matching lifecycle or failure resolves it.

Rebase follow-up

At 118cdf618b the rebase preserved the fix through upstream's rewind feature (restoreFiles === false, rollbackConversation) and upstream migration numbering (this PR's correlation migration moved to 052). Six read-only Codex/Sol high review rounds on the evolving head surfaced and fixed: a scoped-restore arg drop, /compact-queued starts losing durable rows, orphaned submitted rows after dead sessions and settle-time acknowledgement, failed-send cleanup deleting unrelated accepted starts, late-acknowledged source plans staying actionable, preserved queued messages inflating the historical retention quota, nested-workspace cwd removal before git reset, non-live non-orphan threads skipping startup sweep, and a missing source-checkpoint fallback to target-only restore.

Known limitation: adapters whose sendTurn resolves only at prompt completion (Cursor, Antigravity) acknowledge at completion rather than at acceptance; the turn.started-to-acknowledgement window keeps upstream's pre-existing behavior for those providers. Closing it needs an adapter-level admission receipt and is a per-adapter contract decision.

Verification at 118cdf618b

  • 424/424 focused tests pass across 13 files covering Git checkpoint restore, checkpoint/provider reactors, projection pipeline and replay, startup reconciliation, settle/revert admission, server/client projectors, decider, snapshot query, imports, and contracts. The submission-rendezvous regression exhausts all 66 causally valid request A/B, acknowledgement A/B, running, and terminal orderings.
  • Scoped lint exits 0 (pre-existing unused-parameter warnings only); formatting clean; server, @t3tools/client-runtime, and @t3tools/contracts typechecks exit 0.
  • Independent review: six read-only Codex gpt-5.6-sol high rounds (codex exec -s read-only --ephemeral) on the evolving head; all actionable findings verified against source and fixed except the known limitation above. Round 6's remaining finding is that limitation.

Earlier verification

At prior head 92801988d rebased on 7220dfe2c949476eaa7d21eccbcd3a0ce0eddb49, 377/377 focused tests passed and a read-only Codex/Sol review found no actionable issues on that head.

The retained integration package at product head 0fcaff9445b5ca4ccaf4bef255419ec44e6f532d passed the production Linux core suite 16/16 with harness head f9c916b1d596375eaee1669b49cbaa861da1b582 and image digest sha256:9510753c8e09ead6321ac91c71d13dbbf1163ebe4de909f9eb0786d3a9cd2e41. This is intermediate product evidence—not proof for this PR head. The final exact-head multi-PR integration package, desktop artifact, and complete production receipt are missing, so this PR remains a draft.

This is a nonvisual filesystem/event-ordering repair. Screenshots and interaction video would not demonstrate the authoritative Git, persistence, or receipt boundaries and are not included.

Checklist

  • This PR is small and focused — it is one concern, but the required cross-layer invariant is large; see the dependency explanation above
  • I explained what changed and why
  • Before/after screenshots are not applicable to this nonvisual change
  • Interaction video is not applicable to this nonvisual change

Coordination trace: T3 thread 7ad33008-15c5-4aa9-829b-bb38e2fba8d7

Updated with SWE-2 in the Devin harness; independent review by Codex gpt-5.6-sol. Earlier work used GPT-6 in the Codex/T3 harness.

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration/decider.ts:108

      An orphaned pendingTurnStartMessageId permanently makes hasQueuedTurnStartForThread return true, so after a restart between persisting thread.turn-start-requested and reactor consumption, settle, snooze, and checkpoint-revert remain rejected until another user turn is created. The early return bypasses the age-bounded threadHasQueuedTurnStart fallback; remove it so orphaned pending work expires using the existing timestamp rule.

      -  if (thread.pendingTurnStartMessageId != null) return true;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/decider.ts around line 108:
      
      An orphaned `pendingTurnStartMessageId` permanently makes `hasQueuedTurnStartForThread` return `true`, so after a restart between persisting `thread.turn-start-requested` and reactor consumption, settle, snooze, and checkpoint-revert remain rejected until another user turn is created. The early return bypasses the age-bounded `threadHasQueuedTurnStart` fallback; remove it so orphaned pending work expires using the existing timestamp rule.
    3. Verified false positive. A persisted accepted start is durable work, not an age-expiring UI hint: expiring it from client timestamps would allow settle or revert to discard a request that the provider reactor still owes. The timestamp heuristic remains only a compatibility fallback for snapshots predating explicit pending state. Current head tracks each opted-in request until its matching acknowledgement or correlated failure, and legacy histories never enroll.

    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Layers/ProviderCommandReactor.ts:47

      Import this service module as a namespace at the service boundary, then acquire it through its public tag (for example, import * as CheckpointReactor from "../Services/CheckpointReactor.ts" and yield* CheckpointReactor.CheckpointReactor). This preserves the canonical service-module namespace rather than flattening the tag into the consumer.

      No longer relevant as of 8c05d9375b88bf7efb38df2aa98b7f3712fecea5

    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/bd1315a1ab43e61172859e3717ffc12cdb42b1dc/apps/server/src/persistence/Layers/ProjectionTurns.ts#L171

      Re-inserting a previously submitted placeholder through insertPendingProjectionTurn changes it to state = 'pending' and drops its submitted_turn_id, so after thread.reverted and a restart getPendingTurnStartByThreadId treats the already accepted message as new and submits it to the provider again. Preserve the submitted state and correlation when rebuilding this placeholder, or use a separate persistence path for submitted rows.

      Also found in 1 other location(s)

      apps/server/src/orchestration/Layers/ProjectionPipeline.ts:1662

      thread.reverted keeps a submitted placeholder but recreates it with insertPendingTurnStart, which discards its submitted_turn_id correlation and changes it back to pending. For an acknowledgement-first ordering (provider accepted message M as turn T, but no running lifecycle has been projected yet), a revert retains the placeholder then executes this branch. On restart, getPendingTurnStartByThreadId deliberately returns that now-pending row for startup reconciliation, so M can be submitted to the provider a second time despite already having been accepted.

      No longer relevant as of 8c05d9375b88bf7efb38df2aa98b7f3712fecea5

    6. saphid(GitHub profile, opens in a new tab)commented

      Verified and applied at current head 8c05d9375b88bf7efb38df2aa98b7f3712fecea5. ProviderCommandReactor.ts now imports the checkpoint service module as a namespace and acquires CheckpointReactor.CheckpointReactor. Scoped lint and the server typecheck both pass.

    7. saphid(GitHub profile, opens in a new tab)commented

      Verified real and fixed at current head 8c05d9375b88bf7efb38df2aa98b7f3712fecea5. Submitted placeholders retain both state = 'submitted' and submitted_turn_id; revert now leaves all pending/submitted placeholder rows in place and deletes only concrete turns beyond the checkpoint boundary, so it also preserves their durable row order. Focused submitted-correlation and reversed-clock revert regressions pass.

    8. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    9. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    10. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    11. Thanks for the PR. We're not taking changes to the orchestration and provider layers right now: that part of the server is being rewritten for V2, and merging into the current code would either conflict with or be thrown away by that work.

      Closing for now. If this is still an issue once V2 lands, please reopen (or open a fresh PR against the new code) and we'll take a proper look.

    12. juliusmarminge closed this

Sign in to join this conversation.