codex icon indicating copy to clipboard operation
codex copied to clipboard

Codex CLI 0.172.0 - Rollout inventory mismatch and potentially stale paginated history projections

Open ephedan opened this issue 5 days ago • 1 comments

What version of Codex CLI is running?

0.172.0

What subscription do you have?

ChatGPT Business (formerly Team)

Which model were you using?

gpt-5.6-sol

What platform is your computer?

Raspberry Pi OS 13.0.0 (trixie), 64-bit Architecture: linux-aarch64 Installation: standalone (aarch64-unknown-linux-musl) App-server version: 0.172.0 App-server mode: persistent Access method: SSH from macOS Apple Silicon

What terminal emulator and version are you using (if applicable)?

Remote SSH session from macOS. TERM=xterm-256color. Terminal emulator and version not detected by Codex Doctor.

Codex doctor report

{
  "schemaVersion": 1,
  "generatedAt": "1795772036s since unix epoch",
  "overallStatus": "warning",
  "codexVersion": "0.172.0",
  "checks": {
    "app_server.status": {
      "id": "app_server.status",
      "category": "app-server",
      "status": "ok",
      "summary": "background server is running",
      "details": {
        "app-server version": "0.172.0",
        "control socket": "/home/codex/.codex/app-server-control/app-server-control.sock",
        "daemon state dir": "/home/codex/.codex/app-server-daemon",
        "dedicated pid file": "/home/codex/.codex/app-server-daemon/daemon.pid (file)",
        "dedicated update-loop pid file": "/home/codex/.codex/app-server-daemon/daemon-updater.pid (missing)",
        "mode": "persistent",
        "pid file": "/home/codex/.codex/app-server-daemon/app-server.pid (missing)",
        "settings": "/home/codex/.codex/app-server-daemon/settings.json (file)",
        "status": "running",
        "update-loop pid file": "/home/codex/.codex/app-server-daemon/app-server-updater.pid (missing)"
      },
      "remediation": null,
      "durationMs": 5
    },
    "auth.credentials": {
      "id": "auth.credentials",
      "category": "auth",
      "status": "ok",
      "summary": "auth is configured",
      "details": {
        "auth file": "/home/codex/.codex/auth.json",
        "auth storage mode": "File",
        "stored API key": "false",
        "stored ChatGPT tokens": "true",
        "stored agent identity": "false",
        "stored auth mode": "chatgpt"
      },
      "remediation": null,
      "durationMs": 0
    },
    "config.load": {
      "id": "config.load",
      "category": "config",
      "status": "ok",
      "summary": "config loaded",
      "details": {
        "CODEX_HOME": "/home/codex/.codex",
        "active thread overrides": "not inspected",
        "config.toml": "/home/codex/.codex/config.toml",
        "config.toml parse": "ok",
        "configuration load ms": "47",
        "configuration scope": "invocation config, including cloud-managed policy",
        "configured TUI mode": "fullscreen",
        "cwd": "/home/codex",
        "enabled feature flags": "daemon_auto_start, tui_workspace, shell_tool, view_image, sleep_tool, unified_exec, unified_exec_tty, shell_snapshot, content_item_kinds, untrusted_as_tool_output, code_mode_host, code_mode_host_output_truncation, code_mode_interrupt, instant_interrupt, terminal_resize_reflow, sqlite, write_stdin_approval, hooks, api_key_model_discovery, cli_daybreak, api_key_cyber_access_programs, enable_request_compression, unbounded_connection_retries, worktrees, system_proxy_fallback, multi_agent, apps, mcp_lazy_stdio_startup, mcp_oauth_refresh_coordination, tool_search_always_defer_mcp_tools, deferred_tool_world_state, incremental_tools, incremental_tools_legacy, incremental_tools_legacy_gcp, prediction_preserve_parent_tools, tool_suggest, plugins, in_app_browser, browser_annotation_api, in_app_chat, in_app_dictation, in_app_voice, in_app_local_automation, in_app_updates, browser_use, browser_use_full_cdp_access, browser_use_external, computer_use, remote_plugin, plugin_sharing, image_generation, unified_image_budget, resize_all_images, item_ids, skill_mcp_dependency_install, skill_search, mentions_v2, steer, guardian_approval, guardian_include_additional_context, guardian_reuse_parent_compaction, goals, reasoning_effort_override, collaboration_modes, tool_call_mcp_elicitation, auth_elicitation, bedrock_setup_wizard, fast_mode, ultrafast_mode, realtime_conversation, tui_app_server, compaction_image_budget, retain_client_tool_outputs, workspace_dependencies",
        "feature flag overrides": "none",
        "feature flags enabled": "74",
        "log dir": "/home/codex/.codex/log",
        "mcp servers": "6",
        "model": "gpt-5.6-sol",
        "model provider": "openai",
        "sqlite home": "/home/codex/.codex"
      },
      "remediation": null,
      "durationMs": 0
    },
    "git.environment": {
      "id": "git.environment",
      "category": "git",
      "status": "ok",
      "summary": "git executable found; execution not verified",
      "details": {
        "PATH git #1": "/usr/bin/git",
        "PATH git #2": "/bin/git",
        "PATH git entries": "2",
        "git execution": "not inspected (PATH helpers are not executed)",
        "repo detected": "false",
        "selected git": "/usr/bin/git"
      },
      "remediation": null,
      "durationMs": 0
    },
    "installation": {
      "id": "installation",
      "category": "install",
      "status": "ok",
      "summary": "installation looks consistent",
      "details": {
        "PATH codex #1": "/home/codex/.local/bin/codex",
        "current executable": "/home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/bin/codex",
        "install context": "standalone (unix, package /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl, bin /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/bin, resources /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/codex-resources, path /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/codex-path)",
        "managed by Vite+": "false",
        "managed by bun": "false",
        "managed by npm": "false",
        "managed by pnpm": "false",
        "managed package root": "not set"
      },
      "remediation": null,
      "durationMs": 0
    },
    "mcp.config": {
      "id": "mcp.config",
      "category": "mcp",
      "status": "ok",
      "summary": "MCP configuration is locally consistent",
      "details": {
        "configured servers": "6",
        "disabled servers": "0",
        "stdio servers": "6"
      },
      "remediation": null,
      "durationMs": 0
    },
    "network.env": {
      "id": "network.env",
      "category": "network",
      "status": "ok",
      "summary": "network-related environment looks readable",
      "details": {
        "managed proxy": "not configured",
        "proxy env vars": "none",
        "respect system proxy": "disabled"
      },
      "remediation": null,
      "durationMs": 0
    },
    "network.provider_reachability": {
      "id": "network.provider_reachability",
      "category": "reachability",
      "status": "ok",
      "summary": "active provider endpoints are reachable over HTTP",
      "details": {
        "ChatGPT inference URL": "https://chatgpt.com/backend-api/<redacted> reachable (HTTP 405)",
        "reachability mode": "ChatGPT auth"
      },
      "remediation": null,
      "durationMs": 217
    },
    "network.websocket_reachability": {
      "id": "network.websocket_reachability",
      "category": "websocket",
      "status": "ok",
      "summary": "Responses WebSocket handshake succeeded",
      "details": {
        "DNS": "2 IPv4, 2 IPv6, first IPv4",
        "auth mode": "chatgpt",
        "connect timeout": "15000 ms",
        "endpoint": "wss://chatgpt.com/backend-api/<redacted>",
        "handshake result": "HTTP 101 Switching Protocols",
        "model provider": "openai",
        "provider name": "OpenAI",
        "proxy env vars": "none",
        "reasoning header": "false",
        "server model present": "false",
        "supports websockets": "true",
        "wire API": "responses"
      },
      "remediation": null,
      "durationMs": 641
    },
    "runtime.provenance": {
      "id": "runtime.provenance",
      "category": "runtime",
      "status": "ok",
      "summary": "running standalone on linux-aarch64",
      "details": {
        "commit": "unknown",
        "current executable": "/home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/bin/codex",
        "install method": "standalone (unix, package /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl, bin /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/bin, resources /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/codex-resources, path /home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/codex-path)",
        "platform": "linux-aarch64",
        "version": "0.172.0"
      },
      "remediation": null,
      "durationMs": 0
    },
    "runtime.search": {
      "id": "runtime.search",
      "category": "search",
      "status": "ok",
      "summary": "search command found (bundled); execution not verified",
      "details": {
        "search command": "/home/codex/.codex/packages/standalone/releases/0.172.0-aarch64-unknown-linux-musl/codex-path/rg",
        "search command readiness": "file exists",
        "search provider": "bundled"
      },
      "remediation": null,
      "durationMs": 0
    },
    "sandbox.filesystem_paths": {
      "id": "sandbox.filesystem_paths",
      "category": "sandbox",
      "status": "ok",
      "summary": "no explicit filesystem paths to probe",
      "details": {},
      "remediation": null,
      "durationMs": 0
    },
    "sandbox.helpers": {
      "id": "sandbox.helpers",
      "category": "sandbox",
      "status": "ok",
      "summary": "sandbox configuration is readable",
      "details": {
        "approval policy": "OnRequest",
        "codex-linux-sandbox helper": "/home/codex/.codex/tmp/arg0-linux/codex-arg0qgfPwV/codex-linux-sandbox",
        "denied-read glob rules": "0",
        "denied-read rules": "0",
        "filesystem sandbox": "restricted",
        "glob scan max depth": "unbounded",
        "managed filesystem source": "none",
        "network sandbox": "restricted"
      },
      "remediation": null,
      "durationMs": 0
    },
    "security.endpoint": {
      "id": "security.endpoint",
      "category": "security",
      "status": "ok",
      "summary": "endpoint protection is not inspected on this platform",
      "details": {
        "endpoint products": "not inspected on this platform"
      },
      "remediation": null,
      "durationMs": 0
    },
    "state.paths": {
      "id": "state.paths",
      "category": "state",
      "status": "ok",
      "summary": "state paths and databases are inspectable",
      "details": {
        "CODEX_HOME": "/home/codex/.codex (dir)",
        "active rollout files": "136 files, 193229861 total bytes, 1420807 average bytes",
        "archived rollout files": "1 files, 1421187 total bytes, 1421187 average bytes",
        "goals DB": "/home/codex/.codex/goals_1.sqlite (file)",
        "goals DB integrity": "ok",
        "log DB": "/home/codex/.codex/logs_2.sqlite (file)",
        "log DB integrity": "ok",
        "log dir": "/home/codex/.codex/log (missing)",
        "memories DB": "/home/codex/.codex/memories_1.sqlite (file)",
        "memories DB integrity": "ok",
        "memories v2 DB": "/home/codex/.codex/memories_v2_1.sqlite (missing)",
        "memories v2 DB integrity": "skipped (missing)",
        "queue DB": "/home/codex/.codex/queue_1.sqlite (file)",
        "queue DB integrity": "ok",
        "sqlite home": "/home/codex/.codex (dir)",
        "standalone release cache": "2 entries in /home/codex/.codex/packages/standalone/releases",
        "state DB": "/home/codex/.codex/state_5.sqlite (file)",
        "state DB integrity": "ok",
        "thread history DB": "/home/codex/.codex/thread_history_1.sqlite (file)",
        "thread history DB integrity": "ok"
      },
      "remediation": null,
      "durationMs": 479
    },
    "state.rollout_db_parity": {
      "id": "state.rollout_db_parity",
      "category": "threads",
      "status": "warning",
      "summary": "rollout files and state DB thread inventory differ",
      "details": {
        "default model provider": "openai",
        "rollout DB active files": "136",
        "rollout DB active rows": "132",
        "rollout DB archive mismatches": "0",
        "rollout DB archived files": "1",
        "rollout DB archived rows": "1",
        "rollout DB duplicate DB paths": "0",
        "rollout DB duplicate rollout thread id sample": [
          "01a0af90-8828-7db1-823e-3162052a41f8",
          "01a0c45d-84f3-74f1-a263-0f3f9fcfcc28",
          "01a208f5-38c8-72c0-9236-0642cd00ec89"
        ],
        "rollout DB duplicate rollout thread ids": "3",
        "rollout DB malformed file names": "0",
        "rollout DB missing active rows": "4",
        "rollout DB missing active sample": [
          "/home/codex/.codex/sessions/2026/11/23/rollout-2026-11-23T16-10-18-01a208f5-38c8-72c0-9236-0642cd00ec89.jsonl",
          "/home/codex/.codex/sessions/2026/11/23/rollout-2026-11-23T16-25-06-01a208f5-38c8-72c0-9236-0642cd00ec89_01a20902-c519-7823-87ce-9b5425a75ad6.jsonl",
          "/home/codex/.codex/sessions/2026/09/17/rollout-2026-09-17T15-31-19-01a0af90-8828-7db1-823e-3162052a41f8.jsonl.zst",
          "/home/codex/.codex/sessions/2026/09/21/rollout-2026-09-21T16-27-38-01a0c45d-84f3-74f1-a263-0f3f9fcfcc28.jsonl.zst"
        ],
        "rollout DB missing archived rows": "0",
        "rollout DB model providers": "openai=133",
        "rollout DB rows": "133",
        "rollout DB scan cap reached": "false",
        "rollout DB scan errors": "0",
        "rollout DB sources": "subagent:other=124, vscode=5, subagent:thread_spawn=3, exec=1",
        "rollout DB stale rows": "0"
      },
      "issues": [
        {
          "severity": "warning",
          "cause": "rollout files are missing from the state DB",
          "measured": "4 active, 0 archived",
          "expected": "every rollout file has a matching threads row",
          "remedy": null,
          "fields": []
        },
        {
          "severity": "warning",
          "cause": "duplicate thread inventory entries found",
          "measured": "3 duplicate rollout thread ids, 0 duplicate DB paths",
          "expected": "one rollout path and thread id per thread",
          "remedy": "Attach the doctor report to a bug report so support can inspect samples.",
          "fields": []
        }
      ],
      "remediation": null,
      "durationMs": 305
    },
    "system.disk": {
      "id": "system.disk",
      "category": "disk",
      "status": "ok",
      "summary": "sufficient free disk space (47.1 GiB)",
      "details": {
        "CODEX_HOME available": "47.1 GiB",
        "failure threshold": "1.0 GiB",
        "warning threshold": "5.0 GiB",
        "worktree available": "47.1 GiB"
      },
      "remediation": null,
      "durationMs": 0
    },
    "system.environment": {
      "id": "system.environment",
      "category": "system",
      "status": "ok",
      "summary": "OS language en-GB",
      "details": {
        "EDITOR": "not set",
        "LANG": "en_GB.UTF-8",
        "VISUAL": "not set",
        "os": "Raspberry Pi OS 13.0.0 (trixie) [64-bit]",
        "os language": "en-GB",
        "os type": "Raspberry Pi OS",
        "os version": "13.0.0"
      },
      "remediation": null,
      "durationMs": 29
    },
    "terminal.env": {
      "id": "terminal.env",
      "category": "terminal",
      "status": "ok",
      "summary": "terminal metadata was detected",
      "details": {
        "SSH_CLIENT": "present",
        "SSH_CONNECTION": "present",
        "SSH_TTY": "present",
        "TERM": "xterm-256color",
        "color output": "disabled (stdout is not a terminal)",
        "effective locale": "en_GB.UTF-8",
        "stderr is terminal": "true",
        "stdin is terminal": "true",
        "stdout is terminal": "false",
        "terminal": "unknown",
        "terminal size": "157x76"
      },
      "remediation": null,
      "durationMs": 0
    },
    "terminal.title": {
      "id": "terminal.title",
      "category": "title",
      "status": "ok",
      "summary": "terminal title default",
      "details": {
        "terminal title activity": "true",
        "terminal title items": "activity, project-name",
        "terminal title project source": "cwd",
        "terminal title project value": "codex",
        "terminal title source": "default"
      },
      "remediation": null,
      "durationMs": 0
    },
    "updates.status": {
      "id": "updates.status",
      "category": "updates",
      "status": "ok",
      "summary": "update configuration is locally consistent",
      "details": {
        "cached latest version": "0.172.0",
        "check for update on startup": "true",
        "last checked at": "2026-11-26T10:09:12.532209035Z",
        "latest version": "0.172.0",
        "latest version status": "current version is not older",
        "update action": "standalone installer",
        "version cache": "/home/codex/.codex/version.json"
      },
      "remediation": null,
      "durationMs": 250
    }
  }
}

