Skip to content

test(kap-server): wait for search index readiness in route tests - #4909

Merged
Grapedge merged 1 commit into
mainfrom
test/deflake-search-route-ready
Nov 13, 2026
Merged

Grapedge merged 1 commit into
mainfrom
test/deflake-search-route-ready

Conversation

@kimi-agent-bot

Copy link
Copy Markdown
Collaborator

Requirement or Bug

packages/kap-server/test/search/searchRoute.test.ts 在 CI 分片运行时偶发失败(例如 searches across sessions and returns the wire-shaped page 在 user 与 assistant 命中均已通过后,断言 role === 'title' 得到 false)。本 PR 修复该路由测试的索引就绪轮询条件,使全文与字面量两条路由测试均在首轮后台索引真正完成后再执行断言。

Bug Reproduction Steps

  1. 启动开启全局搜索(KIMI_CODE_GLOBAL_SEARCH=1)且预置单会话 s1(含 wire.jsonl 与 state.json 标题)的 kap-server。
  2. 在后台首轮 syncSession 刚完成 wire.jsonl 批次写入但尚未写入 s1/$title 的异步窗口内调用 POST /api/v1/search 查询 { query: "苹果" }(本地可在 SearchIndexCore.syncSession 写入 titleKey 前注入 150ms 延迟稳定复现)。
  3. 观察原测试因 body.data.items.length > 0 提前退出轮询,随后在第 164 行 expect(body!.data.items.some((h) => h.role === 'title')).toBe(true) 报 AssertionError: expected false to be true。

Root Cause

根本修复。

  1. startServer()(packages/kap-server/src/start.ts)初始化 IGlobalSearchService 时,构造函数异步触发后台 requestSync(),不阻塞服务启动返回;搜索 Worker(packages/kap-server/src/search/worker/entry.ts)并发处理 sync 与 search 请求,两者在 SearchIndexCore 的 await 边界交错执行。
  2. SearchIndexCore.syncSession()(packages/kap-server/src/search/indexCore.ts)对单个会话分三步写入 MiniDb:
    • 先执行 await db.set(metaKey, meta) 写入会话元数据 \0meta\session\s1(含目录身份与标题);
    • 再执行 syncWireFile(),通过 await db.batch(ops) 将 user 与 assistant 两条 MessageDoc 同步写入内存与全文索引,随后等待 WAL 落盘及 await handle.close();
    • 最后执行 await db.set(titleKey, doc) 写入 s1/$title(role: 'title' 的 TitleDoc),并在整轮 runSync() 写完 STATS_KEY 后将 this.fullSyncDone 置为 true(index_state.state 从 'building' 转为 'ready')。
  3. 原测试在 searches across sessions and returns the wire-shaped page 与 serves literal mode through the wire 中均以 if (body.data.items.length > 0) break; 作为轮询结束条件。当查询恰好落在 MessageDoc 已入索引而 TitleDoc 尚未写入的异步 I/O 窗口时,接口返回 [user, assistant](items.length === 2、index_state.state === 'building'),导致轮询在半成品索引状态提前退出。
sequenceDiagram
    participant Test as searchRoute.test.ts
    participant Worker as SearchWorker / SearchIndexCore
    participant DB as MiniDb

    Worker->>DB: set("\0meta\session\s1", meta)
    Worker->>DB: batch([user MessageDoc, assistant MessageDoc, fileMeta])
    Note over Worker: await WAL flush / handle.close()
    Test->>Worker: POST /api/v1/search { query: "苹果" }
    Worker->>DB: searchBoundedAsync("body", "苹果")
    DB-->>Worker: [user, assistant] (fullSyncDone === false)
    Worker-->>Test: items=[user, assistant], index_state.state="building"
    Note over Test: 旧逻辑见 items.length > 0 提前 break -> 缺 title 失败
    Worker->>DB: set("s1/$title", TitleDoc)
    Worker->>DB: set("\0meta\stats", stats) + fullSyncDone = true
Loading

因为 index_state.state === 'building' 阶段按设计渐进式暴露已提交批次,所以在测试侧等待首轮索引进入 'ready' 并随后发起一次稳定查询,才能在因果顺序上保证 runBounded 读取到完整提交的会话文档与标题文档。

Code Changes

