perf(host): share one cold cwd read across concurrent /sidebar requests

cwdOf() resolves the session cwd for all twelve /sidebar routes. On a
detached session every call runs one host observation — the whole log read
plus decode — and the host's cold cache only helps AFTER a read completes,
so a session-switch burst decoded the same multi-MB log N times in parallel
(0.28.0: 39 MB × 44 requests ≈ 1.7 GB, OOM). Concurrent asks for the same
session + client cwd hint now share ONE resolution; there is no TTL (the
host already caches completed cold reads by persistence revision), and the
hint stays in the key so different fallbacks never leak across each other.

tests/smoke.spec.ts pins 12 concurrent calls → 1 observeSession (red before
this change: expected 12 to be 1) and the per-hint key. The dock-fallback
reserve test now clears localStorage per case — a previous case persisted
bottomOpen and made the new click toggle it closed.
This commit is contained in:
Menghuan1918 committed 2026-10-26 17:51:30 +08:00
1 parent 8ee6e8de27
commit 7ecf6a14af
7 files changed
+76 -1

No files matched your search

+1
View File
@@ -4,6 +4,7 @@
### v0.28.1
- 🛡 **并发同键冷读合并(OOM 修复)**:全量重启后会话全部转为 detached,12 条 `/sidebar/*` 路由共享的 cwd 解析会对同一会话各做一次宿主冷观察(整份日志读 + 解码;39MB 级会话 × 44 个并发请求 ≈ 1.7GB → OOM)。现在 `cwdOf()` 把**同一会话 + 同一客户端 cwd 提示**的并发请求合并为一次真实读,其余 await 同一结果;不引入 TTL(宿主本身按持久化 revision 缓存已完成冷读),客户端提示参与 key 以免跨提示串味。`tests/smoke.spec.ts` 新增「12 并发 → 1 次冷读」与「不同提示不合并」两例。
- **runGit 输出上限加固**(#999):字节封顶后的 chunk 一律丢弃(闩锁)、超时/封顶路径统一销毁 stdio 并 SIGKILL 进程树、stderr 纳入同一预算;病态工作区的结果从「宿主 `RangeError` 崩溃」降为「一次 SCM 刷新失败」。
- **worktree 会话的根选择与地址基准**(#956 / #947 / #950 / #952):同一会话不再有两个基准——聊天链接按会话 header cwd 解析、打开/保存不再二次拼接,linked worktree 里也不再静默读到另一检出的同名文件。
- **关闭侧聊页签时归档其会话**(#981 / #942):线程的完整父会话副本不再作为独立会话残留在工作区列表里。
+1
View File
@@ -6,6 +6,7 @@
### v0.28.1
- **Concurrent single-flight for cold cwd reads (OOM fix)**: after a full restart every session is detached, and the shared cwd resolution behind all twelve `/sidebar/*` routes ran one host observation per call (a full log read plus decode; a 39 MB session × 44 concurrent requests ≈ 1.7 GB → OOM). `cwdOf()` now shares one resolution between concurrent requests for the same session + client cwd hint; there is no TTL (the host already caches completed cold reads by persistence revision), and the hint stays in the key so different hints never leak across each other. Two new `tests/smoke.spec.ts` cases pin "12 concurrent → 1 cold read" and "different hints do not merge".
- **No more silent wrong-file writes**: tab reconciliation now reaches tabs opened in **background sessions**, and a worktree session resolves chat links against **one address base**. Renaming or deleting an open file no longer re-creates the old path on the next save, and a relative link inside a linked worktree no longer silently opens a same-named file from another checkout ([#915](https://github.com/omdsh-dev/DSH-better-sidebar/issues/915), [#947](https://github.com/omdsh-dev/DSH-better-sidebar/issues/947), [#950](https://github.com/omdsh-dev/DSH-better-sidebar/issues/950), [#952](https://github.com/omdsh-dev/DSH-better-sidebar/issues/952)).
- **Host crash guard for pathological git output**: the bounded `runGit` reader now latches after the byte cap, destroys both stdio streams and kills the process tree, and budgets stderr too. A pathological worktree can no longer take the whole host down with `RangeError: Invalid string length` ([#999](https://github.com/omdsh-dev/DSH-better-sidebar/pull/999)).
- **Git page**: histories with more than 1,000 branches load again ([#1013](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1013)). **Tags now decorate commits, rows and details** — lightweight and annotated, with their own inventory budget and pagination fingerprint, without consuming the branch limit ([#983](https://github.com/omdsh-dev/DSH-better-sidebar/issues/983)).
+1
View File
@@ -100,6 +100,7 @@ If something fails, check the FAQ table in https://github.com/omdsh-dev/DSH-bett
**v0.28.1 — UX and reliability patch**
- **OOM fix**: cold cwd reads shared by the twelve `/sidebar/*` routes are merged per session and client hint, so a session-switch burst no longer decodes the same large session log N times in parallel
- **Silent wrong-file writes are gone**: tab reconciliation now covers tabs in background sessions, and worktree sessions use one address base — a renamed/deleted file is no longer re-created on the next save, and a chat link never opens a same-named file from another checkout
- **Host crash guard**: pathological `git status` output is capped with a latch and a process-tree kill, turning "host dies with `RangeError`" into one failed SCM refresh
- **Git page**: histories with more than 1,000 branches load again; tags now decorate commits, rows and details, and tag changes invalidate pagination
+1
View File
@@ -100,6 +100,7 @@ dsh plugin --profile web add dsh-better-sidebar@latest
**v0.28.1 — UX 与可靠性补丁**
- **OOM 修复**:12 条 `/sidebar/*` 路由共享的冷 cwd 读取按「会话 + 客户端提示」合并,切换会话的并发突发不再并行解码同一份大会话日志
- **不再静默写错文件**:页签调解覆盖后台会话,worktree 会话统一地址基准——改名/删除的已打开文件不会被下一次保存重建,聊天链接也不会静默打开另一检出的同名文件
- **宿主崩溃防护**:病态 `git status` 输出加了闩锁与进程树终止,「宿主 `RangeError` 崩溃」降为一次 SCM 刷新失败
- **Git 页**:>1000 分支的历史恢复加载;tag 现在装饰提交行与详情,tag 变化会使旧分页失效
+27 -1
View File
@@ -635,11 +635,37 @@ function buildApi(
assistantLive: AssistantLiveBuffer,
archiveTasks: ArchiveTasks,
): Record<string, ApiMethod> {
/**
* Same-key sharing for the shared cwd path. All twelve routes below resolve
* the session cwd through here, and a session switch fires them at once. A
* detached (cold) session costs one host observation per call — a full log
* read plus decode, e.g. 39 MB for a large session — and the host's cold
* cache only helps AFTER a read completes; concurrent same-key asks all miss
* it. A client burst therefore used to decode the same log N times in
* parallel (44 × 39 MB ≈ 1.7 GB, OOM on 0.28.0). Concurrent asks for the same
* session + client hint now share ONE resolution; the hint is part of the key
* because it is a fallback the result depends on. No TTL: the host already
* caches completed cold reads by persistence revision, so the leader's result
* is what every follower and every later ask reuses.
*/
const cwdInFlight = new Map<string, Promise<{ sessionId: string; cwd: string }>>()
const cwdOf = async (payload: unknown): Promise<{ sessionId: string; cwd: string }> => {
const sessionId = requireString(payload, 'sessionId')
const record = payload as { cwd?: unknown } | null
const clientCwd = typeof record?.cwd === 'string' && record.cwd !== '' ? record.cwd : undefined
return { sessionId, cwd: await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, clientCwd)) }
const key = `${sessionId}\u0000${clientCwd ?? ''}`
const pending = cwdInFlight.get(key)
if (pending !== undefined) return pending
const resolved = (async (): Promise<{ sessionId: string; cwd: string }> => ({
sessionId,
cwd: await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, clientCwd)),
}))()
cwdInFlight.set(key, resolved)
try {
return await resolved
} finally {
cwdInFlight.delete(key)
}
}
/** Resolve the optional Git-panel checkout selector against the selected
* session repository. Unlike `cwd`, `worktree` is never trusted directly. */
+5
View File
@@ -112,6 +112,10 @@ async function settle(): Promise<void> {
describe('dock fallback(空白会话入口)', () => {
beforeEach(() => {
// The store persists per-session state to localStorage; a test that opens
// the workbench must not seed the next test's store with
// `bottomOpen: true` (the click would close it instead of open it).
localStorage.clear()
intervals.clear()
vi.spyOn(globalThis, 'setInterval').mockImplementation(((fn: () => void, ms?: number) => {
const id = ++intervalSeq
@@ -233,6 +237,7 @@ describe('dock fallback(空白会话入口)', () => {
const shell = document.querySelector<HTMLElement>('[data-dsh-dock-fallback]')
expect(shell, '空白会话没有其他 opener,不能隐藏唯一入口').not.toBeNull()
expect(Number.parseFloat(shell!.style.left), '无空位也不能落到 left<=4 或红绿灯区域').toBeGreaterThanOrEqual(88)
expect(store.getSnapshot().state?.bottomOpen, '本用例从关闭态开始').toBe(false)
clickFallbackToggle()
expect(store.getSnapshot().state?.bottomOpen).toBe(true)
} finally {
+40
View File
@@ -805,6 +805,46 @@ describe('session cwd resolution over the API route', () => {
expect(releases).toBe(2)
})
it('shares one cold observation between concurrent same-session cwd calls', async () => {
let reads = 0
let releases = 0
let unblock!: () => void
const gate = new Promise<void>((resolve) => { unblock = resolve })
const shared = resolvePath('/cold-shared-execution')
const route = mount({ sessionQuery: {
observeSession: async () => {
reads += 1
await gate
return {
header: { cwd: resolvePath('/original-project') },
projections: { values: { workingDirectory: shared } },
[Symbol.dispose]: () => { releases += 1 },
}
},
} })
// A session switch fires the twelve routes at once; every one needs cwd.
const calls = Array.from({ length: 12 }, () =>
invoke(route, 'session.cwd', { sessionId: 'wd-shared', cwd: '/stale-client' }))
await Promise.resolve()
unblock()
const results = await Promise.all(calls)
expect(reads, 'concurrent same-key asks must share ONE cold read').toBe(1)
expect(releases, 'the shared observation is released once').toBe(1)
for (const result of results) {
expect(result).toMatchObject({ ok: true, value: { cwd: shared } })
}
})
it('does not share a resolution across different client cwd hints', async () => {
const route = mount({})
const [first, second] = await Promise.all([
invoke(route, 'session.cwd', { sessionId: 'wd-hints', cwd: resolvePath('/hint-a') }),
invoke(route, 'session.cwd', { sessionId: 'wd-hints', cwd: resolvePath('/hint-b') }),
])
expect(first).toMatchObject({ ok: true, value: { cwd: resolvePath('/hint-a') } })
expect(second).toMatchObject({ ok: true, value: { cwd: resolvePath('/hint-b') } })
})
it('uses the host custom default for a null cold working-directory projection before a stale client hint', async () => {
const defaultDirectory = resolvePath('/configured-execution-default')
let releases = 0