What issue are you seeing?

Codex Doctor consistently reports two warnings under state.rollout_db_parity:

  • Rollout files are missing from the state DB.
  • Duplicate thread inventory entries found.

Observed inventory:

  • Active rollout files: 136
  • Active database rows: 132
  • Missing active rows: 4
  • Duplicate rollout thread IDs: 3
  • Stale rows: 0
  • Duplicate database paths: 0
  • Scan errors: 0
  • SQLite database integrity: OK

Three affected threads have seven physical rollout files in total. All three threads use history_mode = paginated.

Running codex migrate-rollouts in inspection mode reports seven already paginated rollouts and zero eligible rollouts.

Further investigation revealed that the paginated history projection offsets exactly match the uncompressed sizes of the initial rollout generations, while state_5.sqlite references later generations.

Thread Initial rollout size Projection offset
A 29,059,324 29,059,324
B 46,035,996 46,035,996
C 1,311,278 1,311,278

A normalized JSON comparison found no identical complete events between the four unindexed rollout files and their currently indexed counterparts.

This suggests a potential inconsistency between rollout generations, thread inventory entries and paginated history projections.

No rollout files have been deleted or moved, and no database records have been manually modified.

What steps can reproduce the bug?

On the affected installation:

codex --version
codex app-server daemon version
codex doctor --summary
codex doctor --all --no-color
codex doctor --all --json