在 packages/kap-server/test/search/searchRoute.test.ts 中引入 postSearchWhenReady 辅助函数,替换同一 describe 块内两处基于 items.length > 0 的早退轮询,并将 index_state.state 断言收紧为 'ready':

 describe('server-v2 /api/v1/search')
+  postSearchWhenReady(queryBody)
+    poll postSearch(queryBody) until probe.data.index_state.state === 'ready'
+    return await postSearch(queryBody)

   it('searches across sessions and returns the wire-shaped page')
-    poll postSearch({ query: '苹果' }) until body.data.items.length > 0
+    body = await postSearchWhenReady({ query: '苹果' })
-    expect(['building', 'ready', 'readonly']).toContain(body.data.index_state.state)
+    expect(body.data.index_state.state).toBe('ready')

   it('serves literal mode through the wire')
-    poll postSearch({ query: '的价格', mode: 'literal' }) until body.data.items.length > 0
+    body = await postSearchWhenReady({ query: '的价格', mode: 'literal' })
+    expect(body.data.index_state.state).toBe('ready')

因为 SearchIndexCore.search() 先异步执行 runBounded(serveDb) 再调用 readIndexView() 读取 fullSyncDone,所以在探测请求观测到 index_state.state === 'ready' 后再补发一次查询,可以确保最终断言所用的检索过程严格发生在 fullSyncDone = true 之后,同时保留 probe.code !== 0 时的立即失败行为。

Behavior Changes and Affected Users

None。本 PR 仅修改测试文件 packages/kap-server/test/search/searchRoute.test.ts;GlobalSearchService、SearchIndexCore、POST /api/v1/search 路由契约、配置默认值及 CLI 发布产物均未改动(对 TUI、kimi -p print 模式、desktop 与 web、VS Code、ACP、SDK 用户无任何行为变化)。

  • 受影响模块:
    • packages/kap-server/test/search/searchRoute.test.ts
  • 测试覆盖:
    • searches across sessions and returns the wire-shaped page:覆盖全文检索路由在首轮索引就绪后的 user、assistant、title 三类命中与响应结构。
    • serves literal mode through the wire:覆盖字面量检索模式单独运行及整文件运行时的索引就绪等待与精确子串匹配。
验证明细
  • 复现对照验证(在 SearchIndexCore.syncSession 写入 titleKey 前临时注入 150ms 延迟模拟慢盘窗口,验证后还原):
    • 修改前:pnpm -C packages/kap-server exec vitest run test/search/searchRoute.test.ts 稳定复现 AssertionError: expected false to be true(test/search/searchRoute.test.ts:164:62)。
    • 修改后:同一 150ms 注入延迟下 6/6 全部通过。
  • 独立与重复运行:
    • 单独运行 pnpm -C packages/kap-server exec vitest run test/search/searchRoute.test.ts -t "serves literal mode through the wire":通过。
    • 连续 10 轮 pnpm -C packages/kap-server exec vitest run test/search/searchRoute.test.ts:10/10 轮(共 60/60 次用例执行)全部通过。
  • 静态检查:
    • pnpm run typecheck:0 errors。
    • pnpm run lint --quiet(全仓 oxlint --type-aware):0 errors。
    • pnpm run sherif:No issues found。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Requested by 刘金 via Mira.

@changeset-bot

changeset-bot Bot commented Nov 13, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5abdcfa

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T05:47:20.156808Z 5abdcfa PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 13, 2026

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

commit: 5abdcfa

@Grapedge
Grapedge merged commit 8d7948e into main Nov 13, 2026
17 checks passed
@Grapedge
Grapedge deleted the test/deflake-search-route-ready branch November 13, 2026 06:03
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 15, 2026
Port MoonshotAI#4901, MoonshotAI#4909 and MoonshotAI#4911: complete the task before asserting a
zero-timeout wait sees the completed snapshot, restore the instructions
reload spy after the failure assertion, poll the search index until it is
ready before asserting the page, and run remote-session git probes
through a host process that refuses gh.

Record MoonshotAI#4840 as equivalent (the refresh path already rebuilds from the
effective binding here) and pin it with a regression case, record MoonshotAI#4883
as ported with the compaction profile already present, and record MoonshotAI#4830
as blocked on the absent loop requester/request-attribution layering.
Clear the generated-bundle, release-sync and working-notes rows with
their applicable verdicts.
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.

2 participants