perf(host): cwd 解析加在飞去重与 TTL 对齐、numstat 加 pathspec 与输出上限
src/active-worktree.ts 是 v0.25 新文件,却插进了 12 条 /sidebar/* 路由共用的 cwdOf():实测每次缓存未命中 9.6–44.7ms、1–4 次真实 git spawn,而 TTL 3s 与客户端 新的 5s 每-tab 轮询错配——每次轮询必然未命中。 - active-worktree:(session, base) 整链与 base 探针都加在飞去重(并发 8 次只 spawn 一次);ACTIVE_ROOT_TTL_MS 3s→15s(跟随 worktree 的延迟代价写进注释);三个模块级 缓存加 LRU 上界 512/512/256,负结果仍缓存但可淘汰。 - git.ts:两条 --numstat 加 pathspec(非 ?? 路径 + R/C 的 origin,必须 --literal-pathspecs;未跟踪路径不参与 ⇒ 未忽略的大目录从两条全仓库 diff 变成零条; 路径超 8KB 回退整仓库 diff)、runGit 加 8MiB 输出上限、状态行上限改在产出侧生效。 - fs-tree:折叠探测每层封顶 32 且截断层不探测(折叠是纯装饰)。 - index.ts:单层 fs.tree 补 ProbeGate;teardown 主动关闭三个 noServer WSS 的已接受 连接(ws@8 的 close() 不终止在连 socket,句柄会活到浏览器断开)。 - sidechat-routes:冷线程日志按 (childId, revision, size) memo(16 线程,句柄照旧 open/close,只有结果被缓存)。 - agent-opens:每会话队列封顶 64,最旧的丢弃,FIFO 与 drainAll 语义不变。 测试:扩展 active-worktree / git-worktree / fs-tree-probe-gate / sidechat-routes / smoke / agent-opens;14 项「临时回退→变红→还原」突变全部被捕获。
This commit is contained in:
1 parent
43742be658
commit
3e5576ffbb
12 files changed
+1005
-43
No files matched your search
+134
-18
@@ -17,8 +17,11 @@
|
||||
* newest event that has one wins; when there is no evidence the session cwd is
|
||||
* kept (lifted to the repository top level for subdirectory sessions).
|
||||
*
|
||||
* Resolutions are cached process-wide, so the client's periodic re-ask is
|
||||
* cheap after the first scan.
|
||||
* Resolutions are cached process-wide ({@link ACTIVE_ROOT_TTL_MS}), concurrent
|
||||
* callers share one in-flight resolution AND one in-flight base probe, and
|
||||
* every cache is bounded — so the client's periodic re-ask, the debounced
|
||||
* fs-watch frames and the twelve route handlers that funnel through
|
||||
* `cwdOf()` are answered without a process spawn after the first scan.
|
||||
*/
|
||||
import { stat } from 'node:fs/promises'
|
||||
import { dirname, isAbsolute, join, sep } from 'node:path'
|
||||
@@ -27,12 +30,27 @@ import { requireAbsolute } from './fs-tree.ts'
|
||||
import { runGit } from './git.ts'
|
||||
import { readPersistedSessionOf } from './session-store.ts'
|
||||
|
||||
/** How long one computed root is reused before the event log is scanned again. */
|
||||
const ACTIVE_ROOT_TTL_MS = 3_000
|
||||
/**
|
||||
* How long one computed root is reused before the event log is scanned again.
|
||||
*
|
||||
* 15 s, deliberately longer than the client's per-tab 5 s poll: at 3 s every
|
||||
* poll was a cache miss (one `git rev-parse --show-toplevel` spawn plus up to
|
||||
* 4 000 events of backlog scanning per ask, measured 9.6–44.7 ms), which is
|
||||
* the opposite of what this cache is for. The semantic cost of the longer TTL
|
||||
* is that a session which MOVES into a linked worktree is followed within at
|
||||
* most 15 s of the move (was 3 s) — every event-driven re-ask (fs-watch
|
||||
* frames, route calls, editor opens) is served from the cache in the meantime
|
||||
* and no refresh path is turned off.
|
||||
*/
|
||||
const ACTIVE_ROOT_TTL_MS = 15_000
|
||||
/** Only the newest slice of the event log is considered. */
|
||||
const ACTIVE_ROOT_MAX_EVENTS = 4_000
|
||||
/** Upper bound on git probes per scan (cache misses are what cost). */
|
||||
const ACTIVE_ROOT_MAX_PROBES = 24
|
||||
/** Bounds of the three process-wide caches below (LRU, oldest evicted first). */
|
||||
const PATH_TOP_CACHE_MAX = 512
|
||||
const LINKED_WORKTREE_CACHE_MAX = 512
|
||||
const ACTIVE_ROOT_CACHE_MAX = 256
|
||||
/** Explicit override, mainly for tests and manual pinning. */
|
||||
const ACTIVE_ROOT_OVERRIDE_ENV = 'DSH_SIDEBAR_WORKTREE_ROOT'
|
||||
/** Keys whose string values describe where a tool actually ran. */
|
||||
@@ -47,11 +65,47 @@ const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\
|
||||
* (measured ~7 ms), and the repeated asks every debounced watch frame, every
|
||||
* route call, the client's 5 s poll are exactly what the TTL exists to keep
|
||||
* free.
|
||||
*
|
||||
* All three maps are BOUNDED: a long-lived host (and a `keepMounted` right
|
||||
* sidebar that keeps asking about every session it has ever shown) would
|
||||
* otherwise grow them forever. `pathTopCache` caches negative answers too
|
||||
* (`undefined` = "no git top level here"), which is what keeps a non-repo
|
||||
* session cheap; those entries are evictable like any other.
|
||||
*/
|
||||
const activeWorktreeRootCache = new Map<string, { root: string; base: string; expires: number }>()
|
||||
const pathTopCache = new Map<string, string | undefined>()
|
||||
const linkedWorktreeCache = new Map<string, boolean>()
|
||||
|
||||
/**
|
||||
* In-flight de-duplication, mirroring `git.ts`'s `repoRootsInFlight`.
|
||||
*
|
||||
* `activeRootInFlight` collapses a burst of asks for the SAME (session, base)
|
||||
* into one resolution (one base spawn, one event scan); `topLevelInFlight`
|
||||
* collapses the base probe across DIFFERENT sessions that share a base (N tabs
|
||||
* of one workspace would otherwise spawn N `git rev-parse` processes at once).
|
||||
* Both delete their entry on the resolved AND the rejected path, so a failure
|
||||
* never poisons the map.
|
||||
*/
|
||||
const activeRootInFlight = new Map<string, Promise<string>>()
|
||||
const topLevelInFlight = new Map<string, Promise<string | undefined>>()
|
||||
|
||||
/**
|
||||
* Insert or refresh one cache entry, evicting the least recently used entry
|
||||
* once the cache holds more than `max`. Map iteration order is insertion
|
||||
* order, so deleting before setting moves the key to the young end — which is
|
||||
* what makes a HIT refresh recency (this is the repo's bounded-cache style
|
||||
* from `fs-tree.ts`'s `directoryCache`, with the recency touch added).
|
||||
*/
|
||||
function cachePut<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {
|
||||
map.delete(key)
|
||||
map.set(key, value)
|
||||
while (map.size > max) {
|
||||
const oldest = map.keys().next().value
|
||||
if (oldest === undefined) break
|
||||
map.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized IDENTITY of a path (case- and separator-insensitive), for
|
||||
* comparisons and cache keys only: it lowercases, so it must never be handed
|
||||
@@ -82,6 +136,29 @@ async function gitTopLevelOf(cwd: string): Promise<string | undefined> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link gitTopLevelOf} with in-flight sharing per path identity: concurrent
|
||||
* asks for one directory (a route burst, or several sessions rooted in the
|
||||
* same repository) spawn ONE git process between them.
|
||||
*/
|
||||
function topLevelOf(cwd: string): Promise<string | undefined> {
|
||||
const key = pathKeyOf(cwd)
|
||||
const pending = topLevelInFlight.get(key)
|
||||
if (pending !== undefined) return pending
|
||||
const promise = gitTopLevelOf(cwd).then(
|
||||
(top) => {
|
||||
topLevelInFlight.delete(key)
|
||||
return top
|
||||
},
|
||||
(error: unknown) => {
|
||||
topLevelInFlight.delete(key)
|
||||
throw error
|
||||
},
|
||||
)
|
||||
topLevelInFlight.set(key, promise)
|
||||
return promise
|
||||
}
|
||||
|
||||
/** Collapse duplicated separators without destroying a UNC prefix. */
|
||||
function normalizeActivePath(value: string): string {
|
||||
const trimmed = value.replace(/[\\/]+$/, '')
|
||||
@@ -149,11 +226,18 @@ function collectActivePaths(value: unknown, map: Map<string, ActivePathEntry>, s
|
||||
/** git top level for one path (its directory when the path names a file). */
|
||||
async function topOfActivePath(value: string): Promise<string | undefined> {
|
||||
const key = pathKeyOf(value)
|
||||
if (pathTopCache.has(key)) return pathTopCache.get(key)
|
||||
let top = await gitTopLevelOf(value)
|
||||
if (top === undefined) top = await gitTopLevelOf(dirname(value))
|
||||
if (pathTopCache.has(key)) {
|
||||
const cached = pathTopCache.get(key)
|
||||
// A cached `undefined` ("not in a repository") is the answer that keeps a
|
||||
// non-repo session cheap, so it is re-inserted like any other hit — which
|
||||
// also refreshes its recency in the bounded LRU.
|
||||
cachePut(pathTopCache, key, cached, PATH_TOP_CACHE_MAX)
|
||||
return cached
|
||||
}
|
||||
let top = await topLevelOf(value)
|
||||
if (top === undefined) top = await topLevelOf(dirname(value))
|
||||
const result = top === undefined ? undefined : requireAbsolute(top)
|
||||
pathTopCache.set(key, result)
|
||||
cachePut(pathTopCache, key, result, PATH_TOP_CACHE_MAX)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -165,7 +249,10 @@ async function topOfActivePath(value: string): Promise<string | undefined> {
|
||||
async function isLinkedWorktree(top: string): Promise<boolean> {
|
||||
const key = pathKeyOf(top)
|
||||
const cached = linkedWorktreeCache.get(key)
|
||||
if (cached !== undefined) return cached
|
||||
if (cached !== undefined) {
|
||||
cachePut(linkedWorktreeCache, key, cached, LINKED_WORKTREE_CACHE_MAX)
|
||||
return cached
|
||||
}
|
||||
let linked = false
|
||||
try {
|
||||
const out = (await runGit(top, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/)
|
||||
@@ -178,7 +265,10 @@ async function isLinkedWorktree(top: string): Promise<boolean> {
|
||||
} catch {
|
||||
linked = false
|
||||
}
|
||||
linkedWorktreeCache.set(key, linked)
|
||||
// `false` is a real answer ("the main checkout", "a submodule", "not a
|
||||
// repo") and is cached: the negative is what keeps a subdirectory session
|
||||
// from re-probing the same top level on every scan.
|
||||
cachePut(linkedWorktreeCache, key, linked, LINKED_WORKTREE_CACHE_MAX)
|
||||
return linked
|
||||
}
|
||||
|
||||
@@ -237,6 +327,11 @@ async function sessionEventsOf(ctx: Context, sessionId: string): Promise<readonl
|
||||
|
||||
/**
|
||||
* The directory the sidebar should treat as the session's root.
|
||||
*
|
||||
* The cache is consulted BEFORE the probe, and concurrent asks for the same
|
||||
* (session, base) share ONE in-flight resolution: twelve route handlers funnel
|
||||
* through `cwdOf()`, so a burst of parallel `/sidebar/*` calls used to spawn a
|
||||
* `git rev-parse` process per call.
|
||||
* @param ctx - host plugin context.
|
||||
* @param sessionId - session whose tool calls are inspected.
|
||||
* @param base - the authoritative session cwd (already resolved by the caller).
|
||||
@@ -246,23 +341,44 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
|
||||
if (base === '') return base
|
||||
const override = (process.env[ACTIVE_ROOT_OVERRIDE_ENV] ?? '').trim()
|
||||
if (override !== '' && isAbsolute(override)) return requireAbsolute(override)
|
||||
// The cache is consulted BEFORE the probe: doing it afterwards still pays the
|
||||
// spawn on every ask, which is the whole cost the TTL is there to avoid. The
|
||||
// comparison is on the raw base, so a session whose caller switched base (the
|
||||
// `/sidebar/*` routes pass the client's own) never reuses the other one's root.
|
||||
// The comparison is on the raw base, so a session whose caller switched base
|
||||
// (the `/sidebar/*` routes pass the client's own) never reuses the other
|
||||
// one's root.
|
||||
const cached = activeWorktreeRootCache.get(sessionId)
|
||||
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) return cached.root
|
||||
const top = await gitTopLevelOf(base)
|
||||
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) {
|
||||
cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX)
|
||||
return cached.root
|
||||
}
|
||||
const flightKey = `${sessionId}\0${base}`
|
||||
const pending = activeRootInFlight.get(flightKey)
|
||||
if (pending !== undefined) return pending
|
||||
const promise = resolveActiveWorktreeRoot(ctx, sessionId, base).then(
|
||||
(root) => {
|
||||
activeRootInFlight.delete(flightKey)
|
||||
return root
|
||||
},
|
||||
(error: unknown) => {
|
||||
activeRootInFlight.delete(flightKey)
|
||||
throw error
|
||||
},
|
||||
)
|
||||
activeRootInFlight.set(flightKey, promise)
|
||||
return promise
|
||||
}
|
||||
|
||||
/** One uncached resolution (see {@link activeWorktreeRootOf}). */
|
||||
async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string): Promise<string> {
|
||||
const top = await topLevelOf(base)
|
||||
if (top === undefined) {
|
||||
// "Not inside a repository" is an answer too (the base itself), and caching
|
||||
// it is what keeps a non-repo session from re-probing on every ask.
|
||||
activeWorktreeRootCache.set(sessionId, { root: base, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS })
|
||||
cachePut(activeWorktreeRootCache, sessionId, { root: base, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
|
||||
return base
|
||||
}
|
||||
const canonicalTop = requireAbsolute(top)
|
||||
const effectiveBase = pathUnderOf(base, canonicalTop) ? base : canonicalTop
|
||||
const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), effectiveBase)
|
||||
const root = active ?? effectiveBase
|
||||
activeWorktreeRootCache.set(sessionId, { root, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS })
|
||||
cachePut(activeWorktreeRootCache, sessionId, { root, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
|
||||
return root
|
||||
}
|
||||
Reference in new issue
Block a user