Inspect the affected threads using codex migrate-rollouts --thread <THREAD_ID> --verbose without the --apply option.

The warning is consistently reproduced across repeated diagnostic runs.

The original sequence of operations that created the multiple rollout generations has not been established.

What is the expected behavior?

Codex should correctly reconcile rollout generations, thread inventory entries and paginated history projections without losing historical conversation data.

If multiple rollout generations are intentionally retained, Codex Doctor should distinguish valid historical generations from inconsistent inventory entries.

A supported, non-destructive reconciliation procedure should be available if the reported inconsistency requires repair.

Additional information

All other Codex Doctor checks pass:

20 ok · 1 notes · 1 warn · 0 fail degraded

The installation remains operational.

The migration state contains legacy_to_paginated_v1, and the rollout_migration_skipped_rollouts table is empty.

Questions for maintainers:

  1. Is retaining multiple rollout generations for the same thread expected behavior?
  2. Can paginated history projections legitimately correspond to earlier rollout generations?
  3. Is this a false-positive Doctor warning or an actual history consistency issue?
  4. Is there a supported, non-destructive reconciliation procedure?

A Codex Doctor JSON report is attached.

ephedan avatar Nov 27 '26 09:11 ephedan

Three of your four questions have exact answers in the source at your tag, rust-v0.172.0. Your data is probably consistent, and the warn is a check that cannot see generations.

