mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +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:
@@ -379,13 +379,28 @@ function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountNa
|
||||
});
|
||||
return mutated ? out : steps;
|
||||
}
|
||||
/**
|
||||
* 将旧版缓存签名中 0 字节 `.db-wal` 的非零 mtime 规范化为 `|0:0`(仅当主库签名和 `walSize=0` 完全一致时生效),
|
||||
* 避免从 PR #38 前升级后把数百个未变更的本地 SQLite 历史库一次性全部重扫。
|
||||
*
|
||||
* @param {string} sigStr
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeEmptyWalSqliteSig(sigStr) {
|
||||
const s = String(sigStr || '');
|
||||
if (!s.includes(':sqlite:')) return s;
|
||||
return s.replace(/\|\d+:0$/, '|0:0');
|
||||
}
|
||||
|
||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||
const FAILED_RPC_COOLDOWN_MS = 60_000;
|
||||
const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000;
|
||||
const REMOTE_FAILED_RPC_COOLDOWN_MS = 15 * 60_000;
|
||||
const REMOTE_ACTIVE_FAILED_RPC_COOLDOWN_MS = 30_000;
|
||||
const NOT_FOUND_RPC_COOLDOWN_MS = 30 * 60_000;
|
||||
const REMOTE_TRAJECTORY_RPC_TIMEOUT_MS = 25_000;
|
||||
const REMOTE_TRAJECTORY_RPC_TIMEOUT_MS = 12_000;
|
||||
const REMOTE_POLL_TRAJECTORY_BUDGET_MS = 18_000;
|
||||
const REMOTE_MIN_REMAINING_BUDGET_MS = 2_500;
|
||||
const REMOTE_BACKGROUND_FETCH_LIMIT = 2;
|
||||
const REMOTE_CONSECUTIVE_TIMEOUT_BREAKER = 2;
|
||||
const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024;
|
||||
@@ -1553,6 +1568,19 @@ export async function enumerateAndSyncConversations({
|
||||
const activeLiveActivityMemo = isRemote ? endpoint.liveActivityMemo : liveActivityMemo;
|
||||
const maxConcurrentRpc = isRemote ? 1 : MAX_CONCURRENT_RPC;
|
||||
let remoteConsecutiveTimeouts = 0;
|
||||
let remainingRemoteBackgroundBudget = REMOTE_BACKGROUND_FETCH_LIMIT;
|
||||
let remoteFetchStartedAtMs = 0;
|
||||
|
||||
const getRemoteRemainingBudgetMs = () => {
|
||||
if (!isRemote) return Infinity;
|
||||
if (remoteFetchStartedAtMs <= 0) return REMOTE_POLL_TRAJECTORY_BUDGET_MS;
|
||||
return Math.max(0, REMOTE_POLL_TRAJECTORY_BUDGET_MS - (Date.now() - remoteFetchStartedAtMs));
|
||||
};
|
||||
|
||||
const isRemoteFetchHalted = () =>
|
||||
isRemote &&
|
||||
(remoteConsecutiveTimeouts >= REMOTE_CONSECUTIVE_TIMEOUT_BREAKER ||
|
||||
getRemoteRemainingBudgetMs() < REMOTE_MIN_REMAINING_BUDGET_MS);
|
||||
|
||||
const nowSweepMs = Date.now();
|
||||
if (forceRefresh) {
|
||||
@@ -1962,11 +1990,15 @@ export async function enumerateAndSyncConversations({
|
||||
* @param {object[]} targetConvs
|
||||
*/
|
||||
async function fetchTrajectoryBatch(targetConvs) {
|
||||
if (!Array.isArray(targetConvs) || targetConvs.length === 0) return;
|
||||
if (isRemote && remoteFetchStartedAtMs <= 0) {
|
||||
remoteFetchStartedAtMs = Date.now();
|
||||
}
|
||||
for (const c of targetConvs) {
|
||||
attemptedFetchIds.add(c.cascadeId.toLowerCase());
|
||||
}
|
||||
for (let i = 0; i < targetConvs.length; i += maxConcurrentRpc) {
|
||||
if (isRemote && remoteConsecutiveTimeouts >= REMOTE_CONSECUTIVE_TIMEOUT_BREAKER) {
|
||||
if (isRemoteFetchHalted()) {
|
||||
break;
|
||||
}
|
||||
const batch = targetConvs.slice(i, i + maxConcurrentRpc);
|
||||
@@ -2000,10 +2032,16 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
}
|
||||
if (!trajRes) {
|
||||
const rpcTimeoutMs = isRemote
|
||||
? Math.min(
|
||||
REMOTE_TRAJECTORY_RPC_TIMEOUT_MS,
|
||||
Math.max(REMOTE_MIN_REMAINING_BUDGET_MS, getRemoteRemainingBudgetMs())
|
||||
)
|
||||
: 5000;
|
||||
trajRes = await callLsRpc(
|
||||
'GetCascadeTrajectory',
|
||||
{ cascadeId: conv.cascadeId },
|
||||
isRemote ? REMOTE_TRAJECTORY_RPC_TIMEOUT_MS : 5000,
|
||||
rpcTimeoutMs,
|
||||
endpoint
|
||||
);
|
||||
}
|
||||
@@ -2329,7 +2367,7 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
const errText = String(err?.message || '');
|
||||
const isNotFoundErr = /(?:\(404\)|\bnot_found\b)/i.test(errText);
|
||||
const isTimeoutErr = /(?:timed out|timeout|aborted)/i.test(errText);
|
||||
const isTimeoutErr = /(?:timed\s*out|timeout|etimedout|aborted)/i.test(errText);
|
||||
if (isRemote && isTimeoutErr) {
|
||||
remoteConsecutiveTimeouts += 1;
|
||||
}
|
||||
@@ -2470,9 +2508,20 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
if (hasMissingStepFields(cached)) return true;
|
||||
const missingSubagentRefs = !Array.isArray(cached.subagentRefs);
|
||||
let sigMatches = cached.signature === sig;
|
||||
if (
|
||||
!sigMatches &&
|
||||
conv.dbPath &&
|
||||
sqliteAvailable &&
|
||||
normalizeEmptyWalSqliteSig(cached.signature) === sig
|
||||
) {
|
||||
setEntry(conv.cascadeId, { ...cached, signature: sig });
|
||||
cacheDirty = true;
|
||||
sigMatches = true;
|
||||
}
|
||||
if (!conv.inSummaries) {
|
||||
if (conv.dbPath && sqliteAvailable) {
|
||||
if (Boolean(isRunning) !== Boolean(cached.wasRunning) || cached.signature !== sig) {
|
||||
if (Boolean(isRunning) !== Boolean(cached.wasRunning) || !sigMatches) {
|
||||
return true;
|
||||
}
|
||||
if (isRunning) {
|
||||
@@ -2507,7 +2556,7 @@ export async function enumerateAndSyncConversations({
|
||||
if (
|
||||
cached.offlineTranscriptFallback ||
|
||||
missingSubagentRefs ||
|
||||
cached.signature !== sig ||
|
||||
!sigMatches ||
|
||||
isRunning ||
|
||||
cached.wasRunning
|
||||
) {
|
||||
@@ -2526,7 +2575,7 @@ export async function enumerateAndSyncConversations({
|
||||
});
|
||||
|
||||
let fetchQueue = toFetch;
|
||||
if (isRemote && toFetch.length > REMOTE_BACKGROUND_FETCH_LIMIT) {
|
||||
if (isRemote && toFetch.length > 0) {
|
||||
const priorityConvs = [];
|
||||
const backgroundConvs = [];
|
||||
for (const conv of toFetch) {
|
||||
@@ -2539,8 +2588,9 @@ export async function enumerateAndSyncConversations({
|
||||
Boolean(conv.rootConversationId && conv.rootConversationId.toLowerCase() === selectedRootId);
|
||||
if (isPriority) {
|
||||
priorityConvs.push(conv);
|
||||
} else if (backgroundConvs.length < REMOTE_BACKGROUND_FETCH_LIMIT) {
|
||||
} else if (remainingRemoteBackgroundBudget > 0) {
|
||||
backgroundConvs.push(conv);
|
||||
remainingRemoteBackgroundBudget -= 1;
|
||||
}
|
||||
}
|
||||
fetchQueue = [...priorityConvs, ...backgroundConvs];
|
||||
@@ -2713,15 +2763,41 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
}
|
||||
|
||||
if (missingSubagentsToFetch.length === 0) break;
|
||||
await fetchTrajectoryBatch(missingSubagentsToFetch);
|
||||
if (missingSubagentsToFetch.length === 0 || isRemoteFetchHalted()) break;
|
||||
let subagentFetchQueue = missingSubagentsToFetch;
|
||||
if (isRemote) {
|
||||
const prioritySubs = [];
|
||||
const backgroundSubs = [];
|
||||
for (const subConv of missingSubagentsToFetch) {
|
||||
const isPrioritySub =
|
||||
subConv.status === 'CASCADE_RUN_STATUS_RUNNING' ||
|
||||
subConv.cascadeId.toLowerCase() === reqLower ||
|
||||
Boolean(subConv.rootConversationId && subConv.rootConversationId.toLowerCase() === selectedRootId);
|
||||
if (isPrioritySub) {
|
||||
prioritySubs.push(subConv);
|
||||
} else if (remainingRemoteBackgroundBudget > 0) {
|
||||
backgroundSubs.push(subConv);
|
||||
remainingRemoteBackgroundBudget -= 1;
|
||||
}
|
||||
}
|
||||
subagentFetchQueue = [...prioritySubs, ...backgroundSubs];
|
||||
}
|
||||
if (subagentFetchQueue.length === 0) break;
|
||||
await fetchTrajectoryBatch(subagentFetchQueue);
|
||||
}
|
||||
}
|
||||
|
||||
await reconcileParentSubagentRefs();
|
||||
|
||||
// 阶段 3:对剩余尚未标记 subagentRefs 的纯磁盘历史会话每次增量迁移最多 8 个,避免单次轮询阻塞
|
||||
const remainingLegacyDiskConvs = rawConversations
|
||||
// 阶段 3:对剩余尚未标记 subagentRefs 的纯磁盘历史会话每次增量迁移最多 8 个(远端共享整轮背景额度),避免单次轮询阻塞
|
||||
const legacyBatchCap = isRemote
|
||||
? isRemoteFetchHalted()
|
||||
? 0
|
||||
: Math.min(LEGACY_MIGRATION_BATCH_SIZE, remainingRemoteBackgroundBudget)
|
||||
: LEGACY_MIGRATION_BATCH_SIZE;
|
||||
const remainingLegacyDiskConvs =
|
||||
legacyBatchCap > 0
|
||||
? rawConversations
|
||||
.filter((c) => {
|
||||
const sig = buildConvSig(c);
|
||||
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
|
||||
@@ -2730,9 +2806,16 @@ export async function enumerateAndSyncConversations({
|
||||
const cached = getEntry(c.cascadeId);
|
||||
return cached && !Array.isArray(cached.subagentRefs);
|
||||
})
|
||||
.slice(0, LEGACY_MIGRATION_BATCH_SIZE);
|
||||
.slice(0, legacyBatchCap)
|
||||
: [];
|
||||
|
||||
if (remainingLegacyDiskConvs.length > 0) {
|
||||
if (isRemote) {
|
||||
remainingRemoteBackgroundBudget = Math.max(
|
||||
0,
|
||||
remainingRemoteBackgroundBudget - remainingLegacyDiskConvs.length
|
||||
);
|
||||
}
|
||||
await fetchTrajectoryBatch(remainingLegacyDiskConvs);
|
||||
await reconcileParentSubagentRefs();
|
||||
}
|
||||
|
||||
@@ -216,10 +216,14 @@ async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) {
|
||||
});
|
||||
}
|
||||
|
||||
const REMOTE_TIER2_MIN_REMAINING_MS = 1500;
|
||||
|
||||
async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
|
||||
if (!REMOTE_ALLOWED_LS_METHODS.has(method)) {
|
||||
throw new Error(`RPC method ${method} is not allowed on remote endpoints`);
|
||||
}
|
||||
const safeTimeoutMs = Math.max(1000, Number(timeoutMs) || 5000);
|
||||
const deadlineMs = Date.now() + safeTimeoutMs;
|
||||
const baseUrl = String(endpoint.baseUrl || endpoint.origin || '').trim().replace(/\/+$/, '');
|
||||
const csrfToken = String(endpoint.csrfToken || '').trim();
|
||||
const windowInvoker = getRemoteWindowRpcInvoker();
|
||||
@@ -235,8 +239,8 @@ async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
|
||||
const urlStr = `${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`;
|
||||
const bodyText = JSON.stringify(body || {});
|
||||
const res = urlStr.startsWith('https://')
|
||||
? await postLoopbackHttpsJson(urlStr, csrfToken, bodyText, timeoutMs)
|
||||
: await postLsRpcOnce(baseUrl, csrfToken, method, body || {}, timeoutMs);
|
||||
? await postLoopbackHttpsJson(urlStr, csrfToken, bodyText, safeTimeoutMs)
|
||||
: await postLsRpcOnce(baseUrl, csrfToken, method, body || {}, safeTimeoutMs);
|
||||
if (res?.ok) {
|
||||
return await res.json();
|
||||
}
|
||||
@@ -264,7 +268,15 @@ async function callRemoteEndpointLsRpc(endpoint, method, body, timeoutMs) {
|
||||
}
|
||||
|
||||
if (typeof windowInvoker === 'function') {
|
||||
return windowInvoker(endpoint, method, body || {}, timeoutMs);
|
||||
const remainingMs = canTryTier1 ? deadlineMs - Date.now() : safeTimeoutMs;
|
||||
if (!canTryTier1 || remainingMs >= REMOTE_TIER2_MIN_REMAINING_MS) {
|
||||
return windowInvoker(
|
||||
endpoint,
|
||||
method,
|
||||
body || {},
|
||||
Math.max(1000, Math.min(safeTimeoutMs, remainingMs))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (tier1Err) {
|
||||
|
||||
@@ -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