Skip to content

fix(agent-core-v2): rebuild session and search indexes on storage failures, journal session-index freshness - #3694

Merged
sailist merged 6 commits into
MoonshotAI:mainfrom
sailist:bug-181-09-10-index-write-failure-degradation
Sep 10, 2026
Merged

sailist merged 6 commits into
MoonshotAI:mainfrom
sailist:bug-181-09-10-index-write-failure-degradation

Conversation

@sailist

@sailist sailist commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • New classifyStorageError in 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.
  • Session-index query store: runtime failures go through the wipe-and-reproject rebuild channel, now guarded by a live-lock probe so a peer's store is never deleted, and the rebuild latch resets so repeated rebuilds actually work.
  • Search worker: on rebuild-class failure (or 5 consecutive sync failures) the index directory is wiped and reopened; the degraded window surfaces through the existing building/ready/readonly status instead of per-session warn spam.
  • The in-place WAL recovery's fs.truncate now 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:

  • Search sync persists per-file offset/turn/step state in every batch, so progress survives a failed batch and is never re-read or re-written (the 382 MB duplicate-write WAL pattern).
  • Each sync round has a byte (64 MB) and wall-clock (30 s) budget; a truncated round reschedules itself and drains the backlog incrementally — a rebuild is just "sync from offset zero".
  • Search index runs with valueMode: 'disk' (an existing engine-supported larger-than-RAM mode), decoupling worker memory from corpus size.
  • Worker crash backoff decays instead of resetting to 500 ms after any >60 s session.
  • Sessions whose transcripts stay unreadable after 5 sync rounds are skipped with a 5-minute cooldown instead of forever, and retried immediately once their content changes.

Session-index freshness is journal-driven (no steady-state full scans):

  • Session mutations register a dirty mark (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.
  • The periodic freshness check is readdir-only (dirty set + session count): no per-session stat calls (measured ≈7 ms / 0 stats on 6k sessions, down from ≈130–280 ms / 12k stats).
  • Reconciliation is targeted: journaled ids plus id-set differences (which catch unjournaled adds/deletes) drive upserts/removals against only the changed sessions' summaries (2 reads per change instead of 2 per session); workspace counters update by deltas. A schema-version bump (1 → 2) migrates existing manifests through one full reprojection.
  • Startup reconciliation failure without a published generation now surfaces as degraded instead of silently serving nothing.
  • Accepted trade-off: edits made outside Kimi processes (hand-edited session files leave no dirty mark) are not detected until restart/rebuild.

Background load made bounded and observable:

  • The 60 s reconcile is skipped when the journal/count check shows no session changes.
  • Startup with a stale manifest incrementally reconciles the published generation instead of always doing a full reprojection into a new one (full reprojection is kept for schema changes/corruption).
  • Mirror/degraded log lines are emitted once per failure episode (plus one on recovery) instead of on every retry; compaction and generation-publish failures surface via status and transition logs instead of being swallowed.

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

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: the issue must have a maintainer's /approve).

@changeset-bot

changeset-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 1d08628

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@pkg-pr-new

pkg-pr-new Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@1d08628
npx https://pkg.pr.new/@moonshot-ai/kimi-code@1d08628

commit: 1d08628

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment on lines +502 to +504
if (syncBudgetExhausted(budget)) {
truncated = true;
break;

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 Badge 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;

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 Badge 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@sailist

sailist commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment on lines 120 to 121
if (probeError instanceof LockError) throw cause;
await fsp.rm(this.dir, { recursive: true, force: true });

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 Badge 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 👍 / 👎.

@sailist

sailist commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread packages/minidb/src/wipe.ts Outdated
return 'locked';
}
try {
await fs.rm(opts.dir, { recursive: true, force: true });

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 Badge 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 👍 / 👎.

Comment on lines 134 to 135
await this.rebuild(error);
return op(await this.openDb());

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 Badge 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 👍 / 👎.

Comment on lines 501 to 503
} catch (error) {
if (classifyStorageError(error) === 'rebuild') throw error;
this.log.warn('global search: failed to index session', {

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 Badge 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 👍 / 👎.

Comment on lines +225 to +226
const sessionIds = await listSessionIds(storage, sessionsScope, workspaceId);
sessionCount += sessionIds.length;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@sailist

sailist commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment on lines +517 to +519
if ((this.sessionSyncFailures.get(summary.id) ?? 0) >= SESSION_SYNC_FAILURE_SKIP_LIMIT) {
continue;
}

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 Badge 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 👍 / 👎.

Comment on lines 134 to +137
try {
return await op(await this.openDb());
const result = await op(db);
this.transientFailures = 0;
return result;

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 Badge 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 👍 / 👎.

Comment on lines +165 to +169
} catch (error) {
this.log.warn('session index startup reconciliation failed; serving the published generation', {
error: String(error),
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

…ed startup reconciliation, and cool down search session skips
@sailist sailist changed the title fix(agent-core-v2): rebuild session and search indexes on unrecoverable storage failures fix(agent-core-v2): rebuild session and search indexes on storage failures, journal session-index freshness Sep 10, 2026
@sailist

sailist commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment on lines +529 to +531
if (syncBudgetExhausted(budget)) {
truncated = true;
break;

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 Badge 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]);

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 Badge 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 👍 / 👎.

Comment on lines +354 to +355
try {
await markSessionDirty(this.storage, this.sessionsScope, id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@sailist
sailist merged commit f728cb1 into MoonshotAI:main Sep 10, 2026
16 checks passed
7723qqq added a commit to 7723qqq/kimi-code that referenced this pull request Sep 17, 2026
…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.
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.

1 participant