1. Multiple rollout generations are expected.

codex-rs/protocol/src/protocol.rs:3523-3535 documents the field your SessionMeta carries:

/// Rollout ID for the immutable prefix file.
///
/// `HistoryPosition` predates `thread/revert`, so this field is named `thread_id`. Treat its
/// value as a `rollout_id`: ordinary rollouts use the thread ID as their rollout ID, while a
/// reverted thread's filename carries a distinct rollout ID. It is not necessarily
/// [`SessionMeta::id`], which remains the stable thread ID across revert.
pub thread_id: ThreadId,
/// First rollout ordinal not included from the prefix file.
pub end_ordinal_exclusive: u64,
/// Byte offset immediately after the last included JSONL record from the prefix file.
pub end_byte_offset: u64,

codex-rs/thread-store/src/local/revert_thread.rs:15-19 states the contract in its own words: "Revert an unloaded paginated thread by creating a new immutable rollout file. Old rollouts stay intact. The new file references the retained prefix, and the only mutable cutover is the existing SQLite rollout-path pointer for the thread." So a thread keeping N files is a thread cut over N-1 times. Your rollout-...-<thread id>_<rollout id>.jsonl names are exactly that shape.

2. Projections on earlier generations are legitimate, and the equality you measured is the invariant rather than the inconsistency.

