codex icon indicating copy to clipboard operation
codex copied to clipboard

Codex Desktop automation thread resume fails when state_5.sqlite has blank model_provider despite JSONL session_meta provider

Open daniel-graham opened this issue 5 months ago • 3 comments

What version of the Codex App are you using?

Codex App with bundled CLI/runtime:

codex-cli 0.142.0-alpha.1
Codex Doctor v0.142.0-alpha.1 - macos-aarch64

codex doctor --summary after local repair reports:

15 ok - 1 idle - 4 notes - 1 warn - 1 fail
config loaded
databases healthy
rollout files and state DB thread inventory agree
websocket connected
active provider endpoints are reachable over HTTP

The remaining doctor failure is TERM=dumb from a non-interactive shell and appears unrelated.

What subscription do you have?

ChatGPT-authenticated Codex App account. Exact subscription tier is not included in local diagnostics.

What platform is your computer?

Darwin 25.5.0 arm64 arm

What issue are you seeing?

Codex Desktop can fail to resume an automation-created local thread with this toast:

Codex can't load config.toml, so this thread can't resume.
Fix config.toml: Model provider `` not found.
After saving the file, reopen the thread.

This appears to be a stale/incomplete local thread-index row, not a bad config.toml.

The real rollout JSONL for the affected thread contains a non-empty provider:

"model_provider":"openai"

But the corresponding row in ~/.codex/state_5.sqlite had an empty provider:

id: 019edbe5-89a5-70d3-90e9-7c860472a6da
source: vscode
model: gpt-5.3-codex-spark
model_provider: ''
rollout_path: ~/.codex/sessions/2026/06/18/rollout-2026-06-18T14-01-53-019edbe5-89a5-70d3-90e9-7c860472a6da.jsonl

After manually updating that one row to model_provider='openai', the local inventory returned to a clean state and the provider error stopped:

blank provider rows: 0
rollout DB model providers openai=584

What steps can reproduce the bug?

I do not yet have a deterministic minimal repro, but I have hit the same failure class at least twice from Codex Desktop automation/worktree threads.

Current recurrence:

  1. A cron automation created a worktree thread for a repo-local daily performance audit.
  2. The saved transcript JSONL began with session_meta.payload.model_provider = "openai".
  3. The threads row in ~/.codex/state_5.sqlite for that same thread had model_provider = ''.
  4. Opening/resuming that thread in Codex Desktop failed with Model provider `` not found.
  5. Repairing only the SQLite index row from the JSONL session metadata fixed the resume failure.

Relevant commands used locally:

sqlite3 ~/.codex/state_5.sqlite \
  "select id, source, thread_source, model, model_provider, rollout_path
   from threads
   where id='019edbe5-89a5-70d3-90e9-7c860472a6da';"

sqlite3 ~/.codex/state_5.sqlite.bak-20260619-provider-repair \
  "select id, source, thread_source, model, quote(model_provider), rollout_path
   from threads
   where id='019edbe5-89a5-70d3-90e9-7c860472a6da';"

rg -n '"model_provider"' \
  ~/.codex/sessions/2026/06/18/rollout-2026-06-18T14-01-53-019edbe5-89a5-70d3-90e9-7c860472a6da.jsonl

Evidence from the pre-repair DB backup:

019edbe5-89a5-70d3-90e9-7c860472a6da|vscode||gpt-5.3-codex-spark|''|~/.codex/sessions/2026/06/18/rollout-2026-06-18T14-01-53-019edbe5-89a5-70d3-90e9-7c860472a6da.jsonl

Evidence after repair:

019edbe5-89a5-70d3-90e9-7c860472a6da|vscode||gpt-5.3-codex-spark|openai|~/.codex/sessions/2026/06/18/rollout-2026-06-18T14-01-53-019edbe5-89a5-70d3-90e9-7c860472a6da.jsonl

Prior local occurrence:

Local logs show a previous repair of the same failure class:

Root found for real: app DB had empty provider.
Patched 3 rows where threads.model_provider = ''
Now all 3 rows have model_provider = 'openai'
Target fixed: 019ed6bf-827e-7fb1-95b9-6505a69907b2
model = gpt-5.3-codex-spark
model_provider = openai

This recurrence suggests the local index writer or reindexer can still create new blank-provider rows after previous rows have been repaired.

What is the expected behavior?

Codex should not persist or use a blank threads.model_provider value when the rollout session_meta has a valid provider.

Expected behavior:

  • new automation/worktree threads should be indexed with model_provider='openai' when the transcript says model_provider='openai'
  • resume should prefer or recover from the rollout JSONL provider when the SQLite index provider is blank
  • codex doctor or startup reindex should detect and repair blank-provider rows from session metadata
  • the UI error should not blame config.toml when config parses and the active provider is healthy

Additional information

The affected automation config itself appears valid and includes a model:

kind = "cron"
model = "gpt-5.3-codex-spark"
reasoning_effort = "medium"
execution_environment = "worktree"

The automation schema does not expose a provider field, so recreating the automation does not look like a durable fix.

Local workaround installed on my machine:

  • a small guard script reads rows where threads.model_provider is blank
  • for each row, it reads the corresponding rollout JSONL session_meta.payload.model_provider
  • it updates only rows where the transcript has a non-empty provider
  • a LaunchAgent runs that guard periodically

That workaround keeps the local sidebar/resume index usable, but the app should avoid creating the invalid index state in the first place.

daniel-graham avatar Jun 19 '26 11:06 daniel-graham

I investigated this path locally and prepared a tested fix candidate, but this repository currently limits opening pull requests to collaborators, so I cannot open a PR from my fork.

Patch branch:

  • Fork branch: https://github.com/lyezhucc/codex/tree/codex/repair-session-provider-read-repair
  • Commit: https://github.com/lyezhucc/codex/commit/5a0c89f034f57c13d3a25cf6d38f3ff85cb09ea9
  • Compare: https://github.com/openai/codex/compare/main...lyezhucc:codex/repair-session-provider-read-repair

What the patch changes:

  • Repairs existing SQLite rows' threads.model_provider from rollout session_meta.model_provider in read_repair_rollout_path.
  • Before useStateDbOnly + modelProviders listings, scans a bounded candidate page without provider filtering and read-repairs provider mismatches from rollout metadata, then runs the normal provider-filtered query.
  • Allows resume/shutdown/flush to persist stable facts derived from existing history before a later append, while keeping derived display fields such as preview/title/first user message deferred.
  • Adds regression tests for blank/stale provider repair, state-db-only provider-filtered list visibility, and resume metadata flush behavior.

Validation run:

cargo test -p codex-rollout
cargo test -p codex-thread-store
cargo clippy -p codex-rollout -p codex-thread-store --all-targets -- -D warnings
cargo test -p codex-app-server --test all goal_first_live_thread_appears_in_state_db_thread_list
cargo test -p codex-app-server --test all thread_list_state_db_only_returns_sqlite_without_jsonl_repair
cargo test -p codex-app-server --test all thread_list_sort_recency_at_uses_state_db_order_with_provider_filter
cargo test -p codex-app-server --test all thread_list_respects_provider_filter

All passed. Note: thread_list_respects_provider_filter had one transient app-server initialization timeout on the first run, then passed on rerun.

lyezhucc avatar Jun 22 '26 02:06 lyezhucc

Additional reproducible evidence for this issue: the unmodified installed app-server can create the blank-provider row itself, and a subsequent successful rename does not repair it for paginated history. This also reproduces a case where the first rename succeeds while the bad metadata remains.

This is more than a manually corrupted SQLite fixture: the harness does not insert or update thread rows. All bad metadata is written by Codex. The reproduction uses fresh synthetic CODEX_HOME directories, no authentication or inference, and a macOS sandbox that denies network access and access to the real user's home contents. It does not invoke a third-party proxy.

