Repository navigation
fix(agent-core-v2): rebuild session and search indexes on storage failures, journal session-index freshness - #3694
Conversation
…le storage failures
|
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 519d07a2b5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (syncBudgetExhausted(budget)) { | ||
| truncated = true; | ||
| break; |
There was a problem hiding this comment.
Propagate in-file budget exhaustion to the sync outcome
When the byte or time budget expires while processing the final or only session, this outer guard is never reached again because syncWireFile merely breaks its inner loop. The pass therefore returns truncated: false, sets fullSyncDone, and publishes stats even though the file metadata contains only a partial offset, so GlobalSearchService does not schedule the follow-up pass and search reports a partial index as ready. Propagate the in-file exhaustion state through syncSession so the returned outcome remains truncated.
Useful? React with 👍 / 👎.
| return; | ||
| } | ||
| this.generation = manifest.seq; | ||
| if (await this.manifestFresh(manifest)) return; |
There was a problem hiding this comment.
Do not skip reconciliation using only the maximum mtime
When an authoritative session disappears without updating session_index.jsonl—for example, its directory is removed but the subsequent query-store deletion fails—the maximum mtime of the remaining state files stays the same or decreases. manifestFresh consequently returns true here, and the periodic reconciliation that previously removed absent records is skipped forever, leaving deleted sessions and workspace counts in list/count results. Freshness needs to account for set deletions, or the periodic loop must still occasionally reconcile.
Useful? React with 👍 / 👎.
| const chunk = Buffer.allocUnsafe(WIRE_READ_CHUNK_BYTES); | ||
| while (position < size) { | ||
| if (this.disposed) return; | ||
| if (syncBudgetExhausted(budget)) break; |
There was a problem hiding this comment.
Allow a record to make progress across the sync budget
If a single JSONL record is larger than the 64 MiB round budget, this break discards the accumulated pending bytes while byteCursor remains at the preceding newline. Every subsequent pass starts from that same offset and rereads the same 64 MiB without ever indexing or advancing past the record; when more sessions follow, this can also create an indefinitely rescheduled I/O loop. Either finish the current record after the round budget is reached or persist enough partial-record state to resume it.
Useful? React with 👍 / 👎.
…n count in index freshness
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 412a8fd628
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (probeError instanceof LockError) throw cause; | ||
| await fsp.rm(this.dir, { recursive: true, force: true }); |
There was a problem hiding this comment.
Acquire shard locks before deleting the query store
When another process still holds a query-store shard writer, this guard cannot detect it: ClusterDb.open() only creates the lazy ShardLockPool, and no shard lock is acquired until a read or write is performed. Consequently, after a rebuild-class error—or five ordinary lock timeouts—the probe succeeds and rm deletes the directory underneath the live writer, risking loss or corruption of its WAL/state. Probe the shards and retain their locks through removal, or abort rebuilding if any shard is locked.
AGENTS.md reference: AGENTS.md:L32-L32
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d778bf6872
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| return 'locked'; | ||
| } | ||
| try { | ||
| await fs.rm(opts.dir, { recursive: true, force: true }); |
There was a problem hiding this comment.
Preserve exclusion while removing the store directory
The new direct lock acquisition still leaves a race because fs.rm unlinks the lock files inside the directory before the recursive removal has finished. If another process opens the store after db.lock (or a shard lock) is removed, it can acquire a new lock and create files that this in-progress rm then deletes or corrupts; isolate the directory with an atomic rename while the locks remain at their original paths, then remove the isolated tree. This is fresh evidence beyond the earlier lazy-lock issue: locks are now acquired, but the wipe itself destroys the exclusion mechanism.
AGENTS.md reference: packages/minidb/AGENTS.md:L3-L3
Useful? React with 👍 / 👎.
| await this.rebuild(error); | ||
| return op(await this.openDb()); |
There was a problem hiding this comment.
Restart the projection after wiping the query store
When a rebuild-class error occurs after an earlier chunk of a session-index projection has already succeeded, rebuilding here deletes that earlier chunk and retries only the current op. The projector then writes the remaining chunks and publishes a checkpoint containing the authoritative session count, so a store with more than 500 sessions can be marked fresh and ready while its first chunks are permanently absent. The rebuild needs to invalidate and restart the enclosing projection rather than transparently retrying one query-store operation.
Useful? React with 👍 / 👎.
| } catch (error) { | ||
| if (classifyStorageError(error) === 'rebuild') throw error; | ||
| this.log.warn('global search: failed to index session', { |
There was a problem hiding this comment.
Let transient session failures reach the sync retry counter
If syncSession fails with a persistent transient storage error such as EPERM or EIO, this catch logs and suppresses it, so runSync returns successfully and the outer consecutiveSyncFailures counter is reset to zero. The pass can consequently set fullSyncDone and report the index ready while omitting that session, and repeated searches merely retry and log the same failure without ever reaching the five-pass rebuild policy. Propagate storage failures to sync() or explicitly account for them in the outcome.
Useful? React with 👍 / 👎.
| const sessionIds = await listSessionIds(storage, sessionsScope, workspaceId); | ||
| sessionCount += sessionIds.length; |
There was a problem hiding this comment.
Count only sessions represented by the projection
When an unchanged session directory has no readable state document, readSessionSummary filters it out of summaries, so the checkpoint stores a smaller sourceSessionCount; this freshness scan nevertheless counts the raw directory entry. Such an orphaned or partially corrupted directory therefore makes every periodic tick consider the manifest stale and perform the full reconciliation scan forever, defeating the new bounded-background-load behavior. Compute freshness from readable summaries, or persist and compare the same raw count on both paths.
Useful? React with 👍 / 👎.
…s, and account sync failures
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b041a7bfdf
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if ((this.sessionSyncFailures.get(summary.id) ?? 0) >= SESSION_SYNC_FAILURE_SKIP_LIMIT) { | ||
| continue; | ||
| } |
There was a problem hiding this comment.
Retry sessions after the failure skip threshold
When opening or reading a wire file fails five times—for example, during a temporary permission or filesystem outage—this branch permanently skips that session for the lifetime of the core. Because skipped sessions no longer contribute to failures, the next pass can set fullSyncDone and report the index ready, even after the file becomes readable again. Fresh evidence beyond the earlier suppressed-error path is that the new threshold explicitly prevents all subsequent retry attempts; retry after a cooldown or when the transcript metadata changes instead.
Useful? React with 👍 / 👎.
| try { | ||
| return await op(await this.openDb()); | ||
| const result = await op(db); | ||
| this.transientFailures = 0; | ||
| return result; |
There was a problem hiding this comment.
Preserve transient failure streaks across successful reads
When writes persistently fail with a transient error such as EIO while reads still succeed, resetting the global counter on every successful operation prevents escalation indefinitely. Each reconciliation or mirror flush performs successful getCheckpoint/getMany calls before the failing batch, so every write failure is counted as the first one and the store is never rebuilt; the published session index can consequently remain stale while still being served as ready. Track failures per operation class or reset the streak only after a successful write/reconciliation.
Useful? React with 👍 / 👎.
| } catch (error) { | ||
| this.log.warn('session index startup reconciliation failed; serving the published generation', { | ||
| error: String(error), | ||
| }); | ||
| } |
There was a problem hiding this comment.
Re-enter projection when reconciliation removes the checkpoint
When startup finds a stale manifest and reconciliation triggers a query-store rebuild, the rebuild wipes the checkpoint and the projector rejects, but this catch suppresses the error under the assumption that the published generation still exists. The following checkpoint read returns undefined, leaving the service in preparing; no reconciliation timer is installed, and reads in that state do not call prepare, so the read model never rebuilds without an external second prepare() call. If reconciliation removed the manifest, mark the service degraded or immediately start a fresh projection.
Useful? React with 👍 / 👎.
…ty journal and targeted reconciliation
…ed startup reconciliation, and cool down search session skips
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d08628bb3
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (syncBudgetExhausted(budget)) { | ||
| truncated = true; | ||
| break; |
There was a problem hiding this comment.
Carry a session cursor across timed sync rounds
When merely walking the unchanged prefix of a sufficiently large or slow session store consumes the 30-second deadline, this guard ends the pass before later sessions are visited. The rescheduled pass starts again at sessions[0], and checking those unchanged sessions still consumes the same time, so the tail is never indexed and the service continuously reschedules syncs. Persist or rotate a session-level cursor between truncated rounds so time-budget exhaustion makes forward progress.
Useful? React with 👍 / 👎.
|
|
||
| await this.batchChunks([...upserts, ...removals]); | ||
| await this.writeCounters(counters, counts); | ||
| await this.batchChunks([...upserts, ...removals, ...counterOps]); |
There was a problem hiding this comment.
Keep counter deltas atomic with reconciled records
When reconciliation produces more than 500 operations, batchChunks can commit the summary upserts/removals and then fail or crash before the later counter operations. The dirty marks remain, but the retry reads the already-updated summaries as olds, derives no deltas, and therefore can never repair the missing workspace-count changes. This is especially damaging under the storage failures this change is intended to recover from; record mutations and their counter updates must be committed atomically or the retry must recompute affected counters from authoritative state.
Useful? React with 👍 / 👎.
| try { | ||
| await markSessionDirty(this.storage, this.sessionsScope, id); |
There was a problem hiding this comment.
Decrement counters before discarding the deleted summary
When a session is deleted from a workspace that still contains other sessions, remove first deletes the only cached summary carrying its workspace and archived state and then records only the ID as dirty. Targeted reconciliation subsequently gets undefined from olds, so it cannot decrement that workspace's counter; because the workspace still exists, the whole-counter cleanup also does not remove it, and countFromReadModel remains permanently one too high. Preserve the old summary long enough to update the counter, ideally in the same batch as the deletion.
Useful? React with 👍 / 👎.
…runtimes Two product commits landed on upstream/main after the 2.0.0 tag; the tag was already merged, so these are applied on top. install-desktop rename (MoonshotAI#3864): `kimi install-app` becomes `kimi install-desktop` with the old name kept as a hidden alias, matching upstream's rename; the description goes through t() and the bilingual reference docs and the slash-commands tables are synced. VS Code extension joins the shared telemetry pipeline (MoonshotAI#3852): the shared telemetry package gains the initiallyEnabled bootstrap option and the enable/disable API from upstream, a new apps/vscode telemetry module wires the extension to it (first-launch tracking, config + VS Code telemetry settings, region-derived endpoint), and the runtime passes the telemetry client into the SDK session. That commit also retargeted the telemetry crash tests at an API the merge had already renamed, and three of its in-process tests pin Node's synchronous rethrow out of process.emit('unhandledRejection') — a semantic Bun does not have (it defers the rethrow to uncaughtException). The fork's gate runs the suite under Bun, so: the crash-worker subprocess now explicitly resolves a real Node executable (skipping Bun's `bun-node-*` PATH shims, which also masquerade as process.execPath under `bun --bun`) and resolves tsx from the workspace's own node_modules so Node can find esbuild there; the three Node-only rethrow assertions early-return on a Bun runtime and stay fully active when the suite runs under Node (86/86 there). The abort-does-not-crash coverage (MoonshotAI#2801) that upstream's rewrite dropped is restored as a subprocess test, which also replaces a Windows-timer-sensitive polling helper. MoonshotAI#3694 is recorded not-applicable in the delta allowlist: the minidb half (the lock-aware wipe) shipped with the 2.0.0 merge itself, and the agent-core-v2 half (rebuilding session/search indexes on storage failures) has no counterpart — the engine's search is a SQL LIKE query over the messages table and the transcript is re-folded from the event store on read, so there is no derived index to go stale. Verification: bun --bun run test 8311 passed / 0 failed; the telemetry package also passes 86/86 under plain Node; tsc clean for apps/vscode and apps/kimi-code; parity, delta, no-legacy-engine and locale gates all pass.
Related Issue
Related to #3535 (same family of permanent minidb write failures; this PR changes the failure posture to bounded degradation and automatic rebuild, but does not remove the hardlink dependency tracked there).
Problem
User report: on Windows with a large session store (≈1.8 GB index, ≈382 MB WAL), the log repeatedly prints "index shard write failed" and the client gets progressively slower until it is unusable.
Root cause (verified on main): the session-index read model and the global search index are rebuildable derived caches over the transcript/session files, but they are protected with authoritative-store durability semantics. A single transient I/O failure (e.g. an antivirus or indexer holding the WAL on Windows) poisons the WAL and permanently disables writes for the process lifetime (
WAL_WRITE_DISABLED). Every later failure is then amplified: the search sync persists per-file progress only in the final batch, so any failed batch discards the whole round's work and re-reads the same backlog on every pass while duplicating it into the WAL; batch rollbacks abort generation builds, so no new checkpoint is ever published; and the search worker keeps the whole corpus in the V8 heap (memory valueMode), so a large index eventually OOM-loops on a defeated 500 ms restart backoff. The session index adds its own background load: an unconditional full reconcile every 60 s and an almost-guaranteed full reprojection on every startup. Since #3552 made both always-on in 0.42.0, large-store users hit this chronically.What changed
Recovery posture — errors drive bounded recovery instead of infinite retry plus log spam:
classifyStorageErrorin minidb: poison/corruption (WAL_WRITE_DISABLED,WAL_POISONED,CorruptFrameError,SyntaxError) → rebuild; locks/errno/unknown → transient; unknowns escalate to rebuild after 5 consecutive failures, tracked independently per operation kind (reads and writes no longer escalate each other). Shared by both consumers.fs.truncatenow retries EPERM with the same bounded policy as rename-replace, so a transient Windows file lock no longer becomes a permanent write-disable.Rebuild is routine, not catastrophic:
valueMode: 'disk'(an existing engine-supported larger-than-RAM mode), decoupling worker memory from corpus size.Session-index freshness is journal-driven (no steady-state full scans):
sessions/.index-dirty/<id>.<ms>) through the session-index mirror — before the database gate, so one-shot CLI processes are registered too; deletions register through the index remove path.Background load made bounded and observable:
Verification: focused suites (minidb degrade/generation/wal, query-store, sessionIndex, kap-server search) plus the full repo suite (879 files / 15822 tests, two full combined runs) pass on Linux; the Windows-only retry behavior passes on a Windows host.
Checklist
/approve).