mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
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:
@@ -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() {
|
||||
|
||||
@@ -476,13 +476,28 @@ export function getRemoteWindowRpcInvoker() {
|
||||
return registeredWindowRpcInvoker;
|
||||
}
|
||||
|
||||
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
|
||||
process.once('exit', () => {
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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 cachedEntries = localStore.listCachedTrajectoryEntries();
|
||||
let expanded = true;
|
||||
while (expanded) {
|
||||
expanded = false;
|
||||
for (const [rawKey, entry] of cachedEntries) {
|
||||
const lower = String(rawKey || '').toLowerCase();
|
||||
if (!liveIds.has(lower)) continue;
|
||||
if (!lower) continue;
|
||||
if (liveIds.has(lower)) {
|
||||
for (const ref of entry?.subagentRefs || []) {
|
||||
const refLower = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||
if (refLower) liveIds.add(refLower);
|
||||
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,21 +1868,26 @@ export async function enumerateAndSyncConversations({
|
||||
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
|
||||
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
|
||||
if (normalizedKey !== rawCacheKey) {
|
||||
setEntry(normalizedKey, getEntry(rawCacheKey));
|
||||
removeEntry(rawCacheKey);
|
||||
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);
|
||||
}
|
||||
removeEntry(rawCacheKey);
|
||||
const winner =
|
||||
!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)
|
||||
? dupEntry
|
||||
: targetEntry;
|
||||
if (winner) {
|
||||
setEntry(existingCanon, winner);
|
||||
cacheDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const diskLowerId of diskConvMap.keys()) {
|
||||
if (!canonicalIdByLower.has(diskLowerId)) {
|
||||
@@ -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)) {
|
||||
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) {
|
||||
// `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
|
||||
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) {
|
||||
if (isUnexpandedSlim) {
|
||||
upSlimStepKeepDetail.run(cascadeId, pos, accJson);
|
||||
} else {
|
||||
upStep.run(cascadeId, pos, accJson, detJson);
|
||||
}
|
||||
anyStepWritten = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { isDeepStrictEqual, promisify } from 'node:util';
|
||||
import { MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs';
|
||||
import { createTrajectoryCacheStore } from '../backend/trajectory-cache-store.mjs';
|
||||
import {
|
||||
DEFAULT_HOT_SESSION_LRU_LIMIT,
|
||||
createTrajectoryCacheStore,
|
||||
} from '../backend/trajectory-cache-store.mjs';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
@@ -509,3 +512,160 @@ test('Deleting source conversation in Antigravity + clicking Rebuild Cache perma
|
||||
assert.equal(out.deletedViewSteps, 1, 'clicking archived deleted conversation still renders step details');
|
||||
assert.equal(existsSync(liveDbFile), true);
|
||||
});
|
||||
|
||||
test('SQLite hardening: cold metadata vs peer append safety, mixed-case re-keying, corrupt DB quarantine + .bak recovery, and 64-session LRU', (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'ag-um-sqlite-hardening-'));
|
||||
t.after(() => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// 1. Default hot LRU comfortably holds 30 quick-stat sessions + active subagents without cyclic thrashing
|
||||
assert.equal(DEFAULT_HOT_SESSION_LRU_LIMIT, 64);
|
||||
|
||||
const dbPath = join(dir, 'trajectory_store.sqlite');
|
||||
const jsonPath = join(dir, 'trajectory_usage_cache.json');
|
||||
const mixedUpperCid = 'ABCDEF99-1111-4222-8333-444455556666';
|
||||
const mixedLowerCid = mixedUpperCid.toLowerCase();
|
||||
const conflictCid = '11112222-3333-4444-8555-666677778888';
|
||||
|
||||
// Seed initial DB via Store Writer
|
||||
const writer = createTrajectoryCacheStore({
|
||||
cacheFilePath: jsonPath,
|
||||
sqliteFilePath: dbPath,
|
||||
enableSqlite: true,
|
||||
loadJsonFn: loadJsonHelper,
|
||||
});
|
||||
writer.setCachedTrajectory(mixedUpperCid, {
|
||||
signature: 'v4:init',
|
||||
title: 'Mixed Case Session',
|
||||
steps: [makeRichStep(1, { turnPrompt: 'Mixed case prompt 1' })],
|
||||
});
|
||||
writer.setCachedTrajectory(conflictCid, {
|
||||
signature: 'v4:s2',
|
||||
title: 'Initial Title',
|
||||
steps: [
|
||||
makeRichStep(1, { turnPrompt: 'Step 1 intact' }),
|
||||
makeRichStep(2, { turnPrompt: 'Step 2 intact' }),
|
||||
],
|
||||
});
|
||||
assert.equal(writer.flushTrajectoryCacheNow(), true);
|
||||
|
||||
// Open Peer A (cold reader/writer) BEFORE Peer B appends Step #3
|
||||
const peerA = createTrajectoryCacheStore({
|
||||
cacheFilePath: jsonPath,
|
||||
sqliteFilePath: dbPath,
|
||||
enableSqlite: true,
|
||||
loadJsonFn: loadJsonHelper,
|
||||
});
|
||||
const coldConflict = peerA.getCachedTrajectory(conflictCid);
|
||||
assert.equal(coldConflict.steps.length, 2);
|
||||
assert.equal(peerA.isConversationCold(conflictCid), true);
|
||||
|
||||
// Peer B appends Step #3 (with rich detail_json) to conflictCid and flushes first
|
||||
const peerB = createTrajectoryCacheStore({
|
||||
cacheFilePath: jsonPath,
|
||||
sqliteFilePath: dbPath,
|
||||
enableSqlite: true,
|
||||
loadJsonFn: loadJsonHelper,
|
||||
});
|
||||
const hydratedB = peerB.getHydratedTrajectory(conflictCid);
|
||||
peerB.setCachedTrajectory(conflictCid, {
|
||||
...hydratedB,
|
||||
signature: 'v4:s3',
|
||||
steps: [...hydratedB.steps, makeRichStep(3, { turnPrompt: 'Step 3 from Peer B' })],
|
||||
});
|
||||
assert.equal(peerB.flushTrajectoryCacheNow(), true);
|
||||
|
||||
// Peer A (still holding stale 2-step cold entry!) updates metadata & re-keys mixedUpperCid -> mixedLowerCid
|
||||
peerA.setCachedTrajectory(conflictCid, {
|
||||
...coldConflict,
|
||||
workspaceUri: 'file:///workspace/project-a',
|
||||
});
|
||||
const coldMixed = peerA.getCachedTrajectory(mixedUpperCid);
|
||||
assert.equal(peerA.isConversationCold(mixedUpperCid), true);
|
||||
peerA.setCachedTrajectory(mixedLowerCid, { ...coldMixed, title: 'Normalized Lower Title' });
|
||||
assert.equal(peerA.flushTrajectoryCacheNow(), true);
|
||||
|
||||
// Also test array-copied slim steps ([...coldEntry.steps]) losing array-level _isColdSlimSteps
|
||||
const peerC = createTrajectoryCacheStore({
|
||||
cacheFilePath: jsonPath,
|
||||
sqliteFilePath: dbPath,
|
||||
enableSqlite: true,
|
||||
loadJsonFn: loadJsonHelper,
|
||||
});
|
||||
const coldMixedC = peerC.getCachedTrajectory(mixedLowerCid);
|
||||
peerC.setCachedTrajectory(mixedLowerCid, {
|
||||
...coldMixedC,
|
||||
steps: [...coldMixedC.steps],
|
||||
});
|
||||
assert.equal(peerC.flushTrajectoryCacheNow(), true);
|
||||
|
||||
// Verify fresh reader sees ALL 3 steps + ALL detail_json on conflictCid AND preserved detail_json on mixedLowerCid!
|
||||
const verifier = createTrajectoryCacheStore({
|
||||
cacheFilePath: jsonPath,
|
||||
sqliteFilePath: dbPath,
|
||||
enableSqlite: true,
|
||||
loadJsonFn: loadJsonHelper,
|
||||
});
|
||||
const verifiedConflict = verifier.getHydratedTrajectory(conflictCid);
|
||||
assert.equal(verifiedConflict.steps.length, 3, 'Peer B step #3 was NOT truncated by Peer A cold metadata flush');
|
||||
assert.equal(verifiedConflict.steps[0].turnPrompt, 'Step 1 intact');
|
||||
assert.equal(verifiedConflict.steps[1].turnPrompt, 'Step 2 intact');
|
||||
assert.equal(verifiedConflict.steps[2].turnPrompt, 'Step 3 from Peer B');
|
||||
assert.equal(verifiedConflict.steps[2].contextBreakdown.totalTokens, 50_600);
|
||||
|
||||
const verifiedMixed = verifier.getHydratedTrajectory(mixedLowerCid);
|
||||
assert.equal(verifiedMixed.title, 'Normalized Lower Title');
|
||||
assert.equal(verifiedMixed.steps.length, 1);
|
||||
assert.equal(verifiedMixed.steps[0].turnPrompt, 'Mixed case prompt 1', 'mixed-case re-keying + array-spread preserved detail_json');
|
||||
|
||||
// 2. Corrupt SQLite file self-healing + automatic recovery from trajectory_usage_cache.json.bak
|
||||
const corruptDir = mkdtempSync(join(tmpdir(), 'ag-um-sqlite-corrupt-'));
|
||||
t.after(() => {
|
||||
rmSync(corruptDir, { recursive: true, force: true });
|
||||
});
|
||||
const corruptDbPath = join(corruptDir, 'trajectory_store.sqlite');
|
||||
const corruptJsonPath = join(corruptDir, 'trajectory_usage_cache.json');
|
||||
const bakCid = '99998888-7777-4666-8555-444433332222';
|
||||
writeFileSync(corruptDbPath, 'CORRUPT_HEADER_NOT_A_VALID_SQLITE_3_DATABASE_IMAGE', 'utf8');
|
||||
writeFileSync(
|
||||
`${corruptJsonPath}.bak`,
|
||||
JSON.stringify({
|
||||
[bakCid]: {
|
||||
signature: 'v4:bak',
|
||||
title: 'Recovered From Backup',
|
||||
steps: [makeRichStep(1, { turnPrompt: 'Backup survived corruption' })],
|
||||
},
|
||||
}),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const healedStore = createTrajectoryCacheStore({
|
||||
cacheFilePath: corruptJsonPath,
|
||||
sqliteFilePath: corruptDbPath,
|
||||
enableSqlite: true,
|
||||
loadJsonFn: loadJsonHelper,
|
||||
});
|
||||
const recovered = healedStore.getHydratedTrajectory(bakCid);
|
||||
assert.ok(recovered, 'corrupt SQLite quarantined and recovered from .json.bak');
|
||||
assert.equal(recovered.title, 'Recovered From Backup');
|
||||
assert.equal(recovered.steps[0].turnPrompt, 'Backup survived corruption');
|
||||
const quarantinedFiles = readdirSync(corruptDir).filter((f) => f.includes('.corrupt.'));
|
||||
assert.equal(quarantinedFiles.length >= 1, true, 'corrupt DB preserved as .corrupt.<ts>');
|
||||
|
||||
// 3. Transient startup load error does NOT latch loadedOnce permanently
|
||||
let failFirstLoad = true;
|
||||
const retryStore = createTrajectoryCacheStore({
|
||||
cacheFilePath: '/virtual/retry.json',
|
||||
enableSqlite: false,
|
||||
loadJsonFn: () => {
|
||||
if (failFirstLoad) {
|
||||
failFirstLoad = false;
|
||||
throw new Error('transient EBUSY');
|
||||
}
|
||||
return { [bakCid]: { signature: 'v4:ok', steps: [makeRichStep(1)] } };
|
||||
},
|
||||
});
|
||||
assert.throws(() => retryStore.getCachedTrajectory(bakCid), /transient EBUSY/);
|
||||
assert.equal(retryStore.getCachedTrajectory(bakCid)?.steps?.length, 1, 'second read succeeds cleanly');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user