Environment

  • Current desktop: 26.1007.71326, build 20398; observed incident desktop: 26.1007.30912.
  • Installed bundled CLI: 0.162.0-alpha.17.2; also the CLI version in both affected production rollout headers.
  • macOS, arm64; timezone Asia/Seoul (UTC+9).
  • Source trace: matching public tag rust-v0.162.0-alpha.17.2, commit 740e5af33c71225640e0c1c1555c514c2c93ab74. Runtime tests use the installed binary, not a build from that tag; reproducible binary equivalence is not claimed.

Actual / expected behavior

Actual: thread/name/set can persist model_provider='', cli_version='', thread_source=NULL, and a filename-derived creation time. After the rollout has valid session_meta, a paginated rename retry succeeds, but those fields remain wrong. thread/read can even report modelProvider='openai' while SQLite remains blank. thread/resume then fails with:

failed to load configuration: Model provider `` not found

Expected: incomplete recovery metadata should not become authoritative empty identity metadata; once canonical SessionMeta is available, recovery/resume should repair or reject the incomplete persisted value before treating it as a literal configured provider. An explicit legitimate provider must be preserved rather than always forcing openai.

Two original affected rows share this fingerprint despite valid JSONL headers: empty provider/CLI, NULL thread source, paginated history, and created_at = floor(SessionMeta UTC epoch seconds) + 32400. One original thread has a logged empty-rollout rename error followed about 64 ms later by successful rename and four later resume failures. The other has a successful rename log; it was not resumed during investigation. Original chats/configuration/database were not modified.

Reproduction results

The complete standalone Python script is included below. Run on macOS:

python3 reproduce_blank_provider.py --work-dir ./work/repro --repeats 2

The default binary path is the bundled CLI in ChatGPT.app; use --binary /path/to/codex if needed. It requires Python's standard library and macOS sandbox-exec. Synthetic artifacts are retained under --work-dir for inspection.

All 12 scenario runs passed their assertions (six scenarios, twice):

Initial reader-visible fixture Restored header Outcome after rename retry
Valid SessionMeta + event paginated Provider openai, time offset 0, resume succeeds
Zero-byte file paginated First rename fails without creating a row; retry and resume succeed
Event without SessionMeta paginated Empty provider/CLI, NULL thread source, +32400 seconds, resume fails
Malformed header + valid event paginated Same bad metadata and resume failure
Event without SessionMeta legacy Retry reconciles metadata; offset 0, resume succeeds
Controlled stale snapshot paginated First rename succeeds, but bad metadata and resume failure remain

In the controlled stale-snapshot case, the harness holds BEGIN IMMEDIATE on the synthetic DB, starts rename, waits until Codex has read the incomplete rollout, restores the valid file, then releases the lock. Codex commits its earlier incomplete observation even though the file is now valid. The harness does not mutate SQL rows.

Limits: this deterministically stages the missing/unparseable SessionMeta precondition. It does not prove why the original production reader missed that metadata, nor identify the original SQL writer with a production trace. Thirty ordinary offline thread/start → turn/start → thread/name/set sequences did not produce blank providers. Those unauthenticated/offline runs are also not equivalent to successful real model responses. The runtime defect and matching fingerprint are established; the original natural race remains unresolved.

Exact write and resume path

  1. thread/name/set accepts a non-empty name and calls ThreadManager::update_thread_metadata with a name-only patch: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/app-server/src/request_processors/thread_processor.rs#L1848-L1875

  2. LocalThreadStore update_thread_metadata first needs the history mode. Without a live writer it reads the stored thread. A missing SQLite row makes read_thread resolve the rollout through filesystem fallback: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/thread-store/src/local/update_thread_metadata.rs#L38-L110 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/thread-store/src/local/read_thread.rs#L31-L112 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/thread-store/src/local/thread_rollout_resolver.rs#L73-L142

  3. find_thread_path_by_id_str_in_subdir finds the filename and invokes read_repair_rollout_path BEFORE returning the path. Thus even a later failing read/name request can already have written a DB row: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/list.rs#L1387-L1410

  4. read_repair_rollout_path slow path calls read_session_meta_line; an error or missing provider becomes String::default() via .ok().and_then(...).unwrap_or_default(). It passes that empty default provider to reconcile_rollout: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/state_db.rs#L606-L675

read_session_meta_line scans valid records, skips unparsable ones, and emits "is empty" when it reaches EOF without SessionMeta. Therefore this error does NOT prove zero file length; an event-only rollout produces it too: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/list.rs#L1184-L1234

  1. reconcile_rollout -> extract_metadata_from_rollout -> RolloutRecorder::load_rollout_items. The latter skips unparsable lines. extract_metadata_from_rollout only rejects an empty items vector; at least one valid non-SessionMeta item is enough to proceed. builder_from_items falls back to the filename if no usable SessionMeta builder exists: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/state_db.rs#L519-L603 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/metadata.rs#L71-L172 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/recorder.rs#L1108-L1168

  2. Filename fingerprint: precompute_new_rollout_path uses now_local(); RolloutFileName::parse interprets the timezone-free filename timestamp with assume_utc(). In UTC+9, a 21:00 filename for a 12:00Z session becomes 21:00Z in fallback metadata, exactly +32400 seconds: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/recorder.rs#L1737-L1758 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/rollout/src/rollout_file_name.rs#L39-L56

  3. ThreadMetadataBuilder::new leaves provider/CLI version/thread source absent. build("") converts those to provider='', cli_version='', thread_source=None. The filename fallback uses SessionSource::default(), which is vscode in this version: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/state/src/model/thread_metadata.rs#L251-L327 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/protocol/src/protocol.rs#L2815

  4. reconcile_rollout calls StateRuntime::upsert_thread. upsert_thread_with_creation_memory_mode writes the row and ON CONFLICT replaces created_at, provider, CLI version and thread_source without rejecting empty/incomplete values. Its conflict rule preserves existing originator and prevents paginated -> legacy downgrade, but does not similarly protect provider/CLI version. This permits stale recovery observations to clobber richer metadata: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/state/src/runtime/threads.rs#L610-L613 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/state/src/runtime/threads.rs#L910-L1014

Why a successful paginated rename retry does not repair it

After the file becomes valid, stored_thread_from_sqlite_metadata reads SessionMeta to establish canonical history_mode and ancestry. It does not generally replace the SQLite provider/CLI version/created_at with the header values: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/thread-store/src/local/read_thread.rs#L324-L373

apply_metadata_update clones the existing row. It promotes the row's history_mode to paginated, but updates provider, created_at, and cli_version only if the patch contains those fields. A name-only patch does not. The paginated branch then returns before the later legacy reconcile_rollout call: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/thread-store/src/local/update_thread_metadata.rs#L412-L495 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/thread-store/src/local/update_thread_metadata.rs#L157-L229

The public fixture verifies this distinction: restoring a legacy header and retrying name-setting repairs the row; restoring a paginated header and retrying does not. An ordinary thread/read can also report modelProvider='openai' while the DB remains blank, because the API serializer substitutes fallback_provider for an empty stored provider: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/app-server/src/request_processors/thread_processor.rs#L6188-L6192

Why resume fails despite the valid JSONL

thread/resume calls load_and_apply_persisted_resume_metadata. In the absence of an explicit model/provider override, merge_persisted_resume_metadata copies the SQLite provider into ConfigOverrides as Some(""). Configuration loading looks up that literal empty provider and errors before a normal session can repair metadata: https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/app-server/src/request_processors/thread_processor.rs#L230-L248 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/app-server/src/request_processors/thread_processor.rs#L3934-L3975 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/app-server/src/request_processors/thread_processor.rs#L4243-L4277 https://github.com/openai/codex/blob/740e5af33c71225640e0c1c1555c514c2c93ab74/codex-rs/core/src/config/mod.rs#L3838-L3846

Suggested regression coverage

In addition to provider repair discussed above, please cover the paginated name-only retry, API-read/DB-provider discrepancy, missing-header versus zero-byte distinction, and stale-observation upsert. The timezone fingerprint comes from generating the rollout filename in local time and parsing its timezone-free timestamp as UTC; it helps distinguish this fallback path.

Complete offline reproduction — save as reproduce_blank_provider.py
#!/usr/bin/env python3
"""Offline, synthetic Codex blank-provider reproduction (macOS, Python stdlib).

python3 reproduce_blank_provider.py --work-dir ./work/repro

Only creates synthetic files under --work-dir. Never opens the real Codex DB,
configuration, sessions, or credentials. The child process has no inherited
credentials, no network access, and cannot read the real user's home contents.
It performs no model inference. No SQL INSERT/UPDATE is issued by this harness.
The stale-snapshot case takes and releases a lock on its synthetic database.
"""
import argparse
import json
import pathlib
import queue
import re
import sqlite3
import subprocess
import tempfile
import threading
import time
import uuid

DEFAULT_BINARY = '/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex'
UTC_CREATED = 1767268800  # 2026-01-01T12:00:00Z


class Server:
    def __init__(self, binary, work_dir):
        self.home = pathlib.Path(tempfile.mkdtemp(prefix='synthetic-', dir=work_dir)).resolve()
        (self.home / 'tmp').mkdir()
        (self.home / 'config.toml').write_text(
            'model = "gpt-5"\ncli_auth_credentials_store = "file"\n[analytics]\nenabled = false\n'
        )
        user_home = pathlib.Path.home().resolve()
        quote = lambda p: json.dumps(str(p))
        profile = (
            '(version 1) (allow default) (deny network*) '
            f'(deny file-read* (subpath {quote(user_home)})) '
            f'(allow file-read-metadata (subpath {quote(user_home)})) '
            f'(allow file-read* (subpath {quote(self.home)})) '
            f'(allow file-read* (literal {quote(binary)})) '
            '(deny file-write*) '
            f'(allow file-write* (subpath {quote(self.home)}) (literal "/dev/null")) '
            '(deny mach-lookup (global-name "com.apple.securityd"))'
        )
        env = {
            'PATH': '/usr/bin:/bin:/usr/sbin:/sbin',
            'CODEX_HOME': str(self.home),
            'TMPDIR': str(self.home / 'tmp'),
            'TZ': 'Asia/Seoul',
            'RUST_LOG': 'codex_rollout=debug,codex_thread_store=debug,codex_state=debug',
        }
        self.log_path = self.home / 'stderr.log'
        self.log = self.log_path.open('w')
        self.proc = subprocess.Popen(
            ['/usr/bin/sandbox-exec', '-p', profile, str(binary), 'app-server'],
            cwd=self.home, env=env, text=True, bufsize=1,
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log,
        )
        self.messages = queue.Queue()
        self.serial = 0
        threading.Thread(target=self._read, daemon=True).start()
        try:
            self.initialization = self.call('initialize', {
                'clientInfo': {'name': 'independent_qa', 'version': '1.0'},
                'capabilities': {'experimentalApi': True},
            })
            self.send({'method': 'initialized', 'params': {}})
            time.sleep(0.5)  # Let empty-home startup/backfill finish before adding fixtures.
        except Exception:
            self.close()
            raise

    def _read(self):
        for line in self.proc.stdout:
            try:
                self.messages.put(json.loads(line))
            except ValueError:
                pass

    def send(self, message):
        self.proc.stdin.write(json.dumps(message) + '\n')
        self.proc.stdin.flush()

    def call(self, method, params):
        self.serial += 1
        request_id = self.serial
        self.send({'id': request_id, 'method': method, 'params': params})
        end = time.monotonic() + 15
        while time.monotonic() < end:
            try:
                response = self.messages.get(timeout=max(0.01, end - time.monotonic()))
            except queue.Empty:
                raise RuntimeError(f'Timeout calling {method}; exit={self.proc.poll()}')
            if response.get('id') == request_id:
                return response
        raise RuntimeError(f'Timeout calling {method}')

    def db(self, thread_id):
        # Read-only connection to THIS synthetic home, never to the user's home.
        with sqlite3.connect(f'file:{self.home}/state_5.sqlite?mode=ro', uri=True) as db:
            db.row_factory = sqlite3.Row
            row = db.execute(
                'SELECT model_provider, cli_version, thread_source, source, created_at, '
                'created_at_ms, history_mode FROM threads WHERE id=?', (thread_id,)
            ).fetchone()
            return dict(row) if row else None

    def close(self):
        self.proc.terminate()
        try:
            self.proc.wait(timeout=3)
        except subprocess.TimeoutExpired:
            self.proc.kill()
            self.proc.wait()
        self.log.close()


def fixture(server, kind, history_mode='paginated'):
    thread_id = str(uuid.uuid4())
    folder = server.home / 'sessions/2026/01/01'
    folder.mkdir(parents=True, exist_ok=True)
    # Local filename is UTC+9, while session_meta is UTC.
    path = folder / f'rollout-2026-01-01T21-00-00-{thread_id}.jsonl'
    records = [
        {'timestamp': '2026-01-01T12:00:00.000Z', 'ordinal': 0, 'type': 'session_meta',
         'payload': {'id': thread_id, 'timestamp': '2026-01-01T12:00:00.000Z',
                     'cwd': str(server.home), 'originator': 'synthetic QA',
                     'cli_version': '0.162.0-alpha.17.2', 'source': 'vscode',
                     'model_provider': 'openai', 'base_instructions': {'text': 'Synthetic.'},
                     'history_mode': history_mode, 'thread_source': 'agent_created_thread'}},
        {'timestamp': '2026-01-01T12:00:00.000Z', 'ordinal': 1, 'type': 'event_msg',
         'payload': {'type': 'user_message', 'message': 'Synthetic.',
                     'images': [], 'local_images': [], 'text_elements': []}},
    ]
    full = ''.join(json.dumps(record) + '\n' for record in records)
    event = json.dumps(records[1]) + '\n'
    path.write_text({'valid': full, 'empty': '', 'event': event,
                     'malformed': '{"incomplete":\n' + event}[kind])
    return thread_id, path, full


