fix(panel): harden SQLite ledger concurrency, LRU sizing, and recovery

- Preserve step detail_json and peer-appended rows during cold metadata flushes, slim-step spreads, and mixed-case UUID re-keying without triggering case-insensitive self-deletion
- Raise default hot session LRU limit to 64 and prime stepSigs during on-demand hydration to avoid cyclic read thrashing across 30-session quick stats plus active subagents
- Quarantine corrupt SQLite images to .corrupt.<ts> with automatic .json.bak recovery and defer latching loadedOnce until initial hydration succeeds
- Flush pending throttled endpoint caches on worker/standalone stop, isolate unscoped node --test runs from live user data, and transitively retain nested subagents and side questions on cache rebuilds
This commit is contained in:
fish
2026-11-24 15:04:14 +09:00
parent 030d894988
commit 173e21c607
8 changed files with 381 additions and 49 deletions
+11 -3
View File
@@ -418,14 +418,22 @@ export function computeRuntimeCodeVersion(options = {}) {
/**
* 本机内存态轨迹步骤缓存容器(委托 `createTrajectoryCacheStore`,首次读取时惰性加载历史缓存)。
*/
const isUnscopedHostTestRunner = Boolean(
typeof process !== 'undefined' &&
process?.env?.NODE_TEST_CONTEXT &&
!process?.env?.USAGE_MONITOR_APP_DATA_DIR &&
!process?.env?.ANTIGRAVITY_APP_DATA_DIR &&
!process?.env?.ANTIGRAVITY_GEMINI_DIR
);
const localTrajectoryCacheStore = createTrajectoryCacheStore({
cacheFilePath: CACHE_FILE,
sqliteFilePath: TRAJECTORY_DB_FILE,
cacheFilePath: isUnscopedHostTestRunner ? '' : CACHE_FILE,
sqliteFilePath: isUnscopedHostTestRunner ? '' : TRAJECTORY_DB_FILE,
loadJsonFn: loadJson,
writeCacheFn: (targetPath, dataObj) => saveJson(targetPath, dataObj),
shouldBypassThrottleFn: (allowThrottleInTest) =>
lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest,
registerExitHook: true,
registerExitHook: !isUnscopedHostTestRunner,
});
export function getLocalTrajectoryCacheStore() {
+18 -3
View File
@@ -476,13 +476,28 @@ export function getRemoteWindowRpcInvoker() {
return registeredWindowRpcInvoker;
}
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
process.once('exit', () => {
for (const ep of remoteEndpointRegistry.values()) {
export function flushAllEndpointCachesNow() {
try {
if (hasPendingTrajectoryCacheSave()) {
flushTrajectoryCacheNow();
}
} catch {
// 忽略关闭阶段本机刷盘异常
}
for (const ep of remoteEndpointRegistry.values()) {
try {
if (ep.store.hasPendingTrajectoryCacheSave()) {
ep.store.flushTrajectoryCacheNow();
}
ep.store.cancelFlushTimer();
} catch {
// 忽略关闭阶段远端端点刷盘异常
}
}
}
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
process.once('exit', () => {
flushAllEndpointCachesNow();
});
}
+51 -17
View File
@@ -587,12 +587,34 @@ export function collectAuthoritativeLiveCascadeIds(endpoint = null) {
for (const id of diskConvMap.keys()) liveIds.add(String(id).toLowerCase());
for (const id of localSnap.byId.keys()) liveIds.add(String(id).toLowerCase());
const localStore = getEndpointCacheStore(null);
for (const [rawKey, entry] of localStore.listCachedTrajectoryEntries()) {
const lower = String(rawKey || '').toLowerCase();
if (!liveIds.has(lower)) continue;
for (const ref of entry?.subagentRefs || []) {
const refLower = String(ref?.cascadeId || '').trim().toLowerCase();
if (refLower) liveIds.add(refLower);
const cachedEntries = localStore.listCachedTrajectoryEntries();
let expanded = true;
while (expanded) {
expanded = false;
for (const [rawKey, entry] of cachedEntries) {
const lower = String(rawKey || '').toLowerCase();
if (!lower) continue;
if (liveIds.has(lower)) {
for (const ref of entry?.subagentRefs || []) {
const refLower = String(ref?.cascadeId || '').trim().toLowerCase();
if (refLower && !liveIds.has(refLower)) {
liveIds.add(refLower);
expanded = true;
}
}
} else {
const parentLower = String(entry?.parentConversationId || entry?.parentCascadeId || '')
.trim()
.toLowerCase();
const rootLower = String(entry?.rootConversationId || '').trim().toLowerCase();
if (
(parentLower && liveIds.has(parentLower)) ||
(rootLower && liveIds.has(rootLower))
) {
liveIds.add(lower);
expanded = true;
}
}
}
}
return liveIds;
@@ -1846,19 +1868,24 @@ export async function enumerateAndSyncConversations({
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
if (normalizedKey !== rawCacheKey) {
setEntry(normalizedKey, getEntry(rawCacheKey));
removeEntry(rawCacheKey);
cacheDirty = true;
const prevVal = getEntry(rawCacheKey);
if (prevVal) {
setEntry(normalizedKey, prevVal);
cacheDirty = true;
}
}
canonicalIdByLower.set(lower, normalizedKey);
} else if (existingCanon !== rawCacheKey) {
const targetEntry = getEntry(existingCanon);
const dupEntry = getEntry(rawCacheKey);
if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) {
setEntry(existingCanon, dupEntry);
const winner =
!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)
? dupEntry
: targetEntry;
if (winner) {
setEntry(existingCanon, winner);
cacheDirty = true;
}
removeEntry(rawCacheKey);
cacheDirty = true;
}
}
@@ -3279,12 +3306,18 @@ export async function enumerateAndSyncConversations({
}
if (!isMeaningfulTitle(rootConv.title, cid)) {
const localSumTitle = localSummaryByLower.get(cid)?.title || '';
const stepTurnTitle = extractFirstStepTurnTitle(rootCached?.steps);
let recoveredTitle = pickFirstMeaningfulTitle(cid, [
localSumTitle,
rootCached?.title,
stepTurnTitle,
]);
if (!recoveredTitle && rootCached) {
const titleSourceEntry = rootCached._coldSteps
? getHydratedEntry(rootConv.cascadeId) || rootCached
: rootCached;
recoveredTitle = pickFirstMeaningfulTitle(cid, [
extractFirstStepTurnTitle(titleSourceEntry?.steps),
]);
}
if (!recoveredTitle && !isRemote) {
recoveredTitle = probeLocalFallbackTitle(
cid,
@@ -3293,8 +3326,9 @@ export async function enumerateAndSyncConversations({
}
if (recoveredTitle) {
rootConv.title = recoveredTitle;
if (rootCached && rootCached.title !== recoveredTitle) {
setEntry(rootConv.cascadeId, { ...rootCached, title: recoveredTitle });
const curRootCached = getEntry(rootConv.cascadeId) || rootCached;
if (curRootCached && curRootCached.title !== recoveredTitle) {
setEntry(rootConv.cascadeId, { ...curRootCached, title: recoveredTitle });
titleBackfillDirty = true;
}
}
@@ -14,6 +14,7 @@ import {
dispatchBridgeApiRequest,
} from './api-actions.mjs';
import { computeRuntimeCodeVersion } from './config.mjs';
import { flushAllEndpointCachesNow } from './endpoint-registry.mjs';
let shuttingDown = false;
let reloadRequested = false;
@@ -50,6 +51,11 @@ async function gracefulStop() {
if (shuttingDown) return;
shuttingDown = true;
clearInterval(driftWatchTimer);
try {
flushAllEndpointCachesNow();
} catch {
// Ignore cache flush errors
}
try {
await bridgeController?.stop?.({ disposeWindows: false });
} catch {
@@ -16,6 +16,7 @@ import {
readLocalAsync,
} from './api-actions.mjs';
import { loadSettings, lsRuntimeEndpoint, setLsRuntimeEndpoint } from './config.mjs';
import { flushAllEndpointCachesNow } from './endpoint-registry.mjs';
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
import { syncCloudCatalog } from './plugin-updater.mjs';
@@ -643,6 +644,7 @@ export function createStandaloneWebServer(options = {}) {
}
async function stop() {
flushAllEndpointCachesNow();
const srv = server;
server = null;
boundPort = 0;
@@ -20,7 +20,7 @@ import {
} from './trajectory-sqlite-ledger.mjs';
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
export const DEFAULT_HOT_SESSION_LRU_LIMIT = 24;
export const DEFAULT_HOT_SESSION_LRU_LIMIT = 64;
const TCS_WAL_SYNC_MIN_INTERVAL_MS = 250;
function tcsMarkColdSlimSteps(steps) {
@@ -242,18 +242,22 @@ export function createTrajectoryCacheStore({
function ensureLoaded() {
if (loadedOnce) return;
loadedOnce = true;
if (useSqlite && sqliteLedger) {
const hydrated = sqliteLedger.openAndHydrateInitial();
cacheObj = hydrated.cacheObj;
loadedOnce = true;
rebuildLowerIndexFromCacheObj(true);
lastWalSyncCheckMs = Date.now();
return;
}
if (!cacheFilePath || typeof loadJsonFn !== 'function') return;
if (!cacheFilePath || typeof loadJsonFn !== 'function') {
loadedOnce = true;
return;
}
const loaded = loadJsonFn(cacheFilePath, {});
const hydrated = hydrateTrajectoryCacheObject(loaded);
cacheObj = hydrated.cacheObj;
loadedOnce = true;
for (const key of Object.keys(cacheObj)) {
byLower.set(key.toLowerCase(), key);
}
@@ -231,6 +231,33 @@ export function splitStepForStorage(step) {
* @param {(val: string) => string} [internFn]
* @returns {object}
*/
function isSqliteCorruptError(err) {
const msg = String(err?.message || err?.errstr || err?.code || '');
return /SQLITE_CORRUPT|SQLITE_NOTADB|database disk image is malformed|file is not a database/i.test(
msg
);
}
function tslQuarantineCorruptDbFiles(sqliteFilePath) {
if (!sqliteFilePath || !existsSync(sqliteFilePath)) return '';
const stamp = Date.now();
const quarantineBase = `${sqliteFilePath}.corrupt.${stamp}`;
for (const suffix of ['', '-wal', '-shm']) {
const src = `${sqliteFilePath}${suffix}`;
if (!existsSync(src)) continue;
try {
renameSync(src, `${quarantineBase}${suffix}`);
} catch {
try {
rmSync(src, { force: true });
} catch {
// Ignore cleanup failure
}
}
}
return quarantineBase;
}
export function buildSlimStepFromAccounting(rawAccounting, internFn = (v) => v || '') {
if (!Array.isArray(rawAccounting)) {
if (isPlainObject(rawAccounting)) {
@@ -273,6 +300,12 @@ export function buildSlimStepFromAccounting(rawAccounting, internFn = (v) => v |
if (t[20]) {
slim.anomaly = t[20];
}
Object.defineProperty(slim, '_isSlimStep', {
value: true,
enumerable: false,
configurable: true,
writable: true,
});
return slim;
}
@@ -473,12 +506,9 @@ export function createTrajectorySqliteLedger({
return dedupedByLower;
}
/**
* Initializes schema, migrates legacy `.json` inside a single `BEGIN IMMEDIATE` transaction if needed,
* and hydrates all conversations in cold slim accounting mode.
*/
function openAndHydrateInitial() {
function openAndHydrateInitialCore() {
let migratedLegacy = false;
const bakJsonPath = legacyJsonPath ? `${legacyJsonPath}.bak` : '';
const hasLegacyJsonOnDisk = Boolean(
legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath)
);
@@ -493,8 +523,12 @@ export function createTrajectorySqliteLedger({
if (migRow?.value === '1') return;
let rawLoaded = null;
if (legacyJsonPath && typeof loadJsonFn === 'function' && existsSync(legacyJsonPath)) {
rawLoaded = loadJsonFn(legacyJsonPath, null);
if (typeof loadJsonFn === 'function') {
if (legacyJsonPath && existsSync(legacyJsonPath)) {
rawLoaded = loadJsonFn(legacyJsonPath, null);
} else if (!dbExistsBefore && bakJsonPath && existsSync(bakJsonPath)) {
rawLoaded = loadJsonFn(bakJsonPath, null);
}
}
db.exec('BEGIN IMMEDIATE');
@@ -566,6 +600,27 @@ export function createTrajectorySqliteLedger({
return hydrateAllSlimFromDb();
}
/**
* Initializes schema, migrates legacy `.json` inside a single `BEGIN IMMEDIATE` transaction if needed,
* self-heals corrupted SQLite images by quarantining `.corrupt.<ts>` and recovering from `.json.bak`,
* and hydrates all conversations in cold slim accounting mode.
*/
function openAndHydrateInitial() {
try {
return openAndHydrateInitialCore();
} catch (err) {
if (!isSqliteCorruptError(err)) {
throw err;
}
persistedByLower.clear();
const quarantined = tslQuarantineCorruptDbFiles(sqliteFilePath);
console.error(
`Quarantined corrupt SQLite trajectory ledger (${quarantined || sqliteFilePath}): ${err.message}`
);
return openAndHydrateInitialCore();
}
}
function hydrateAllSlimFromDb() {
if (!existsSync(sqliteFilePath)) {
localEpoch = 1;
@@ -656,8 +711,13 @@ export function createTrajectorySqliteLedger({
return slimSteps.map((s) => ({ ...s }));
}
const hydrated = new Array(detailRows.length);
const hydratedStepSigs = new Array(detailRows.length);
let posAligned = true;
for (let i = 0; i < detailRows.length; i += 1) {
const r = detailRows[i];
if (Number(r.pos) !== i) {
posAligned = false;
}
let acc = null;
let det = null;
try {
@@ -672,8 +732,17 @@ export function createTrajectorySqliteLedger({
det = null;
}
}
hydratedStepSigs[i] = r.detail_json
? `${r.accounting_json}\n${r.detail_json}`
: String(r.accounting_json || '');
hydrated[i] = mergeStepFromStorage(acc, det, internString);
}
if (posAligned) {
const prevDigest = persistedByLower.get(lower);
if (prevDigest && prevDigest.cascadeId === dbCid && !prevDigest.stepSigs) {
prevDigest.stepSigs = hydratedStepSigs;
}
}
return hydrated;
});
}
@@ -738,15 +807,21 @@ export function createTrajectorySqliteLedger({
INSERT OR REPLACE INTO steps (cascade_id, pos, accounting_json, detail_json)
VALUES (?, ?, ?, ?)
`);
const upSlimStepKeepDetail = db.prepare(`
INSERT INTO steps (cascade_id, pos, accounting_json, detail_json)
VALUES (?, ?, ?, NULL)
ON CONFLICT(cascade_id, pos) DO UPDATE SET
accounting_json = excluded.accounting_json
`);
const truncSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ? AND pos >= ?');
const delOldCidSteps = db.prepare('DELETE FROM steps WHERE cascade_id = ?');
const rekeyStepsCid = db.prepare('UPDATE steps SET cascade_id = ? WHERE cascade_id = ?');
for (const { cascadeId, entry } of upserts) {
if (!cascadeId || !entry || typeof entry !== 'object') continue;
const lower = String(cascadeId).toLowerCase();
const prevDbRow = selExisting.get(lower);
if (prevDbRow?.cascade_id && prevDbRow.cascade_id !== cascadeId) {
delOldCidSteps.run(prevDbRow.cascade_id);
rekeyStepsCid.run(cascadeId, prevDbRow.cascade_id);
}
const prevDigest = persistedByLower.get(lower) || null;
@@ -756,24 +831,46 @@ export function createTrajectorySqliteLedger({
const steps = Array.isArray(entry.steps) ? entry.steps : [];
// When an entry is still in `_coldSteps` mode (only metadata such as `signature`, `title`,
// or `archived` changed without mutating steps), update ONLY `conversations` in O(1)
// without touching `steps` (`detail_json` on disk stays 100% intact)!
if (entry._coldSteps && prevDbRow && prevDbRow.step_count === steps.length) {
if (
prevDigest &&
prevDigest.cascadeId === cascadeId &&
prevDigest.metaJson === metaJson &&
prevDigest.archivedInt === archivedInt
) {
// `workspaceUri`, or `archived` changed without hydrating `detail_json`), NEVER overwrite
// `detail_json` with NULL or truncate newer steps written concurrently by a peer process.
if (entry._coldSteps) {
if (prevDbRow) {
const preservedStepCount = Math.max(steps.length, Number(prevDbRow.step_count || 0));
if (
prevDigest &&
prevDigest.cascadeId === cascadeId &&
prevDigest.metaJson === metaJson &&
prevDigest.archivedInt === archivedInt &&
prevDbRow.cascade_id === cascadeId &&
Number(prevDbRow.step_count || 0) === preservedStepCount
) {
continue;
}
seq += 1;
upConv.run(cascadeId, lower, archivedInt, preservedStepCount, seq, nowMs, metaJson);
persistedByLower.set(lower, {
cascadeId,
metaJson,
archivedInt,
stepSigs:
preservedStepCount === steps.length ? prevDigest?.stepSigs || null : null,
});
continue;
}
// Cold entry flushed when row was absent in `conversations` (e.g. after external reset):
// insert accounting tuples without ever clobbering any existing `detail_json`.
for (let pos = 0; pos < steps.length; pos += 1) {
const { accountingTuple } = splitStepForStorage(steps[pos]);
upSlimStepKeepDetail.run(cascadeId, pos, JSON.stringify(accountingTuple));
}
seq += 1;
upConv.run(cascadeId, lower, archivedInt, steps.length, seq, nowMs, metaJson);
persistedByLower.set(lower, {
cascadeId,
metaJson,
archivedInt,
stepSigs: prevDigest?.stepSigs || null,
stepSigs: null,
});
continue;
}
@@ -786,13 +883,19 @@ export function createTrajectorySqliteLedger({
let anyStepWritten = false;
for (let pos = 0; pos < steps.length; pos += 1) {
const { accountingTuple, detailObj } = splitStepForStorage(steps[pos]);
const rawStep = steps[pos];
const { accountingTuple, detailObj } = splitStepForStorage(rawStep);
const accJson = JSON.stringify(accountingTuple);
const detJson = detailObj ? JSON.stringify(detailObj) : null;
const isUnexpandedSlim = Boolean(rawStep?._isSlimStep === true && detJson === null);
const sig = detJson ? `${accJson}\n${detJson}` : accJson;
nextStepSigs[pos] = sig;
if (!prevStepSigs || prevStepSigs[pos] !== sig) {
upStep.run(cascadeId, pos, accJson, detJson);
if (isUnexpandedSlim) {
upSlimStepKeepDetail.run(cascadeId, pos, accJson);
} else {
upStep.run(cascadeId, pos, accJson, detJson);
}
anyStepWritten = true;
}
}