mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
fix(panel): enforce remote RPC deadline/poll budget, cap Stage 2/3 fetches, and migrate empty-WAL signatures in-place
This commit is contained in:
@@ -826,3 +826,138 @@ test('computeSqliteWalSig ignores zero-byte .db-wal mtime churn while detecting
|
||||
const sigTruncatedWal = computeSqliteWalSig(dbPath);
|
||||
assert.deepEqual(sigTruncatedWal, sigNoWal);
|
||||
});
|
||||
|
||||
test('legacy pre-PR#38 empty-WAL sqlite cache signatures migrate in-place without re-reading SQLite', async (t) => {
|
||||
const { normalizeEmptyWalSqliteSig } = await import('../backend/local-scanner.mjs');
|
||||
|
||||
assert.equal(
|
||||
normalizeEmptyWalSqliteSig('v10-model-identity:sqlite:12:2026-11-22T10:00:00Z:1795400000:50000|1795412345:0'),
|
||||
'v10-model-identity:sqlite:12:2026-11-22T10:00:00Z:1795400000:50000|0:0'
|
||||
);
|
||||
assert.equal(
|
||||
normalizeEmptyWalSqliteSig('v10-model-identity:sqlite:12:2026-11-22T10:00:00Z:1795400000:50000|1795412345:4096'),
|
||||
'v10-model-identity:sqlite:12:2026-11-22T10:00:00Z:1795400000:50000|1795412345:4096',
|
||||
'non-empty WAL signature must NOT be collapsed'
|
||||
);
|
||||
|
||||
// End-to-end verification in isolated subprocess: pre-seed trajectory_usage_cache.json with legacy |<walMtime>:0
|
||||
// signature for a real .db + 0-byte .db-wal, verify enumerateAndSyncConversations does NOT re-read SQLite
|
||||
// (keeping sentinel step marker intact) and normalizes cached signature to |0:0.
|
||||
let sqliteMod = null;
|
||||
try {
|
||||
sqliteMod = await import('node:sqlite');
|
||||
} catch {
|
||||
sqliteMod = null;
|
||||
}
|
||||
if (!sqliteMod?.DatabaseSync) {
|
||||
t.skip('node:sqlite DatabaseSync unavailable');
|
||||
return;
|
||||
}
|
||||
const { DatabaseSync } = sqliteMod;
|
||||
const tempRoot = mkdtempSync(join(tmpdir(), 'agy-sqlite-smooth-upgrade-'));
|
||||
t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
||||
|
||||
const geminiDir = join(tempRoot, '.gemini');
|
||||
const convDir = join(geminiDir, 'antigravity', 'conversations');
|
||||
const dataDir = join(geminiDir, 'antigravity', 'sidecar_data', 'usage-monitor', 'panel', 'data');
|
||||
mkdirSync(convDir, { recursive: true });
|
||||
mkdirSync(dataDir, { recursive: true });
|
||||
|
||||
const cid = '99999999-9999-4999-8999-999999999999';
|
||||
const dbPath = join(convDir, `${cid}.db`);
|
||||
const walPath = `${dbPath}-wal`;
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
PRAGMA journal_mode = WAL;
|
||||
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||
`);
|
||||
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid);
|
||||
db.close();
|
||||
|
||||
const baseSec = 1_795_000_000;
|
||||
writeFileSync(walPath, Buffer.alloc(0));
|
||||
utimesSync(dbPath, baseSec, baseSec);
|
||||
utimesSync(walPath, baseSec + 120, baseSec + 120);
|
||||
|
||||
const curSig = computeSqliteWalSig(dbPath);
|
||||
assert.ok(curSig.sig.endsWith('|0:0'));
|
||||
const legacyDiskSig = curSig.sig.replace(/\|0:0$/, `|${(baseSec + 120) * 1000}:0`);
|
||||
const legacyFullSig = `v10-model-identity:sqlite:1::${legacyDiskSig}`;
|
||||
|
||||
// Write a sentinel cached step so if SQLite were re-read (empty steps table), the sentinel would vanish!
|
||||
const cacheFile = join(dataDir, 'trajectory_usage_cache.json');
|
||||
writeFileSync(
|
||||
cacheFile,
|
||||
JSON.stringify({
|
||||
[cid]: {
|
||||
title: 'Pre-PR38 Cached Session',
|
||||
signature: legacyFullSig,
|
||||
lastModifiedMs: baseSec * 1000,
|
||||
diskMtimeMs: baseSec * 1000,
|
||||
wasRunning: false,
|
||||
offlineSqliteTelemetry: true,
|
||||
contextLimitTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
turnRailTelemetry: true,
|
||||
anomalyTelemetry: true,
|
||||
subagentRefs: [],
|
||||
steps: [
|
||||
{
|
||||
stepIndex: 0,
|
||||
turnIndex: 1,
|
||||
model: 'MODEL_PLACEHOLDER_M429',
|
||||
responseModel: 'gemini-4-carbon-high',
|
||||
inputTokens: 1234,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 567,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 567,
|
||||
createdAtMs: baseSec * 1000,
|
||||
completedAtMs: (baseSec + 2) * 1000,
|
||||
durationSec: 2,
|
||||
ttftSec: 0.5,
|
||||
streamSec: 1.5,
|
||||
contextBreakdown: { toolResultsTokens: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const scannerUrl = new URL('../backend/local-scanner.mjs', import.meta.url).href;
|
||||
const configUrl = new URL('../backend/config.mjs', import.meta.url).href;
|
||||
const script = `
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { enumerateAndSyncConversations } from ${JSON.stringify(scannerUrl)};
|
||||
import { CACHE_FILE, flushTrajectoryCacheNow, getCachedTrajectory } from ${JSON.stringify(configUrl)};
|
||||
await enumerateAndSyncConversations({ summariesObj: {}, requestedConvId: '' });
|
||||
const entry = getCachedTrajectory(${JSON.stringify(cid)});
|
||||
flushTrajectoryCacheNow();
|
||||
const onDisk = JSON.parse(readFileSync(CACHE_FILE, 'utf8'));
|
||||
console.log(JSON.stringify({
|
||||
memSig: entry?.signature || '',
|
||||
diskSig: onDisk[${JSON.stringify(cid)}]?.signature || '',
|
||||
stepCount: entry?.steps?.length || 0,
|
||||
firstInput: entry?.steps?.[0]?.inputTokens || 0,
|
||||
}));
|
||||
`;
|
||||
const { stdout } = await execFileAsync(process.execPath, ['--input-type=module', '-e', script], {
|
||||
env: {
|
||||
...process.env,
|
||||
ANTIGRAVITY_GEMINI_DIR: geminiDir,
|
||||
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||
ANTIGRAVITY_EXECUTABLE_DATA_DIR: dataDir,
|
||||
ANTIGRAVITY_LS_ADDRESS: 'test.invalid',
|
||||
},
|
||||
});
|
||||
const out = JSON.parse(stdout.trim().split('\n').pop());
|
||||
assert.equal(out.stepCount, 1, 'cached sentinel step preserved (SQLite was NOT re-read)');
|
||||
assert.equal(out.firstInput, 1234, 'cached usage preserved intact');
|
||||
assert.ok(out.memSig.endsWith('|0:0'), `in-memory signature normalized to |0:0: ${out.memSig}`);
|
||||
assert.ok(out.diskSig.endsWith('|0:0'), `persisted signature normalized to |0:0: ${out.diskSig}`);
|
||||
});
|
||||
|
||||
@@ -2371,28 +2371,29 @@ test('remote endpoint caps background history fetches per poll, prioritizes acti
|
||||
if (cid === missingCid) {
|
||||
throw new Error('RPC GetCascadeTrajectory failed (404): not_found');
|
||||
}
|
||||
// Simulate slow remote RPC advancing the clock by 70s (> old 60s cooldown) before timing out
|
||||
now += 70_000;
|
||||
// Simulate slow remote RPC advancing the clock by 8s per attempt (within 18s poll budget)
|
||||
now += 8_000;
|
||||
throw new Error('signal timed out');
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
// Poll A: t1 (selected, isReq=true -> 30s cooldown) and t2 (background -> 15m cooldown) both time out
|
||||
// after advancing clock by 70s each -> trips 2-consecutive-timeout breaker, so t3 is NOT attempted.
|
||||
// Poll A: t1 (selected, isReq=true -> 30s cooldown, completes at T+8s) and
|
||||
// t2 (background -> 15m cooldown, completes at T+16s) both time out ->
|
||||
// trips 2-consecutive-timeout breaker, so t3 is NOT attempted.
|
||||
await h.executeTelemetryAction({ conversationId: t1, range: 'today' }, { endpointId: ep2.id });
|
||||
assert.deepEqual(calls2, [t1, t2]);
|
||||
|
||||
// Poll B (+15s after Poll A finished): if failedAt had wrongly used nowPollMs (140s earlier),
|
||||
// BOTH t1 and t2 would already be expired; with completion-time Date.now(), t2 stays in 15m cooldown
|
||||
// (and t1 is still within 30s of its completion if only 15s elapsed since t2 finished? t1 finished 85s ago -> expired,
|
||||
// while t2 finished 15s ago -> still in 15m cooldown). Verify t2 stays suppressed and t3 + missingCid run.
|
||||
// Poll B (+16s after Poll A finished -> T+32s): if failedAt had wrongly used nowPollMs (T+0),
|
||||
// t1's 30s active cooldown would ALREADY be expired (32s >= 30s); with completion-time Date.now()
|
||||
// (T+8s), t1 is only 24s old and stays suppressed alongside t2 while t3 + missingCid run.
|
||||
calls2.length = 0;
|
||||
now += 15_000;
|
||||
now += 16_000;
|
||||
await h.executeTelemetryAction({ conversationId: t3, range: 'today' }, { endpointId: ep2.id });
|
||||
assert.equal(calls2.includes(t1), false, 't1 completion-time 30s cooldown must still hold at T+32s');
|
||||
assert.equal(calls2.includes(t2), false, 't2 must stay in 15m remote timeout cooldown');
|
||||
assert.ok(calls2.includes(t3), 'selected t3 must be attempted');
|
||||
assert.ok(calls2.includes(missingCid) || calls2.includes(t1), 'remaining non-cooled entries proceed until breaker');
|
||||
assert.ok(calls2.includes(missingCid), 'missingCid must be attempted after non-timeout or single timeout');
|
||||
|
||||
// Ensure missingCid hits 404 once if deferred by breaker above
|
||||
if (!calls2.includes(missingCid)) {
|
||||
@@ -2416,5 +2417,200 @@ test('remote endpoint caps background history fetches per poll, prioritizes acti
|
||||
assert.equal(calls2.includes(missingCid), false, '404 missingCid must stay in 30m cooldown after 20m');
|
||||
});
|
||||
|
||||
test('remote RPC enforces single Tier-1->Tier-2 deadline, clamps per-poll trajectory budget, recognizes ETIMEDOUT, and caps Stage 2/3 background fetches', async () => {
|
||||
const { callLsRpc } = await import('../backend/ls-rpc.mjs');
|
||||
const { setRemoteWindowRpcInvoker, shouldRemoteEndpointPreferTier2 } = await import(
|
||||
'../backend/endpoint-registry.mjs'
|
||||
);
|
||||
|
||||
// 1. Tier-1 timeout consuming the full deadline must NOT double-wait in Tier-2;
|
||||
// fast Tier-1 failure falls back to Tier-2 with remaining deadline only.
|
||||
const origDateNow = Date.now;
|
||||
const origFetch = globalThis.fetch;
|
||||
let fakeNow = Date.UTC(2026, 10, 23, 8, 0, 0);
|
||||
Date.now = () => fakeNow;
|
||||
const tier2Calls = [];
|
||||
setRemoteWindowRpcInvoker(async (_ep, method, _body, timeoutMs) => {
|
||||
tier2Calls.push({ method, timeoutMs });
|
||||
return { trajectory: { steps: [] } };
|
||||
});
|
||||
|
||||
try {
|
||||
const epSlowTier1 = registerRemoteEndpoint({
|
||||
origin: 'http://127.0.0.1:43101',
|
||||
baseUrl: 'http://127.0.0.1:43101',
|
||||
csrfToken: 'tok-slow',
|
||||
hostLabel: 'tier1-timeout-host',
|
||||
stableHostKey: 'tier1-timeout-host',
|
||||
});
|
||||
globalThis.fetch = async () => {
|
||||
fakeNow += 12_000;
|
||||
throw new Error('connect ETIMEDOUT 127.0.0.1:43101');
|
||||
};
|
||||
await assert.rejects(
|
||||
() => callLsRpc('GetCascadeTrajectory', { cascadeId: 'cid-1' }, 12_000, epSlowTier1),
|
||||
/ETIMEDOUT/
|
||||
);
|
||||
assert.equal(tier2Calls.length, 0, 'exhausted Tier-1 deadline must skip Tier-2 double-wait');
|
||||
assert.equal(shouldRemoteEndpointPreferTier2(epSlowTier1), true, 'endpoint switches to Tier-2 for subsequent calls');
|
||||
|
||||
// Subsequent call on same endpoint goes straight to Tier-2 with full 12s budget
|
||||
await callLsRpc('GetCascadeTrajectory', { cascadeId: 'cid-1' }, 12_000, epSlowTier1);
|
||||
assert.equal(tier2Calls.length, 1);
|
||||
assert.equal(tier2Calls[0].timeoutMs, 12_000);
|
||||
|
||||
// Fast Tier-1 transport failure (200ms) falls back to Tier-2 with reduced remaining timeout
|
||||
tier2Calls.length = 0;
|
||||
const epFastFail = registerRemoteEndpoint({
|
||||
origin: 'http://127.0.0.1:43102',
|
||||
baseUrl: 'http://127.0.0.1:43102',
|
||||
csrfToken: 'tok-fast',
|
||||
hostLabel: 'tier1-fastfail-host',
|
||||
stableHostKey: 'tier1-fastfail-host',
|
||||
});
|
||||
globalThis.fetch = async () => {
|
||||
fakeNow += 200;
|
||||
throw new Error('ECONNREFUSED');
|
||||
};
|
||||
await callLsRpc('GetCascadeTrajectory', { cascadeId: 'cid-2' }, 12_000, epFastFail);
|
||||
assert.equal(tier2Calls.length, 1);
|
||||
assert.equal(tier2Calls[0].timeoutMs, 11_800);
|
||||
} finally {
|
||||
Date.now = origDateNow;
|
||||
globalThis.fetch = origFetch;
|
||||
setRemoteWindowRpcInvoker(null);
|
||||
clearRemoteEndpointRegistry();
|
||||
}
|
||||
|
||||
// 2. Per-poll remote wall-clock budget clamps per-RPC timeoutMs, stops before 30s worker timeout,
|
||||
// and recognizes ETIMEDOUT for breaker counting.
|
||||
let now = Date.UTC(2026, 10, 23, 9, 0, 0);
|
||||
const h = backendHarness({ clock: () => now });
|
||||
const epBudget = h.registerRemoteEndpoint({
|
||||
origin: 'https://127.0.0.1:43103',
|
||||
hostLabel: 'budget-ssh-host',
|
||||
stableHostKey: 'budget-ssh-host',
|
||||
});
|
||||
const isoAt = (sec) => new Date(Date.UTC(2026, 10, 23, 8, 0, sec)).toISOString();
|
||||
const b1 = '33333333-3333-4333-8333-000000000001';
|
||||
const b2 = '33333333-3333-4333-8333-000000000002';
|
||||
const b3 = '33333333-3333-4333-8333-000000000003';
|
||||
const seenTimeouts = [];
|
||||
|
||||
h.setRemoteWindowRpcInvoker(async (_ep, method, body, timeoutMs) => {
|
||||
if (method === 'GetUserStatus') return { userStatus: { email: 'remote@example.com' } };
|
||||
if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } };
|
||||
if (method === 'GetAllCascadeTrajectories') {
|
||||
return {
|
||||
trajectorySummaries: {
|
||||
[b1]: { stepCount: 1, createdTime: isoAt(90), lastModifiedTime: isoAt(90), status: 'CASCADE_RUN_STATUS_RUNNING' },
|
||||
[b2]: { stepCount: 1, createdTime: isoAt(80), lastModifiedTime: isoAt(80), status: 'CASCADE_RUN_STATUS_RUNNING' },
|
||||
[b3]: { stepCount: 1, createdTime: isoAt(70), lastModifiedTime: isoAt(70), status: 'CASCADE_RUN_STATUS_RUNNING' },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === 'GetCascadeTrajectory') {
|
||||
seenTimeouts.push({ cid: body?.cascadeId, timeoutMs });
|
||||
if (body?.cascadeId === b1) {
|
||||
now += 10_000;
|
||||
throw new Error('connect ETIMEDOUT 127.0.0.1:43103');
|
||||
}
|
||||
now += 6_000;
|
||||
throw new Error('ESOCKETTIMEDOUT');
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
await h.executeTelemetryAction({ conversationId: b1, range: 'today' }, { endpointId: epBudget.id });
|
||||
assert.deepEqual(
|
||||
seenTimeouts.map((x) => x.cid),
|
||||
[b1, b2],
|
||||
'poll stops after 16s elapsed (< 2.5s budget remaining) and ETIMEDOUT breaker'
|
||||
);
|
||||
assert.equal(seenTimeouts[0].timeoutMs, 12_000, 'first remote trajectory capped at 12s');
|
||||
assert.equal(seenTimeouts[1].timeoutMs, 8_000, 'second remote trajectory clamped to remaining 8s budget');
|
||||
|
||||
// 3. Stage 2 (non-selected historical subagents) shares REMOTE_BACKGROUND_FETCH_LIMIT = 2 with Stage 1
|
||||
const epSub = h.registerRemoteEndpoint({
|
||||
origin: 'https://127.0.0.1:43104',
|
||||
hostLabel: 'subagent-cap-ssh-host',
|
||||
stableHostKey: 'subagent-cap-ssh-host',
|
||||
});
|
||||
const activeSel = '44444444-4444-4444-8444-000000000001';
|
||||
const histParent = '44444444-4444-4444-8444-000000000002';
|
||||
const subIds = [
|
||||
'44444444-4444-4444-8444-000000000011',
|
||||
'44444444-4444-4444-8444-000000000012',
|
||||
'44444444-4444-4444-8444-000000000013',
|
||||
'44444444-4444-4444-8444-000000000014',
|
||||
'44444444-4444-4444-8444-000000000015',
|
||||
];
|
||||
const makeBasicStep = (sec) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: isoAt(sec),
|
||||
completedAt: isoAt(sec + 1),
|
||||
generatorModel: 'gemini-4-carbon-high',
|
||||
modelUsage: { model: 'gemini-4-carbon-high', inputTokens: '100', outputTokens: '50' },
|
||||
},
|
||||
});
|
||||
const subFetchLog = [];
|
||||
|
||||
h.setRemoteWindowRpcInvoker(async (_ep, method, body) => {
|
||||
if (method === 'GetUserStatus') return { userStatus: { email: 'remote@example.com' } };
|
||||
if (method === 'RetrieveUserQuotaSummary') return { response: { groups: [] } };
|
||||
if (method === 'GetAllCascadeTrajectories') {
|
||||
return {
|
||||
trajectorySummaries: {
|
||||
[activeSel]: { stepCount: 1, createdTime: isoAt(90), lastModifiedTime: isoAt(90), status: 'CASCADE_RUN_STATUS_IDLE' },
|
||||
[histParent]: { stepCount: 6, createdTime: isoAt(80), lastModifiedTime: isoAt(80), status: 'CASCADE_RUN_STATUS_IDLE' },
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === 'GetCascadeTrajectory') {
|
||||
const cid = body?.cascadeId;
|
||||
subFetchLog.push(cid);
|
||||
if (cid === histParent) {
|
||||
return {
|
||||
trajectory: {
|
||||
steps: [
|
||||
makeBasicStep(1),
|
||||
...subIds.map((sid, idx) => ({
|
||||
type: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: { createdAt: isoAt(10 + idx) },
|
||||
invokeSubagent: {
|
||||
conversationId: sid,
|
||||
subagents: [{ role: `worker-${idx + 1}`, typeName: 'research' }],
|
||||
},
|
||||
})),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
return { trajectory: { steps: [makeBasicStep(2)] } };
|
||||
}
|
||||
return {};
|
||||
});
|
||||
|
||||
// Poll 1: activeSel (priority) + histParent (1 background slot in Stage 1) ->
|
||||
// Stage 2 has only 1 remaining background slot left, so at most 1 of the 5 historical subagents is fetched!
|
||||
await h.executeTelemetryAction({ conversationId: activeSel, range: 'today' }, { endpointId: epSub.id });
|
||||
const bgSubFetchedPoll1 = subFetchLog.filter((id) => subIds.includes(id));
|
||||
assert.equal(
|
||||
bgSubFetchedPoll1.length,
|
||||
1,
|
||||
`Stage 1 (1 bg) + Stage 2 (${bgSubFetchedPoll1.length} bg) must share the 2-item remote background cap`
|
||||
);
|
||||
|
||||
// Poll 2: histParent is now cached, so Stage 2 fetches 2 more background subagents (total 3 of 5)
|
||||
subFetchLog.length = 0;
|
||||
now += 5_000;
|
||||
await h.executeTelemetryAction({ conversationId: activeSel, range: 'today' }, { endpointId: epSub.id });
|
||||
const bgSubFetchedPoll2 = subFetchLog.filter((id) => subIds.includes(id));
|
||||
assert.equal(bgSubFetchedPoll2.length, 2, 'subsequent poll drains 2 more historical subagents');
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user