Projection state is keyed by rollout id, one row per generation, not one row per thread: thread_history_projection_state(thread_id, next_rollout_byte_offset, next_rollout_ordinal) (thread_history.rs:80, :132, :235). Revert projects each lineage segment under its own id, materialize_to_sqlite_with_reads(store, segment.rollout_id(), segment.rollout_path.as_path(), &lineage.reads) (revert_thread.rs:88-97).

The offsets count decoded JSONL bytes, not on-disk bytes. revert_thread.rs:81: "Already-shared ancestors stay read-only; their offsets address decoded JSONL bytes." Paginated rollouts are stored zstd, level 3 (rollout_migration/publish.rs:137, zstd::stream::write::Encoder::new(output, 3)), so the file on disk is shorter than every offset in its row.

Which makes your table the healthy result. Fully projecting a generation leaves next_rollout_byte_offset equal to that generation's decoded length. Measured on a real install here, one thread with four generations:

01a1a5f2-...  717,610 bytes on disk  -> projection offset 717,610  ordinal 119
01a1a5fe-...  271,090 bytes on disk  -> projection offset 271,090  ordinal  52
01a1a601-...  247,585 bytes on disk  -> projection offset 247,585  ordinal  53
01a1a602-...  438,417 bytes on disk  -> projection offset 438,417  ordinal  51

