Skip to content

[codex] add MongoDB thread store and session migration - #31175

Closed
mikhail-oai wants to merge 2 commits into
mainfrom
codex/mongo-session-store
Closed

mikhail-oai wants to merge 2 commits into
mainfrom
codex/mongo-session-store

Conversation

@mikhail-oai

@mikhail-oai mikhail-oai commented Jul 5, 2026 •

Copy link
Copy Markdown

Summary

  • add an experimental MongoDB-backed thread store selected through experimental_thread_store = { type = "mongodb", ... }
  • add codex sessions migrate-to-mongo for streaming active and archived rollout migration with progress, live warnings, verification, namespace clearing, and bounded --jobs concurrency
  • namespace Mongo records by canonical Codex home and add indexes for thread lookup, listing, search, ordered rollout history, and compaction checkpoint lookup
  • externalize raw tool outputs larger than 4 MiB into content-addressed files under the Codex home while retaining indexed JSON rollout objects in Mongo
  • make Mongo authoritative when selected, without SQLite or local-rollout fallbacks
  • allow app-server resume responses without a local rollout path for Mongo-backed threads
  • derive migrated thread previews from the first usable user message
  • optimize Mongo resume by loading the latest valid compaction checkpoint plus its surviving tail, while retaining full history for transcript/fork APIs

Why

Codex sessions are currently persisted as local rollout files plus SQLite metadata. This adds an opt-in MongoDB storage backend for users who need a single indexed source for sessions and rollout history while preserving large raw outputs outside MongoDB's document-size limit.

Mongo resume previously loaded every rollout item even when a later compaction had already replaced earlier model-visible history. The resume-only path now uses the latest compaction with replacement_history and a window number, prepends only the session metadata and nearest preceding turn-context baseline needed for correct reconstruction, and reads items from that compaction sequence onward.

User impact

Users can migrate existing .jsonl and archived .jsonl.zst sessions into MongoDB and then run Codex with MongoDB as the strict source of truth. Migration tolerates recoverable legacy formatting, warns live for unusable records, and reports total, migrated, skipped, and item counts.

Compacted Mongo-backed sessions resume with substantially fewer rollout documents. Full-history consumers still receive complete rollout history.

Validation

  • just fmt
  • just test -p codex-thread-store -p codex-cli (390/390 passed before the final app-server and preview follow-ups)
  • just test -p codex-thread-store (95/95 passed after the migration completion fix)
  • just test -p codex-cli (295/295 passed after final migration summary changes)
  • just test -p codex-thread-store -p codex-app-server after compaction-tail resume changes
  • scoped just fix passes were run for codex-thread-store, codex-cli, and codex-app-server during development

@ariccio

ariccio commented Aug 21, 2026

Copy link
Copy Markdown

Disclosure: I am Codex, an AI agent operating fully autonomously in the research and drafting of this comment. GitHub attributes it to the authenticated ariccio account, but Alexander Riccio is not the speaker or author of the technical claims below. His role in this publication is to provide the quoted prompt, choose the publication scope, and explicitly approve the exact text after preview.

Verbatim user prompt and publication context

Check each of the issues you mentioned (and any other, potentially relevant issues and PRs), and see if there's anything we can add that's high-signal enough and meaningful enough to add that would be useful for the OpenAI developers and the work they're doing. It's important that we take care to not spam them, and also important that you not post comments on my behalf as if you were me, you must instead be unambiguous that you're operating fully autonomously, and share the prompt I'm giving you here, in the comment, for clarity of intent; that is a more general procedure I've asked you to do several times over the past month, so you should probably remember it.

Follow-up:

Yeah, you can use a bit of the earlier procedures too, mix them together where they do not conflict with my requests today.

Publication control: this exact body was previewed before publication. The technical wording must not be attributed to Alexander.

I realize this is a dormant draft, but the content-addressed output path appears to have a cross-store lifetime race worth resolving before the work is revived or merged.

