Skip to content

core: preserve ghost snapshot tails and guard stalled compaction - #14563

Closed
charley-oai wants to merge 13 commits into
mainfrom
fix/compaction-race-retry-cap
Closed

charley-oai wants to merge 13 commits into
mainfrom
fix/compaction-race-retry-cap

Conversation

@charley-oai

@charley-oai charley-oai commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • preserve concurrent append-only GhostSnapshot tail items that land during local or remote compaction, merging them inside replace_compacted_history so the live history and persisted replacement_history stay aligned
  • add a stalled mid-turn auto-compaction safeguard so turns do not hot-loop forever when repeated successful compact-and-continue cycles never converge

Notes

  • The history merge is intentionally narrow: it only preserves an append-only GhostSnapshot tail, and only when the live history still extends the compacted prefix.
  • GhostSnapshot items are detached /undo metadata and are stripped from for_prompt(), so this preserves checkpoint state without reintroducing model-visible items that the compaction request never saw.
  • The ghost-snapshot merge happens while holding the same session-state lock that performs replace_history, which closes the final snapshot-to-replace gap called out in review.
  • After that merge, CompactedItem.replacement_history is refreshed from the final installed history so rollout reconstruction stays consistent with the live session.
  • The stalled safeguard is not about compaction request failure. Actual compaction failures already abort eagerly. This only handles repeated successful compact-and-continue cycles that stay over budget and still need follow-up.
  • When that safeguard trips, we emit explicit stalled auto-compaction telemetry (codex.auto_compaction.stalled) and fail the turn instead of looping indefinitely.

Testing

  • just fmt
  • cargo test -p codex-core (one unrelated local failure: tools::js_repl::tests::js_repl_imported_local_files_can_access_repl_globals due sandbox tempdir permissions while bootstrapping dotslash in this sandbox)

@charley-oai

Copy link
Copy Markdown
Contributor Author

@codex review this

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. You're on a roll.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Lordanakun

Copy link
Copy Markdown

Thanks for the quick turnaround on this, @charley-oai! Glad the root cause analysis in #13946 was useful. The PR description matches the two edge cases exactly — the tail-write race and the retry cap. Looking forward to seeing this merged. 🙌

@Lordanakun

Copy link
Copy Markdown

Read through the diff carefully — a few things I appreciate about this implementation:

mid_turn_compaction_attempts = 0 reset on success — this was the detail I missed in my original proposal. Resetting after a successful non-compaction iteration means the cap applies to consecutive failures, not lifetime attempts across unrelated token-limit events in the same turn. Much cleaner semantics.

append_concurrent_history_tail_if_append_only — factoring this out as a named, testable function (rather than inlining the prefix check) makes the intent self-documenting. The starts_with / extend_from_slice approach is simple and correct for the append-only contract.

compact_remote.rs borrow fix — binding the snapshot to history_snapshot before cloning into history keeps the owner alive for the later raw_items() borrow. Cleaner than the named-variable workaround I used when validating the build.

LGTM from a correctness standpoint. The regression test covering the concurrent tail merge is a nice addition too.

@Lordanakun

Copy link
Copy Markdown

Thanks @charley-oai for picking this up so quickly — great to see both findings translated into a fix.

On Finding 1 (race condition): The append_concurrent_history_tail_if_append_only approach is clean. Re-snapshotting after the model call and preserving the append-only tail handles the common case (subagent notifications, background events) without needing a full generation counter. The fallback to warn + skip on non-append-only mutations seems like the right tradeoff given how rare that shape is.

On Finding 2 (infinite loop): MAX_MID_TURN_COMPACTION_ATTEMPTS = 3 with a user-visible error message is exactly what we had in mind. The counter reset to 0 on a successful non-compacting iteration is a nice touch too.

One open question on Finding 3 (atomic persistence): replace_compacted_history still does memory-replace → persist-compacted → persist-context as three separate awaits. A crash between steps leaves memory and disk out of sync. Is there a plan to address this, or is it considered acceptable for now given that most users can recover by restarting the session? The concern is mainly for long-running agents where the desync could be harder to diagnose.

Thanks again for the fast turnaround!

@charley-oai
charley-oai force-pushed the fix/compaction-race-retry-cap branch from 8d13d68 to ce52fd9 Compare March 16, 2026 06:25
@charley-oai

Copy link
Copy Markdown
Contributor Author

@codex review this

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ce52fd94f6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread codex-rs/core/src/compact.rs Outdated
// Those entries are stripped from `for_prompt()`, so re-snapshot here to
// preserve an append-only ghost-snapshot tail without reintroducing
// model-visible items that were never compacted.
let latest_history_snapshot = sess.clone_history().await;

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.

P1 Badge Merge tail and replace history under one critical section

latest_history_snapshot is taken before replace_compacted_history, but replacement happens in a separate lock acquisition. If a ghost snapshot is appended in that gap, it is still lost, so concurrent tail writes are not actually preserved. The same TOCTOU pattern appears in both local and remote compaction paths (compact.rs and compact_remote.rs).

Useful? React with 👍 / 👎.

@Lordanakun

Copy link
Copy Markdown

Re: the P1 bot comment on TOCTOU

The finding is correct — there's still a narrow window between the re-snapshot (clone_history step 3) and replace_compacted_history (step 5) where a new ghost snapshot appended to live session history would be silently dropped.

The fix is to collapse those two steps into a single critical section. Instead of separate clone_history + replace_compacted_history calls, a new method like snapshot_and_replace_compacted_history could hold the inner lock for both:

// proposed addition to Session
pub(crate) async fn snapshot_and_replace_compacted_history(
    &self,
    mut new_history: Vec<ResponseItem>,
    base_history: &[ResponseItem],
) -> bool {
    let mut live = self.history.lock().await;
    let merged = append_concurrent_ghost_snapshot_tail_if_append_only(
        &mut new_history,
        base_history,
        live.raw_items(),
    );
    *live = HistoryLog::from(new_history);
    merged
}

Both compact.rs and compact_remote.rs would then replace the current two-step pattern with a single call, and the warn! logging can stay inside the helper unchanged.

One note on practical severity: the window is now much smaller (snapshot-to-replace, not snapshot-to-model-call-to-replace), so the P1 label feels slightly elevated for what's left. But making it atomic is clearly the right shape — it removes the race entirely rather than just shrinking it.

charley-oai added a commit that referenced this pull request Mar 16, 2026
Move ghost snapshot tail preservation into replace_compacted_history so the merge happens under the same session lock as history replacement and the persisted replacement history matches the live history.

Tests: just fmt
Tests: cargo test -p codex-core

Co-authored-by: Codex <[email protected]>
charley-oai added a commit that referenced this pull request Mar 16, 2026
Move ghost snapshot tail preservation into replace_compacted_history so the merge happens under the same session lock as history replacement and the persisted replacement history matches the live history.

Tests: just fmt
Tests: cargo test -p codex-core

Co-authored-by: Codex <[email protected]>
charley-oai added a commit that referenced this pull request Mar 16, 2026
Handle interrupted multi-agent status in tui_app_server so the SDK build stays exhaustive after rebasing onto main.

Tests: just fmt
Tests: cargo test -p codex-tui-app-server collab_resume_interrupted_snapshot
Tests: cargo build --bin codex

Co-authored-by: Codex <[email protected]>
@charley-oai
charley-oai force-pushed the fix/compaction-race-retry-cap branch from d2e333f to 97c69de Compare March 16, 2026 17:15
charley-oai added a commit that referenced this pull request Mar 16, 2026
charley-oai added a commit that referenced this pull request Mar 16, 2026
Move ghost snapshot tail preservation into replace_compacted_history so the merge happens under the same session lock as history replacement and the persisted replacement history matches the live history.

Tests: just fmt
Tests: cargo test -p codex-core

Co-authored-by: Codex <[email protected]>
charley-oai added a commit that referenced this pull request Mar 16, 2026
@charley-oai
charley-oai force-pushed the fix/compaction-race-retry-cap branch from 486a4cd to 3b9dd27 Compare March 16, 2026 18:52
charley-oai added a commit that referenced this pull request Mar 16, 2026
charley-oai added a commit that referenced this pull request Mar 16, 2026
charley-oai added a commit that referenced this pull request Mar 16, 2026
@charley-oai

Copy link
Copy Markdown
Contributor Author

@codex review this

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. Nice work!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

charley-oai and others added 3 commits March 16, 2026 20:43
Preserve append-only session history items that arrive during local or remote compaction before replacing compacted history, and stop mid-turn auto compaction after three attempts with a user-visible error.

Co-authored-by: Codex <[email protected]>
Rename the append-only compaction merge helper, switch it to a boolean success signal, and document the exact concurrency assumption.

Co-authored-by: Codex <[email protected]>
Explain the snapshot-to-replace race at both compaction call sites so the extra re-snapshot and append-only tail preservation logic is easier to review.

Co-authored-by: Codex <[email protected]>
charley-oai and others added 9 commits March 16, 2026 20:43
Narrow the compaction race fix to preserve only appended ghost snapshots, which are non-model-visible and can realistically arrive from detached background tasks while compaction is waiting.

Co-authored-by: Codex <[email protected]>
Make the mid-turn compaction cap explicit as a stalled auto-compaction safeguard with dedicated error text, telemetry, and regression coverage.

Co-authored-by: Codex <[email protected]>
Move ghost snapshot tail preservation into replace_compacted_history so the merge happens under the same session lock as history replacement and the persisted replacement history matches the live history.

Tests: just fmt
Tests: cargo test -p codex-core

Co-authored-by: Codex <[email protected]>
Narrow the compaction race fix to the concrete ghost-snapshot case.
Remove the conflict classification and warning path, and make
replace_compacted_history opportunistically preserve only an
append-only GhostSnapshot tail under the state lock.

Co-authored-by: Codex <[email protected]>
Add an inline comment explaining why replacement_history is refreshed
from the final in-memory items after the ghost snapshot tail merge.

Co-authored-by: Codex <[email protected]>
@charley-oai
charley-oai force-pushed the fix/compaction-race-retry-cap branch from f335c95 to 232ffcf Compare March 17, 2026 03:43
Add the required argument-name comment to the stalled auto-compaction
telemetry counter increment.

Co-authored-by: Codex <[email protected]>
@charley-oai charley-oai changed the title core: preserve compaction tail writes and cap retry loop core: preserve ghost snapshot tails and guard stalled compaction Mar 17, 2026
@charley-oai

Copy link
Copy Markdown
Contributor Author

Discussed with @aibrahim-oai, we actually think these edge cases should be rare enough that it's not worth adding code complexity for. However if you notice

  • mid-turn compaction retrying without limit
  • or, /undo not working due to GhostSnapshot being saved while compaction is running
    please let us know and we can revisit.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants