[Bug] Concurrent session saves from two processes drop entries from sessions.json, so saved sessions disappear from resume
Description
When two Nanocoder processes save a session at about the same time, one of the two entries is dropped from sessions.json. The session file stays on disk, but the session no longer shows up in /resume, --continue, --resume last or ACP listSessions. In the affected project, nanocoder --resume last prints No sessions found. and exits 1. Nanocoder's own nanocoder storage --format json flags it as session_unindexed: Session file is absent from index.
Every CLI/TUI process and the ACP server (VS Code extension) share one session store. So this is reachable with two terminals open in different projects, a terminal plus the VS Code extension (ACP saves at the end of every prompt), or scripts that start parallel nanocoder run jobs.
Root cause (links pinned to 8c50d68d):
- The read-modify-write of
sessions.jsonis guarded only by an in-process promise lock:indexWriteLock, used by the index-lock helper. Each process reads the index, adds its own entry and atomically renames its copy into place, so the last writer drops the other process's entry. The comment says the lock exists "to prevent lost updates from concurrent autosave/resume", but it can't do that across processes. - The dropped entry is never repaired.
readIndex()only rebuilds when the index is unparseable or has no valid entries. An index that is valid but incomplete is trusted as-is. - A missing
sessions.jsonisn't rebuilt either.initialize()writes[]before anyreadIndex(), so the "index missing" rebuild path is never reached.
Environment
- OS: macOS 26.6.2
- Node version: v22.23.3
- Nanocoder version: 1.31.0 (published npm package), and current
main(8c50d68d) - Provider: any (the session store isn't provider-specific). I used a local OpenAI-compatible endpoint for the end-to-end runs.
- Model: any
Steps to Reproduce
Deterministic version: two processes save through the production SessionManager at the same moment. Run it from a built checkout (pnpm run build), with throwaway dirs.
- Save this as
/tmp/race-worker.mjs:import path from 'node:path'; import {pathToFileURL} from 'node:url'; const [, , startAtMs, tag] = process.argv; const {sessionManager} = await import( pathToFileURL(path.join(process.env.NC_ROOT, 'dist/session/session-manager.js')).href ); await sessionManager.initialize(); const wait = Number(startAtMs) - Date.now(); // start both processes at the same instant if (wait > 0) await new Promise(r => setTimeout(r, wait)); await sessionManager.createSession({ title: tag, messageCount: 1, provider: 'mock', model: 'mock-model', workingDirectory: process.cwd(), messages: [{role: 'user', content: tag}], }); - From the repo root:
export NANOCODER_DATA_DIR=$(mktemp -d) NANOCODER_CONFIG_DIR=$(mktemp -d) NC_ROOT=$PWD start=$(( $(node -e 'console.log(Date.now())') + 1500 )) node /tmp/race-worker.mjs $start A & node /tmp/race-worker.mjs $start B & wait ls "$NANOCODER_DATA_DIR/sessions" # two session files + sessions.json node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).length)' "$NANOCODER_DATA_DIR/sessions/sessions.json" - The index often lists 1 session even though 2 session files exist (3 of 5 runs of this exact snippet in a quick check; 19 of 20 in a longer harness). Running the two
nodecommands one after the other always lists 2.
End-to-end version: start nanocoder run "<prompt>" in two terminals (two different projects, same data dir) at about the same moment. When an entry is lost, nanocoder --resume last in that project prints No sessions found., and nanocoder storage --format json reports session_unindexed.
Expected Behavior
Every saved session stays listed and resumable, whichever processes saved it and when. The lock's own comment describes this ("prevent lost updates from concurrent autosave/resume"), as do the resume features in docs/features/session-management.md. An index that has drifted from the session files on disk should be repaired, not trusted.
Actual Behavior
One process's entry is silently dropped from sessions.json, and nothing ever adds it back. The session can only be resumed by its raw UUID, if you happen to know it.
From reading the code (not reproduced): retention and maxSessions pruning iterate the index, so the unindexed file is never cleaned up. The startup artifact sweep (#1704) also treats it as an unknown session.
Logs/Screenshots
Observed frequencies:
| Setup | Lost an entry |
|---|---|
Module-level race with a start barrier (as above), main |
19/20 trials |
| Same, published 1.31.0 | 10/10 trials |
| Same, sequential control | 0/10 and 0/5 trials |
Two real concurrent nanocoder runs, no barrier |
4/12 trials (about 1 in 12 in an earlier batch) |
One lost-entry trial with the real CLI:
trial 6: session files=2 indexed=1 [task in projB]
on disk: 2c7aa66a-… "task in projA"
on disk: f810dad9-… "task in projB"
nanocoder storage --format json:
[{"code":"session_unindexed","message":"Session file is absent from index","severity":"warning", …}]
'nanocoder --resume last' in projA:
No sessions found.
exit=1
Additional Context
- [x] I have searched existing issues to ensure this is not a duplicate (open and closed issues/PRs for
sessions.jsonconcurrency,session_unindexed, "No sessions found", index lock/race, missing resume entries) - [ ] I can reproduce this issue consistently (it's a race: 19/20 with the barrier repro, about 1 in 3 to 1 in 12 with two real concurrent runs, never when run sequentially)
- [x] This issue occurs with the latest version of nanocoder
Proposed fix:
- Make the index update safe across processes. Either take a cross-process lock around the read-modify-write (for example an exclusive-create lock file next to
sessions.json, with stale-lock handling), or re-read and merge the on-disk index just before the atomic rename, retrying if it changed. - Make the index self-healing. On load, reconcile
sessions.jsonwith the valid session files on disk: add unindexed files and drop entries whose file is gone.nanocoder storagealready detectssession_unindexed, so the reconcile logic can share that check. Also make the "index missing" rebuild path reachable.
Regression tests:
- A two-process concurrent-save spec, like the repro above, asserts that both sessions are indexed.
- An index missing one entry, or missing entirely, gets reconciled on the next load.
@addyCooks I'd like to work on this one too. Could you assign it to me if that works for you?
Assigning you @diyaavirmani, go ahead