Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

docs(agent-index): document the cron auth layers and keep the health board honest

nirholas88270c25a10b
diff --git a/api/_lib/ops/index-lag.js b/api/_lib/ops/index-lag.js
index 4f8c5c4eb..06bd43161 100644
--- a/api/_lib/ops/index-lag.js
+++ b/api/_lib/ops/index-lag.js
@@ -79,7 +79,7 @@ function withTimeout(promise, ms) {
* evm: { lagMin: number|null, chains: number, configuredChains: number,
* uncrawledChains: number, staleChains: number, worstBlocksBehind: number,
* behindChains: number, worstChainId: number|null, worstChainName: string|null,
- * events: number },
+ * historyGapChains: number, historyGapBlocks: number, events: number },
* lastEventAt: string|null,
* lastIndexedAt: string|null,
* }>}
@@ -111,6 +111,8 @@ export async function readIndexLag() {
count(*) FILTER (WHERE blocks_behind >= ${EVM_BLOCKS_BEHIND_DEGRADED})::int AS behind_chains,
max(extract(epoch FROM now() - updated_at) / 60)::int AS lag_min,
coalesce(max(blocks_behind), 0)::bigint AS worst_blocks_behind,
+ count(*) FILTER (WHERE history_gap_blocks > 0)::int AS gap_chains,
+ coalesce(sum(history_gap_blocks), 0)::bigint AS gap_blocks,
(
SELECT chain_id FROM erc8004_crawl_cursor
ORDER BY blocks_behind DESC LIMIT 1
@@ -162,6 +164,13 @@ export async function readIndexLag() {
worstBlocksBehind: Number(e.worst_blocks_behind ?? 0),
worstChainId,
worstChainName: CHAINS.find((c) => c.id === worstChainId)?.name ?? null,
+ // Blocks the crawl skipped past a provider that no longer serves them.
+ // Reported, never scored: the gap is history that is already lost, so
+ // letting it drive the verdict would keep the subsystem red forever
+ // over something no tick can fix. It belongs on the surface anyway,
+ // because skipping is what MAKES a chain report zero backlog again.
+ historyGapChains: e.gap_chains ?? 0,
+ historyGapBlocks: Number(e.gap_blocks ?? 0),
events: t.evm_events ?? 0,
},
lastEventAt: t.last_event_at ? new Date(t.last_event_at).toISOString() : null,
@@ -262,6 +271,9 @@ export function indexLagVerdict(lag) {
(lag.evm.behindChains ? `, ${lag.evm.behindChains} behind` : '') +
(lag.evm.staleChains ? `, ${lag.evm.staleChains} stale` : '') +
(lag.evm.uncrawledChains ? `, ${lag.evm.uncrawledChains} never crawled` : '') +
+ (lag.evm.historyGapChains
+ ? `, ${lag.evm.historyGapChains} carrying a permanent ${lag.evm.historyGapBlocks.toLocaleString('en-US')}-block history gap`
+ : '') +
`, ${lag.evm.events} events`;
const detail =
diff --git a/api/_lib/solana-agent-events.js b/api/_lib/solana-agent-events.js
index 9fafc9140..403fb7494 100644
--- a/api/_lib/solana-agent-events.js
+++ b/api/_lib/solana-agent-events.js
@@ -549,6 +549,63 @@ export const SOLANA_SWEEP_BUDGET_MS = 120_000;
* failed: number, truncated: boolean, batch: number, concurrency: number,
* elapsedMs: number, error?: string }>}
*/
+/**
+ * Run `handle` over `items` through a small worker pool, stopping on a
+ * wall-clock budget rather than on the list.
+ *
+ * Split out from the sweep because the pool is the part with the edge cases and
+ * the sweep is the part that needs a database and twenty RPC providers: this
+ * way the ordering, the budget and the truncation flag are exercised directly,
+ * with a real list and a real clock function, instead of being reasoned about.
+ *
+ * `truncated` means the budget expired with items still queued. It is read
+ * BEFORE the clock on purpose, so a run that consumed its last item on the
+ * final millisecond reports completion rather than phantom unfinished work.
+ *
+ * @template T
+ * @param {T[]} items
+ * @param {(item: T, index: number) => Promise<void>} handle
+ * @param {{ concurrency?: number, budgetMs?: number, now?: () => number }} [opts]
+ * @returns {Promise<{ processed: number, truncated: boolean, workers: number, elapsedMs: number }>}
+ */
+export async function drainWithBudget(items, handle, { concurrency = 1, budgetMs = Infinity, now = Date.now } = {}) {
+ const startedAt = now();
+ const workers = Math.max(1, Math.min(Math.trunc(concurrency) || 1, items.length || 1));
+ let next = 0;
+ let truncated = false;
+
+ const drain = async () => {
+ for (;;) {
+ if (next >= items.length) return;
+ if (now() - startedAt > budgetMs) {
+ truncated = true;
+ return;
+ }
+ const index = next++;
+ await handle(items[index], index);
+ }
+ };
+
+ await Promise.all(Array.from({ length: workers }, drain));
+ return { processed: next, truncated, workers, elapsedMs: now() - startedAt };
+}
+
+/**
+ * Crawl one tick's worth of the Solana agent directory.
+ *
+ * Drains the oldest-cursor-first batch through the pool above, stops on the
+ * budget rather than on the batch, and stamps a failure onto every agent it
+ * could not read so one unreadable account cannot hold the queue head forever.
+ *
+ * A `truncated` tick is the signal that the batch has outgrown the budget: the
+ * cycle time the freshness sensor derives from SOLANA_SWEEP_BATCH assumes a
+ * batch that drains, so from that point on the sensor's cycle is optimistic.
+ *
+ * @param {{ budgetMs?: number, limit?: number, concurrency?: number, now?: () => number }} [opts]
+ * @returns {Promise<{ agents: number, scanned: number, inserted: number, rejected: number,
+ * failed: number, truncated: boolean, batch: number, concurrency: number,
+ * elapsedMs: number, error?: string }>}
+ */
export async function sweepAgentEvents({
budgetMs = SOLANA_SWEEP_BUDGET_MS,
limit = SOLANA_SWEEP_BATCH,
@@ -574,23 +631,11 @@ export async function sweepAgentEvents({
} catch (err) {
return { ...summary, elapsedMs: now() - startedAt, error: err?.message || String(err) };
}
-
summary.batch = batch.length;
- const workers = Math.max(1, Math.min(concurrency, batch.length));
- summary.concurrency = workers;
- let next = 0;
- const drain = async () => {
- for (;;) {
- // Read the queue position BEFORE the clock, so a tick that finished its
- // batch on the last millisecond of the budget is reported as complete
- // rather than as truncated work that never existed.
- if (next >= batch.length) return;
- if (now() - startedAt > budgetMs) {
- summary.truncated = true;
- return;
- }
- const row = batch[next++];
+ const run = await drainWithBudget(
+ batch,
+ async (row) => {
try {
const r = await crawlAgentEvents({ agentRef: row.agent_ref, network: row.network });
summary.agents += 1;
@@ -605,10 +650,12 @@ export async function sweepAgentEvents({
error: err?.message || String(err),
}).catch(() => {});
}
- }
- };
+ },
+ { concurrency, budgetMs, now },
+ );
- await Promise.all(Array.from({ length: workers }, drain));
- summary.elapsedMs = now() - startedAt;
+ summary.truncated = run.truncated;
+ summary.concurrency = run.workers;
+ summary.elapsedMs = run.elapsedMs;
return summary;
}
diff --git a/api/cron/[name].js b/api/cron/[name].js
index f4a7c7991..9850bfff2 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -794,16 +794,32 @@ async function erc8004CrawlChain(chain) {
// ran, and a chain producing blocks faster than the crawl consumes them keeps
// a fresh updated_at forever while falling further behind every tick.
const blocksBehind = Math.max(0, latestBlock - toBlock);
+ // A skip closes the backlog, which is exactly why the gap has to be banked
+ // here. The moment the cursor reaches the head this chain reports zero blocks
+ // behind and reads as perfectly healthy, so the span it jumped over would
+ // otherwise exist only in one cron response that rotates out of the logs.
+ // Accumulated, never overwritten: a provider that keeps pruning under the
+ // crawl shows up as a number that grows.
+ const gapBlocks = prunedSkip ? prunedSkip.blocks : 0;
await sql`
- INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at, head_block, blocks_behind, chunk_size, last_error)
- VALUES (${chain.id}, ${toBlock}, now(), ${latestBlock}, ${blocksBehind}, ${chunkSize}, null)
+ INSERT INTO erc8004_crawl_cursor (
+ chain_id, last_block, updated_at, head_block, blocks_behind, chunk_size, last_error,
+ history_gap_blocks, history_gap_to, history_gap_at
+ )
+ VALUES (
+ ${chain.id}, ${toBlock}, now(), ${latestBlock}, ${blocksBehind}, ${chunkSize}, null,
+ ${gapBlocks}, ${prunedSkip ? prunedSkip.to : null}, ${prunedSkip ? new Date() : null}
+ )
ON CONFLICT (chain_id) DO UPDATE SET
last_block = GREATEST(erc8004_crawl_cursor.last_block, ${toBlock}),
updated_at = now(),
head_block = excluded.head_block,
blocks_behind = excluded.blocks_behind,
chunk_size = excluded.chunk_size,
- last_error = null
+ last_error = null,
+ history_gap_blocks = erc8004_crawl_cursor.history_gap_blocks + excluded.history_gap_blocks,
+ history_gap_to = COALESCE(excluded.history_gap_to, erc8004_crawl_cursor.history_gap_to),
+ history_gap_at = COALESCE(excluded.history_gap_at, erc8004_crawl_cursor.history_gap_at)
`;
return {
diff --git a/docs/ops/README.md b/docs/ops/README.md
index 5958324c8..276ebd940 100644
--- a/docs/ops/README.md
+++ b/docs/ops/README.md
@@ -14,6 +14,7 @@ Start with [gcp-production.md](gcp-production.md); it is the complete operationa
| [gcp-logs.md](gcp-logs.md) | Production log reading and automated triage tools for the Cloud Run fleet. |
| [production-log-triage.md](production-log-triage.md) | Known error/warning signature map: what each recurring log signature means and the fix. |
| [forge-error-triage.md](forge-error-triage.md) | `npm run forge:errors`: which 3D generation failures actually recur, ranked by class and lane over a real window. |
+| [cron-auth.md](cron-auth.md) | The two locks on `/api/cron/*`: the handler gate, the edge gate, and the header trap that makes attaching Cloud Scheduler OIDC take the whole fleet down if done naively. |
| [payment-outcomes.md](payment-outcomes.md) | The payment-outcome board (`GET /api/ops/payment-outcomes`): verify-reject, settle-fail, replay, and sponsor-runway signals and how to read them in an incident. |
| [agent-index.md](agent-index.md) | The agent index crawls end to end: the cursor stall both chain legs share, the error-class table, the recovery script, and how the freshness sensor scores each leg. |
| [solana-rpc-lanes.md](solana-rpc-lanes.md) | The Solana RPC tier end to end: one-sweep diagnosis, per-lane method capability, what must rotate vs fail, config traps, recovery. |
diff --git a/docs/ops/cron-auth.md b/docs/ops/cron-auth.md
new file mode 100644
index 000000000..b9bfc12d7
--- /dev/null
+++ b/docs/ops/cron-auth.md
@@ -0,0 +1,121 @@
+# Cron authentication: the two locks on `/api/cron/*`
+
+The Cloud Scheduler jobs declared in `vercel.json` (its `crons` array is the
+source of truth for how many) drive handlers that move real money: custody attestation, buybacks, treasury top-ups, payouts, wallet
+intents, the dead-man switch. Anything that can invoke those can spend from
+them, so the gate is layered and both layers fail closed.
+
+## Lock 1: the handler gate (`api/_lib/cron-auth.js`)
+
+Every file under `api/cron/` opens with `if (!requireCron(req, res)) return;`.
+That helper is the only place the credential is compared:
+
+- `CRON_SECRET` unset is a `503 not_configured`, never a pass. A misconfigured
+ deploy must not expose a money-moving sweep.
+- The comparison is constant time, so the secret has no timing oracle.
+- `Authorization: Bearer <secret>` and `X-Cron-Secret: <secret>` are both
+ accepted, and both carry the same secret. The second spelling is not
+ historical clutter: it is what makes lock 2 attachable at all (see below).
+- An inbound header like `x-vercel-cron` is never authorization on its own.
+
+`tests/api/cron-auth-sweep.test.js` invokes every handler in the directory with
+no credential on every test run and requires a closed status from each, plus
+each of the `[name].js` dispatcher's routes individually. The sweep is
+behavioral, not a grep, so a guard that exists but is never called still fails
+it. It also runs against four deliberately broken fixtures (no guard, a verdict
+computed and discarded, a 200 above the guard, a handler that hangs) and must
+reject all four, so a sweep that quietly degraded into a no-op cannot pass.
+
+## Lock 2: the edge gate (`server/cron-edge-auth.mjs`)
+
+Lock 1 is a convention, not a mechanism. The server's filesystem phase routes
+every `api/cron/*.js` file by its existence, so one future handler that forgets
+the line is directly internet-invokable. The edge gate makes that omission
+survivable: mounted ahead of the route table in `server/index.mjs`, it refuses
+the request before any handler is imported.
+
+It accepts two credentials, permanently. This is defense in depth, not a
+migration with a cutover:
+
+1. **`CRON_SECRET`**, via `isCronAuthorized()` from the same module lock 1 uses,
+ so the edge and the handler can never disagree about what a valid secret is.
+2. **A Cloud Scheduler OIDC identity token**: Google-signed, short-lived, bound
+ to one audience, and unusable from a leaked env dump.
+
+Both halves of the OIDC identity are required, and the email is the load-bearing
+one: any Google service account can mint an ID token for an arbitrary audience,
+so an audience match alone authenticates nobody. The token must carry
+`email_verified: true`, an email in `CRON_OIDC_SERVICE_ACCOUNT`, and an audience
+in `CRON_OIDC_AUDIENCE`. With either var unset the OIDC path is off and only the
+secret is accepted.
+
+| Var | Value in production | Effect |
+|---|---|---|
+| `CRON_OIDC_AUDIENCE` | the Cloud Run service URL | audiences the edge will accept, comma-separated |
+| `CRON_OIDC_SERVICE_ACCOUNT` | `[email protected]` | service-account emails the edge will accept, comma-separated |
+
+The one case where the edge stands aside is "no credential configured at all"
+(no `CRON_SECRET`, no OIDC pair), which is a developer's machine: the request
+falls through so `requireCron` owns the single canonical 503. Production always
+has `CRON_SECRET`, so production is always closed here. A fault inside the gate
+itself is a 401, not a pass.
+
+Covered by `tests/server-cron-edge-auth.test.js`, which verifies real RS256
+signatures against a locally generated key set: a forged token, a wrong
+audience, a wrong issuer, a wrong service account, an unverified email, and an
+expired token are each refused, and a genuine one is accepted.
+
+## Attaching the OIDC token (the fleet-wide step)
+
+**The trap:** Cloud Scheduler puts its OIDC token in the `Authorization` header.
+The jobs today authenticate with `Authorization: Bearer $CRON_SECRET`, so naively
+adding `--oidc-service-account-email` DESTROYS the credential every job runs
+on, and they 401 together. The secret must move to `X-Cron-Secret` in the same
+update. `node scripts/create-gcp-scheduler.mjs --oidc` does exactly that, and
+`tests/cron-scheduler-sync.test.js` pins the pairing so the two can never be
+emitted apart.
+
+Order matters. Attach the token first and require it second, never the reverse:
+
+```sh
+# 1. Teach the service which identity to trust (merge, never --set-env-vars).
+gcloud run services update three-ws-api \
+ --region us-central1 --project aerial-vehicle-466722-p5 \
+ --update-env-vars \
+CRON_OIDC_AUDIENCE=https://three-ws-api-lp642k3kpa-uc.a.run.app,\
+CRON_OIDC_SERVICE_ACCOUNT=three-ws@aerial-vehicle-466722-p5.iam.gserviceaccount.com
+
+# 2. Migrate ONE job and prove it before touching the fleet.
+node scripts/create-gcp-scheduler.mjs --oidc --only uptime-check
+gcloud scheduler jobs run cron--api-cron-uptime-check \
+ --location us-central1 --project aerial-vehicle-466722-p5
+gcloud scheduler jobs describe cron--api-cron-uptime-check \
+ --location us-central1 --project aerial-vehicle-466722-p5 \
+ --format='value(status.code,lastAttemptTime,state)' # empty code = success
+
+# 3. Migrate the rest.
+node scripts/create-gcp-scheduler.mjs --oidc
+
+# 4. Confirm nothing is failing, over a window that covers the slowest cron.
+gcloud logging read \
+ 'resource.type="cloud_run_revision"
+ resource.labels.service_name="three-ws-api"
+ httpRequest.requestUrl:"/api/cron/"
+ httpRequest.status=401' \
+ --project aerial-vehicle-466722-p5 --freshness=2h --limit=20
+```
+
+The sync reads `CRON_SECRET` from `--env-file`, then `process.env`, then the
+live Cloud Run service, so on an authenticated machine step 2 needs no argument.
+
+**Rollback** is one command and needs nothing else: `node
+scripts/create-gcp-scheduler.mjs` (no `--oidc`) puts the Bearer secret back on
+every job. The edge keeps accepting it, because it never stopped.
+
+## Related
+
+- `api/_lib/cron-auth.js`, `server/cron-edge-auth.mjs`,
+ `scripts/create-gcp-scheduler.mjs`
+- [gcp-production.md](gcp-production.md) for the service, env, and deploy story
+- `npm run check:cron-drift` (declared vs live jobs) and
+ `npm run audit:cron-liveness` (jobs that exist but never fire)
diff --git a/tests/agent-index.test.js b/tests/agent-index.test.js
index caa663809..0247d1776 100644
--- a/tests/agent-index.test.js
+++ b/tests/agent-index.test.js
@@ -16,6 +16,8 @@ import {
WRAPPED_SOL_MINT,
SOLANA_SWEEP_BATCH,
SOLANA_SWEEP_PERIOD_MIN,
+ SOLANA_SWEEP_CONCURRENCY,
+ drainWithBudget,
} from '../api/_lib/solana-agent-events.js';
import {
normalizeEvent,
@@ -30,6 +32,7 @@ import {
indexLagVerdict,
SOLANA_ERROR_RATE_DEGRADED,
SOLANA_ERROR_RATE_DOWN,
+ SOLANA_LAG_DEGRADED_MIN,
} from '../api/_lib/ops/index-lag.js';
import {
nextChunkSize,
@@ -432,6 +435,20 @@ describe('isPrunedHistoryRejection', () => {
expect(isPrunedHistoryRejection('missing trie node 0xabc (path )')).toBe(true);
});
+ it('reads a paywalled archive range as the same retention wall', () => {
+ // Verbatim from the lane that held the busiest secondary chain 17,396,220
+ // blocks behind head. A keyless node that serves the last few thousand
+ // blocks and charges for anything older has drawn exactly the wall a
+ // pruning node draws: no window down to the 100-block floor gets past it,
+ // so the shrink loop spun on it for months.
+ expect(
+ isPrunedHistoryRejection(
+ 'RPC -32602: Archive requests require a personal token. Get one at: https://www.allnodes.com/publicnode',
+ ),
+ ).toBe(true);
+ expect(isPrunedHistoryRejection('this method requires an archive node')).toBe(true);
+ });
+
it('does NOT claim a range rejection or a plan limit is pruned history', () => {
// These have their own recovery (shrink the window). Reading them as
// pruned would skip the cursor to the head and silently drop real blocks.
@@ -448,6 +465,7 @@ describe('isPrunedHistoryRejection', () => {
'block range is too wide (maximum 1024)',
'query returned more than 10000 results',
'missing trie node',
+ 'RPC -32602: Archive requests require a personal token',
]) {
expect(isPrunedHistoryRejection(msg) && isRangeRejection(msg)).toBe(false);
}
@@ -492,11 +510,109 @@ describe('sweepCycleMin', () => {
expect(sweepCycleMin(1576) / 2).toBeLessThan(90);
});
+ it('finishes a full cycle inside the fresh threshold, not just the median', () => {
+ // The median passing is not enough. The oldest agent in the queue waits a
+ // WHOLE cycle, so a cycle longer than the fresh threshold means part of the
+ // directory is always stale by the sensor's own definition. Measured on
+ // 2026-09-02: 1,604 agents at 120 per tick cycled in 140 minutes against a
+ // 90-minute threshold, and the batch, not the cron's budget, was the cap.
+ expect(sweepCycleMin(1604)).toBeLessThanOrEqual(SOLANA_LAG_DEGRADED_MIN);
+ });
+
+ it('leaves the directory room to grow before the batch has to move again', () => {
+ // Headroom is the point: a batch sized exactly to today's directory goes
+ // stale the week it grows. This is the size at which someone must revisit.
+ expect(sweepCycleMin(2000)).toBeLessThanOrEqual(SOLANA_LAG_DEGRADED_MIN);
+ });
+
it('is null when nothing is queued', () => {
expect(sweepCycleMin(0)).toBe(null);
});
});
+describe('drainWithBudget', () => {
+ // A hand-cranked clock, not a timer: the budget cases have to be exact, and
+ // a real clock would make them race on a loaded machine.
+ const clockFrom = (ticks) => {
+ let i = 0;
+ return () => ticks[Math.min(i++, ticks.length - 1)];
+ };
+
+ it('runs every item once, in order, when the budget is not the constraint', async () => {
+ const seen = [];
+ const run = await drainWithBudget([1, 2, 3, 4, 5], async (n) => void seen.push(n), { concurrency: 1 });
+ expect(seen).toEqual([1, 2, 3, 4, 5]);
+ expect(run.processed).toBe(5);
+ expect(run.truncated).toBe(false);
+ });
+
+ it('overlaps work across the pool instead of serialising it', async () => {
+ let inFlight = 0;
+ let peak = 0;
+ const run = await drainWithBudget(
+ Array.from({ length: 12 }, (_, i) => i),
+ async () => {
+ inFlight += 1;
+ peak = Math.max(peak, inFlight);
+ await Promise.resolve();
+ await Promise.resolve();
+ inFlight -= 1;
+ },
+ { concurrency: 4 },
+ );
+ expect(peak).toBe(4);
+ expect(run.workers).toBe(4);
+ expect(run.processed).toBe(12);
+ });
+
+ it('never opens more workers than there is work for them to do', async () => {
+ const run = await drainWithBudget([1, 2], async () => {}, { concurrency: 8 });
+ expect(run.workers).toBe(2);
+ expect(run.processed).toBe(2);
+ });
+
+ it('stops on the budget and says the rest is still queued', async () => {
+ // Clock: start at 0, then jump past the budget on the second check.
+ const seen = [];
+ const run = await drainWithBudget([1, 2, 3, 4], async (n) => void seen.push(n), {
+ concurrency: 1,
+ budgetMs: 100,
+ now: clockFrom([0, 0, 500]),
+ });
+ expect(seen).toEqual([1]);
+ expect(run.truncated).toBe(true);
+ expect(run.processed).toBe(1);
+ });
+
+ it('reports a run that consumed its last item on the deadline as complete', async () => {
+ // The queue is read before the clock precisely so this is not truncated:
+ // a tick that finished everything has no remainder to report, and calling
+ // it truncated would tell the sweep to shrink a batch that was fine.
+ const run = await drainWithBudget([1, 2], async () => {}, {
+ concurrency: 1,
+ budgetMs: 100,
+ now: clockFrom([0, 0, 50, 9999]),
+ });
+ expect(run.processed).toBe(2);
+ expect(run.truncated).toBe(false);
+ });
+
+ it('does nothing, and claims nothing, for an empty queue', async () => {
+ const run = await drainWithBudget([], async () => {
+ throw new Error('an empty queue must not reach the handler');
+ });
+ expect(run.processed).toBe(0);
+ expect(run.truncated).toBe(false);
+ });
+
+ it('keeps the shipped concurrency low enough not to outrun the RPC lanes', () => {
+ // The lane router parks a cooling provider; a wide fan-out earns 429s
+ // faster than it earns signatures. This is a ceiling, not a target.
+ expect(SOLANA_SWEEP_CONCURRENCY).toBeGreaterThan(1);
+ expect(SOLANA_SWEEP_CONCURRENCY).toBeLessThanOrEqual(8);
+ });
+});
+
// ─── Directory detail fallback ───────────────────────────────────────────────
// /discover lists external Solana agents from the crawled registry directory
// and links every one to /discover/a/sol/<asset>, which is also where the
@@ -693,6 +809,8 @@ function lagFixture({ solana = {}, evm = {} } = {}) {
worstBlocksBehind: 0,
worstChainId: null,
worstChainName: null,
+ historyGapChains: 0,
+ historyGapBlocks: 0,
events: 107296,
...evm,
},
@@ -747,6 +865,24 @@ describe('indexLagVerdict', () => {
expect(clear.status).toBe('ok');
});
+ it('names a permanent history gap that skipping the retention wall left behind', () => {
+ // Skipping is what MAKES the chain report zero backlog again, so without
+ // this line the 17M blocks the crawl gave up on vanish from every surface
+ // the moment the recovery works.
+ const verdict = indexLagVerdict(
+ lagFixture({ evm: { historyGapChains: 2, historyGapBlocks: 19_881_607 } }),
+ );
+ expect(verdict.detail).toContain('2 carrying a permanent 19,881,607-block history gap');
+ });
+
+ it('does not let a history gap alone score the index unhealthy', () => {
+ // The gap is history that is already lost. Scoring it would pin the
+ // subsystem red forever over something no tick can ever fix.
+ expect(
+ indexLagVerdict(lagFixture({ evm: { historyGapChains: 3, historyGapBlocks: 25_000_000 } })).status,
+ ).toBe('ok');
+ });
+
it('reports a never-crawled index as warming up rather than broken', () => {
const verdict = indexLagVerdict(lagFixture({ solana: { agents: 0 }, evm: { chains: 0 } }));
expect(verdict.status).toBe('unknown');