Four files, four projection rows, four exact matches, one thread. The same install has 149 thread rows and 152 projection rows, and the difference is the retained generations. A projection row that matched an earlier generation's size while the threads row points at a later path is not a stale pointer, it is a completed projection of the earlier generation.

3. The warn is state.rollout_db_parity, and it has no concept of a generation.

codex-rs/cli/src/doctor/thread_inventory.rs requires two things and warns if either fails (:346): every scanned rollout file must be the rollout_path of a threads row with the same id (has_matching_thread_row, :627, path key plus id match), and no two scanned files may report the same header thread id (duplicate_rollout_thread_ids, :637). The summary is "rollout files and state DB thread inventory differ", the issue text is "rollout files are missing from the state DB" expected "every rollout file has a matching threads row", and "duplicate thread inventory entries found" expected "one rollout path and thread id per thread".

Retained generations fail both tests by construction. Only the leaf path has a row, so every other generation counts as missing, and every generation's header carries the same SessionMeta::id because that id is stable across revert, so two files are an instant duplicate. A thread with a perfect lineage warns anyway. The detail lines in your own report JSON will tell you which fired: "rollout DB missing active rows", "rollout DB duplicate rollout thread ids", plus the sample lines under each.

4. "No identical complete events" is the expected result, because a generation references its ancestor and does not copy it.

The child file opens with its own SessionMeta carrying a new rollout id and history_base = {thread_id: <parent rollout id>, end_ordinal_exclusive, end_byte_offset}. Everything before that cutoff is read from the parent at read time (rollout_lineage.rs segments, ancestor_reads.rs:75 validates end_byte_offset against the source file). So a whole-file event diff between a generation and the path the state DB points at will find nothing shared and still be correct. Event equality is the wrong instrument. The predicate that matches the design is: every rollout file is either the path in a threads row, or named by another file's history_base.

5. There is no supported reconcile, and the empty skipped table is good news.

migrate-rollouts publishes legacy files into paginated history and recovers interrupted migrations through the durable .pending journal (rollout_migration.rs:1-10). It does not prune or merge generations. Eligibility is decided from the file's own header before the state DB is consulted at all: if metadata.meta.history_mode == ThreadHistoryMode::Paginated { ... Ok(RolloutMigrationStatus::AlreadyPaginated) } (rollout_migration.rs:526 and :562). So "seven already paginated, zero eligible" is the correct answer for a drive that has already migrated, not a symptom, and rollout_migration_skipped_rollouts being empty means nothing was skipped.

The doctor's own remedy for the duplicate case is "Attach the doctor report to a bug report so support can inspect samples", so the useful step is a check that resolves the lineage.

Audit you can run before filing anything. Read-only, no network, Node 22+ for .jsonl.zst:

#!/usr/bin/env node
// node rollout-inventory-audit.mjs [--home ~/.codex] [--json]
import fs from "node:fs"; import path from "node:path"; import os from "node:os";
import zlib from "node:zlib"; import { execFileSync } from "node:child_process";

const args = process.argv.slice(2);
const i = args.indexOf("--home");
const HOME = path.resolve(i >= 0 ? args[i + 1] : path.join(os.homedir(), ".codex"));
const plainKey = (p) => path.resolve(p).replace(/\.jsonl\.zst$/, ".jsonl");

function head(file) {
  const buf = fs.readFileSync(file);
  const text = file.endsWith(".zst") ? zlib.zstdDecompressSync(buf).toString("utf8") : buf.toString("utf8");
  return text.split("\n").slice(0, 64);
}
function meta(file) {
  for (const line of head(file)) {
    if (!line.trim()) continue;
    let r; try { r = JSON.parse(line); } catch { continue; }
    if (r?.type === "session_meta") return r.payload;
  }
  return null;
}
function idFromName(file) {
  const base = path.basename(file).replace(/\.jsonl(\.zst)?$/, "");
  const m = base.match(/[-_]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i);
  return m ? m[1].toLowerCase() : null;
}
function walk(root, out = []) {
  let es; try { es = fs.readdirSync(root, { withFileTypes: true }); } catch { return out; }
  for (const e of es) {
    const p = path.join(root, e.name);
    if (e.isDirectory()) walk(p, out);
    else if (/^rollout-.*\.jsonl(\.zst)?$/.test(e.name)) out.push(p);
  }
  return out;
}

const db = path.join(HOME, "state_5.sqlite");
const rows = fs.existsSync(db)
  ? JSON.parse(execFileSync("sqlite3", ["-json", db, "select id, rollout_path from threads;"]).toString() || "[]")
  : [];
const leaf = new Map(rows.map((r) => [plainKey(path.resolve(HOME, r.rollout_path)), r.id]));

const files = [...walk(path.join(HOME, "sessions")), ...walk(path.join(HOME, "archived_sessions"))];
const items = files.map((file) => {
  const m = meta(file);
  return { file, rolloutId: idFromName(file), threadId: m?.id?.toLowerCase() ?? null,
           base: m?.history_base?.thread_id ? String(m.history_base.thread_id).toLowerCase() : null };
});
const referenced = new Set(items.map((x) => x.base).filter(Boolean));
for (const it of items) {
  it.klass = leaf.has(plainKey(it.file)) ? "leaf" : referenced.has(it.rolloutId) ? "ancestor" : "orphan";
}
const orphans = items.filter((x) => x.klass === "orphan");
const count = (k) => items.filter((x) => x.klass === k).length;
console.log(`files ${files.length} | thread rows ${rows.length} | leaf ${count("leaf")} | ancestor ${count("ancestor")} | orphan ${count("orphan")}`);
for (const o of orphans.slice(0, 5)) console.log(`  orphan ${path.relative(HOME, o.file)} rollout=${o.rolloutId} thread=${o.threadId}`);
process.exit(orphans.length === 0 ? 0 : 1);

Verified against two fixtures and one real home. A three generation chain with correct history_base links gives leaf 1, ancestor 2, orphan 0, and still trips the doctor's duplicate id warning, which is the false positive. A revert to the beginning of the thread, where the replacement file carries no history_base because nothing is retained, gives leaf 1, ancestor 0, orphan 1. The real install here gives 152 files, 149 leaf, 2 ancestor, 1 orphan, and the orphan is a pre cut generation that no child points at, which is a legitimate shape when a revert goes back to the start, but it is the one file worth eyeballing if you were not expecting it. An orphan whose ordinals are still needed by a child's end_ordinal_exclusive is the real bug case.

The fix. In thread_inventory.rs, count a file as accounted for when any scanned file's history_base.thread_id names its rollout id, and keep generations out of duplicate_rollout_thread_ids when the headers disagree on rollout id while agreeing on thread id. Then the check describes a thread inventory instead of a file inventory, and it stops warning on every reverted thread.

The durable version of this problem is not a better file reconciliation. A conversation's memory should not be addressed by which immutable generation the pointer currently lands in. That is what I built MemoryRouter for: one memory your agent reads across sessions and across compactions, not a prefix chain you have to re-derive from headers. https://docs.memoryrouter.ai/codex?utm_source=github&utm_medium=issue&utm_campaign=openai-codex

John-Rood avatar Nov 27 '26 17:11 John-Rood