def summary(response):
    if 'error' not in response:
        thread = response.get('result', {}).get('thread', {})
        return {'ok': True, **({'api_model_provider': thread['modelProvider']}
                             if 'modelProvider' in thread else {})}
    error = response['error']
    # Public results contain neither absolute paths nor generated UUIDs.
    message = re.sub(r'/[^\s:]+', '<SYNTHETIC_PATH>', error['message'])
    message = re.sub(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', '<SYNTHETIC_ID>', message)
    return {'ok': False, 'code': error['code'], 'message': message}


def run_case(binary, work_dir, kind, mode='paginated', stale=False):
    server = Server(binary, work_dir)
    try:
        thread_id, path, full = fixture(server, kind, mode)
        name_params = {'threadId': thread_id, 'name': 'Synthetic title'}
        assert server.db(thread_id) is None
        if stale:
            lock = sqlite3.connect(server.home / 'state_5.sqlite')
            lock.execute('BEGIN IMMEDIATE')
            responses = queue.Queue()
            def call_name():
                try:
                    responses.put(server.call('thread/name/set', name_params))
                except Exception as error:
                    responses.put(error)
            worker = threading.Thread(target=call_name)
            worker.start()
            try:
                end = time.monotonic() + 5
                marker = 'Resumed rollout with 1 items, thread ID: None'
                while marker not in server.log_path.read_text():
                    if time.monotonic() > end:
                        raise RuntimeError('Did not reach metadata snapshot before timeout')
                    time.sleep(0.01)
                path.write_text(full)  # Valid BEFORE the app-server's SQL write can commit.
            finally:
                lock.rollback()  # Harness never INSERTs or UPDATEs a row.
                lock.close()
            worker.join(timeout=16)
            first = responses.get(timeout=1)
            if isinstance(first, Exception):
                raise first
        else:
            first = server.call('thread/name/set', name_params)
        after_first = server.db(thread_id)
        path.write_text(full)
        retry = server.call('thread/name/set', name_params)
        after_retry = server.db(thread_id)
        read = server.call('thread/read', {'threadId': thread_id, 'includeTurns': False})
        after_read = server.db(thread_id)
        resume = server.call('thread/resume', {'threadId': thread_id, 'cwd': str(server.home)})
        expected_bad = kind in ('event', 'malformed') and mode == 'paginated'
        assert 'result' in retry
        assert after_retry['model_provider'] == ('' if expected_bad else 'openai')
        assert after_retry['created_at'] - UTC_CREATED == (32400 if expected_bad else 0)
        if expected_bad:
            assert after_retry['cli_version'] == '' and after_retry['thread_source'] is None
            assert resume['error']['message'] == 'failed to load configuration: Model provider `` not found'
        else:
            assert 'result' in resume, resume
        if stale:
            assert 'result' in first
        if kind == 'empty':
            assert after_first is None
        return {'case': 'stale_snapshot' if stale else kind + '_' + mode,
                'first_name': summary(first), 'db_after_first_name': after_first,
                'retry_name': summary(retry), 'db_after_retry': after_retry,
                'read': summary(read), 'db_after_read': after_read, 'resume': summary(resume),
                'created_at_offset_seconds': after_retry['created_at'] - UTC_CREATED,
                'assertions_passed': True}
    finally:
        server.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--binary', default=DEFAULT_BINARY)
    parser.add_argument('--work-dir', required=True)
    parser.add_argument('--repeats', type=int, default=1)
    args = parser.parse_args()
    work_dir = pathlib.Path(args.work_dir).resolve()
    work_dir.mkdir(parents=True, exist_ok=True)
    binary = pathlib.Path(args.binary).resolve()
    results = []
    for repeat in range(args.repeats):
        for kind in ['valid', 'empty', 'event', 'malformed']:
            results.append(run_case(binary, work_dir, kind))
        results.append(run_case(binary, work_dir, 'event', mode='legacy'))
        results.append(run_case(binary, work_dir, 'event', stale=True))
    print(json.dumps({'results': results, 'passed': len(results),
                      'network_policy': 'macOS sandbox denies network*',
                      'limitations': 'Stages missing/unparseable metadata; does not prove the original natural race.'}, indent=2))


if __name__ == '__main__':
    main()

heznpc avatar Oct 15 '26 03:10 heznpc

Additional anonymized Windows reproduction of the same failure:

  • Codex Desktop on Windows, installed version 26.1117.41037.
  • The rollout's first session_meta, the desktop thread catalog, and global config all identify the provider as openai.
  • The corresponding paginated-history row in state_5.sqlite instead had model_provider='', cli_version='', thread_source=NULL, and empty first_user_message/title fields, while the display name was present.
  • The SQLite created_at was exactly 28,800 seconds later than the UTC timestamp in the rollout header (UTC+8).
  • Resume failed with Model provider `` not found. After a backup and an offline update of only that row's provider to openai, the thread resumed and could be read. The provider field later regressed once.
  • This metadata fingerprint is consistent with an incomplete rollout-metadata read/repair being persisted as authoritative, although I cannot identify which exact request or race triggered this Windows instance.

A durable fix should avoid persisting incomplete provider metadata and should reconcile an existing blank provider from a valid session_meta during paginated thread naming/resume/list recovery, with regression coverage for the incomplete/stale-read case. No thread IDs, user paths, or conversation text are included.

glehuy-ai avatar Nov 22 '26 13:11 glehuy-ai