Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 35 additions & 19 deletions scw_js/llm_x402_cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ interface NetworkResult {
escrowHeld?: string;
/** Channels that should have been refunded by now and were not — see assertSweptClean. */
stuckChannels?: string[];
/** Post-condition escrow read failed (transient S3 stall) — shown, not paged; next run re-verifies. */
checkError?: string;
error?: string;
}

Expand Down Expand Up @@ -377,24 +379,37 @@ export async function handle(
logger.error({ err, network, asset }, "Refund sweep failed");
}

// The sweep's post-condition, checked against storage as it now stands. Runs even when the
// refund step threw: a failed sweep is exactly when escrow is most likely left behind.
const remaining = await scheme.getStorage().list();
// `balance` is cumulative DEPOSITS — claims do not decrement it, they move funds out via
// `totalClaimed` (the SDK validates a voucher's cumulative maxClaimable against `balance`,
// so it has to keep growing). Summing `balance` alone therefore reports money that has
// already been collected as still at risk, in the field printed next to the stuck-escrow
// error. Clamped at zero so a record caught mid-drift reads as nothing held rather than a
// negative total.
const escrowHeld = remaining.reduce((sum, c) => {
const held = BigInt(c.balance) - BigInt(c.totalClaimed);
return sum + (held > 0n ? held : 0n);
}, 0n);
const stuckChannels = findStuckChannels(remaining);
if (stuckChannels.length > 0) {
logger.error(
{ network, asset, stuckChannels, escrowHeld: escrowHeld.toString() },
"Channels are past the refund threshold and still hold escrow — the sweep did not do its job",
// The sweep's post-condition. Only the read can fail here; a stalled S3 list must not
// land in the outer catch as "claimAndSettle failed" (2026-11-23) — warn + checkError
// on the row, the audit re-verifies next run. Warn, and phrased to match no alert
// filter (pinned in test/alert_coverage.test.ts).
let checkError: string | undefined;
let escrowHeld: bigint | undefined;
let stuckChannels: string[] = [];
try {
// `balance` is cumulative DEPOSITS — claims do not decrement it, they move funds out via
// `totalClaimed` (the SDK validates a voucher's cumulative maxClaimable against `balance`,
// so it has to keep growing). Summing `balance` alone therefore reports money that has
// already been collected as still at risk, in the field printed next to the stuck-escrow
// error. Clamped at zero so a record caught mid-drift reads as nothing held rather than a
// negative total.
const remaining = await scheme.getStorage().list();
escrowHeld = remaining.reduce((sum, c) => {
const held = BigInt(c.balance) - BigInt(c.totalClaimed);
return sum + (held > 0n ? held : 0n);
}, 0n);
stuckChannels = findStuckChannels(remaining);
if (stuckChannels.length > 0) {
logger.error(
{ network, asset, stuckChannels, escrowHeld: escrowHeld.toString() },
"Channels are past the refund threshold and still hold escrow — the sweep did not do its job",
);
}
} catch (err) {
checkError = (err as Error).message;
logger.warn(
{ err, network, asset },
"Post-sweep escrow check could not run — S3 list timed out",
);
}

Expand All @@ -409,7 +424,8 @@ export async function handle(
...(garbageCollected !== undefined && { garbageCollected }),
...(anomalousChannels !== undefined && { anomalousChannels }),
...(claimsLeft !== null && { feeAllowanceClaimsLeft: claimsLeft }),
escrowHeld: escrowHeld.toString(),
...(escrowHeld !== undefined && { escrowHeld: escrowHeld.toString() }),
...(checkError !== undefined && { checkError }),
...(stuckChannels.length > 0 && { stuckChannels }),
});
} catch (err) {
Expand Down
8 changes: 8 additions & 0 deletions scw_js/test/alert_coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ describe("scw_js alert coverage", () => {
}
});

// payments.yaml filters have no level gate, so this logger.warn's phrase must match none
// of them. If it starts matching, it was reworded into collision or promoted to
// logger.error — then give it an alert phrase or an EXEMPT entry, deliberately.
it("the post-condition warn phrase pages nobody", () => {
const phrase = "Post-sweep escrow check could not run — S3 list timed out";
expect(isCovered(scwJsRules, phrase)).toBe(false);
});

for (const { file, message } of messages) {
it(`"${message}" (${file}) is alertable`, () => {
if (message in EXEMPT) {
Expand Down
53 changes: 53 additions & 0 deletions scw_js/test/llm_x402_cron.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,59 @@ describe("llm_x402_cron", () => {
expect(res.statusCode).toBe(500);
});

// ═══════════════════════════════════════════════════════════
// The post-condition read itself failing (2026-11-23): warn + checkError, no page —
// while the sweep-failure signal is preserved.
// ═══════════════════════════════════════════════════════════

it("reports a failed post-condition read as checkError without failing the run", async () => {
// list() runs three times per pair: partition (1), refund mock (2), post-condition (3).
let calls = 0;
mockStorageList.mockImplementation(async () => {
calls += 1;
if (calls === 3) {
throw new DOMException("The operation was aborted due to timeout", "TimeoutError");
}
return [];
});

const res = await handle(makeEvent() as never, {});

expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body) as { results: Array<Record<string, unknown>> };
expect(body.results).toHaveLength(RUNS.length);
const first = body.results[0];
expect(first.checkError).toContain("aborted due to timeout");
expect(first.claims).toBe(1);
expect(first.error).toBeUndefined();
expect(first.escrowHeld).toBeUndefined();
expect(first.stuckChannels).toBeUndefined();
// Only this pair lost its audit; later pairs listed fine.
expect(body.results.slice(1).every((r) => r.checkError === undefined)).toBe(true);
});

it("keeps the sweep-failure page when the post-condition read also fails", async () => {
mockRefundIdleChannels.mockRejectedValue(new Error("batch reverted"));
// With the refund batch throwing, list() runs partition (1), then the read (2).
let calls = 0;
mockStorageList.mockImplementation(async () => {
calls += 1;
if (calls === 2) {
throw new DOMException("The operation was aborted due to timeout", "TimeoutError");
}
return [];
});

const res = await handle(makeEvent() as never, {});

expect(res.statusCode).toBe(500);
const body = JSON.parse(res.body) as { results: Array<Record<string, unknown>> };
const first = body.results[0];
expect(first.refundError).toContain("batch reverted");
expect(first.checkError).toContain("aborted due to timeout");
expect(first.error).toBeUndefined();
});

// ═══════════════════════════════════════════════════════════
// The sweep's pre-pass: refundable / fully-claimed (garbage-collected) / anomalous.
// The 2026-10-11 incident: a fully-claimed record with balance != 0 poisoned the batch
Expand Down