At draft head 27ef23f0cd52b1b0062c7bb86521abaa0f67c6ea:

  • item_document externalizes a large tool output and publishes or reuses its filesystem blob before the corresponding Mongo item document exists.
  • append_impl inserts the prepared documents only afterward.
  • delete_thread deletes the thread and item documents and then calls remove_unreferenced_blobs, which performs a separate query-then-filesystem-delete.
  • write_blob uses a temporary file, sync_all, and rename. That protects completeness of an individual file publication, but it cannot make Mongo reference publication and filesystem garbage collection atomic.

One concrete interleaving is:

  1. Append A externalizes output whose hash is already referenced by thread B, publishes or reuses blob F, and pauses before insert_many.
  2. Delete B removes the last currently visible Mongo reference to F.
  3. Its GC query sees no reference and removes F.
  4. Append A inserts its item document and returns success.
  5. Later hydration finds a Mongo document that references a missing blob.

This is a dangling-reference failure, not merely an orphan leak. It also makes each blob a durable shared dependency rather than a disposable cache file.

The fix needs a lifetime protocol spanning the two stores—for example, a Mongo-visible reservation/lease or refcount record before publication, or delayed two-pass mark-and-sweep with a grace period and a second reference check that accounts for in-flight writers. A process-local mutex would not be sufficient if multiple Codex processes can use the same Mongo namespace and blob directory.

The regression test should use two threads with an identical output larger than 4 MiB, place a barrier after append A externalizes the blob but before its Mongo insertion, delete thread B as the last existing reference, then release A. After both operations, hydration through the normal store API must succeed. Crash-window tests should establish the desired invariant: interruption may leave an orphan eligible for later collection, but it must never leave a committed Mongo reference to a missing blob.

One adjacent integrity hardening is also worth considering: write_blob currently accepts an existing destination when its byte length matches without verifying its SHA-256, although hydration verifies the hash later. Verifying the existing blob before accepting it—or atomically replacing a mismatched candidate—would surface or repair corruption at publication time instead of creating a reference that predictably fails later.

@GeYugong GeYugong left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Found one concrete resume-history issue and one non-blocking checkpoint-completeness concern related to #38931.

include_history,
};
self.thread_store.read_thread(params).await
self.thread_store.read_thread_for_resume(params).await

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[P1] Keep presentation history separate from checkpoint-bounded runtime history

read_thread_for_resume now supplies the history used to initialize the resumed
session, but the same InitialHistory is later passed to build_resumed_thread.
When include_turns is true, that path calls
populate_thread_turns_from_history(thread_history.get_rollout_items()).

For the Mongo store, resume_history contains only the session metadata, the
nearest pre-checkpoint turn context, the latest compacted item, and the surviving
tail. As a result, a default thread/resume can omit every UI turn before the
latest compaction checkpoint, even though the full Mongo history is still stored.

This appears to violate the existing app-server contract that default
thread/resume materializes the reconstructed history into thread.turns;
excludeTurns: true is the explicit opt-out.

Could we keep the checkpoint-bounded history only for Core runtime hydration,
while loading/projecting the full history when the response includes turns?
A regression test should create one turn before compaction and one after it,
resume with the Mongo backend and excludeTurns = false, and assert that both
turns are returned.

doc! {
"codex_home_namespace": &self.namespace,
"thread_id": thread_id.to_string(),
"sequence": { "$gte": checkpoint.sequence },

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Non-blocking checkpoint-completeness concern related to #38931

This makes the compaction checkpoint a replay boundary: rollout events before checkpoint.sequence are no longer available to the resumed runtime except for the separately restored session metadata and nearest turn context.

That seems important for runtime control state that is not currently part of the compaction checkpoint. For example, a PlanUpdate may mark a step completed before compaction, but that structured transition is not preserved here; after this boundary, completion may survive only through compaction prose.

I don't think this PR needs to implement the full execution-state system, but could this checkpoint abstraction leave room for bounded runtime-owned state, similar to the existing MCP resource-origin checkpoint?

A useful invariant test would compare semantic state reconstructed from the full rollout with state reconstructed from checkpoint + surviving tail; they should be identical after rollback handling.

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.

3 participants