Skip to content

Commit 7dea6f3

Browse files
committed
fix(recovery): rotate placeholder discovery cursors
1 parent d3810a0 commit 7dea6f3

11 files changed

Lines changed: 694 additions & 169 deletions

‎.github/workflows/exact-review-reconcile.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ jobs:
233233
GH_TOKEN: ${{ github.token }}
234234
TARGET_WRITE_TOKEN: ${{ steps.target-write-token.outputs.token }}
235235
QUEUE_URL: ${{ vars.CLAWSWEEPER_EXACT_REVIEW_QUEUE_URL || 'https://clawsweeper.openclaw.ai' }}
236+
REVIEW_PLACEHOLDER_CURSOR_STORE_URL: ${{ vars.CLAWSWEEPER_EXACT_REVIEW_QUEUE_URL || 'https://clawsweeper.openclaw.ai' }}
236237
REVIEW_PLACEHOLDER_LOOKBACK_HOURS: ${{ vars.REVIEW_PLACEHOLDER_LOOKBACK_HOURS || '48' }}
237238
REVIEW_PLACEHOLDER_MAX_CHECKS: ${{ vars.REVIEW_PLACEHOLDER_MAX_CHECKS || '20' }}
238239
REVIEW_PLACEHOLDER_MAX_RECOVERIES: ${{ vars.REVIEW_PLACEHOLDER_MAX_RECOVERIES || '5' }}

‎dashboard/exact-review-queue.ts‎

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -488,10 +488,16 @@ const EXACT_REVIEW_QUEUE_ROLLBACK_CLOCK_SKEW_MS = 5 * 60 * 1000;
488488
const EXACT_REVIEW_QUEUE_LEGACY_GENERATION_PREFIX = "__clawsweeper_sql_generation:";
489489
const EXACT_REVIEW_QUEUE_STATE_KEY = "exact-review-queue";
490490
const EXACT_REVIEW_SOURCE_AUTHORITY_SEQUENCE_KEY = "exact-review-source-authority-sequence:v1";
491-
const TARGET_FANOUT_CURSOR_KEY_PREFIX = "target-fanout-cursor:v1:";
492-
type TargetFanoutMode = "hot-intake" | "normal-review" | "audit";
493-
type TargetFanoutCursor = {
494-
mode: TargetFanoutMode;
491+
// Preserve the original key prefix so existing fanout cursors survive the
492+
// broader operational-cursor contract introduced for bounded recovery lanes.
493+
const OPERATIONAL_CURSOR_KEY_PREFIX = "target-fanout-cursor:v1:";
494+
type OperationalCursorMode =
495+
| "hot-intake"
496+
| "normal-review"
497+
| "audit"
498+
| `review-placeholder-${string}-${"open" | "closed"}`;
499+
type OperationalCursor = {
500+
mode: OperationalCursorMode;
495501
nextCursor: number;
496502
revision: number;
497503
updatedAt: number;
@@ -629,12 +635,15 @@ export class ExactReviewQueue {
629635
this.reviewCoverageCache = null;
630636
return json({ ok: true, accepted: true }, 202);
631637
}
632-
const targetFanoutMode = targetFanoutModeFromPath(url.pathname);
633-
if (targetFanoutMode && request.method === "GET") {
634-
return this.readTargetFanoutCursor(targetFanoutMode);
638+
const operationalCursorMode = operationalCursorModeFromPath(url.pathname);
639+
if (operationalCursorMode && request.method === "GET") {
640+
return this.readOperationalCursor(operationalCursorMode);
635641
}
636-
if (targetFanoutMode && request.method === "PUT") {
637-
return this.writeTargetFanoutCursor(targetFanoutMode, await request.json().catch(() => null));
642+
if (operationalCursorMode && request.method === "PUT") {
643+
return this.writeOperationalCursor(
644+
operationalCursorMode,
645+
await request.json().catch(() => null),
646+
);
638647
}
639648
if (request.method === "GET" && url.pathname === "/recent-durable-publication-events") {
640649
const events = this.recentDurablePublicationEvents(
@@ -3092,13 +3101,13 @@ export class ExactReviewQueue {
30923101
return value;
30933102
}
30943103

3095-
private readTargetFanoutCursor(mode: TargetFanoutMode) {
3096-
const stored = readTargetFanoutCursor(this.storage.kv.get(targetFanoutCursorKey(mode)), mode);
3104+
private readOperationalCursor(mode: OperationalCursorMode) {
3105+
const stored = readOperationalCursor(this.storage.kv.get(operationalCursorKey(mode)), mode);
30973106
if (stored === "invalid") return json({ error: "fanout_cursor_store_invalid" }, 500);
3098-
return json(targetFanoutCursorJson(stored ?? emptyTargetFanoutCursor(mode)));
3107+
return json(operationalCursorJson(stored ?? emptyOperationalCursor(mode)));
30993108
}
31003109

3101-
private writeTargetFanoutCursor(mode: TargetFanoutMode, value: unknown) {
3110+
private writeOperationalCursor(mode: OperationalCursorMode, value: unknown) {
31023111
const body = objectValue(value);
31033112
const nextCursor = Number(body.next_cursor);
31043113
const expectedRevision = Number(body.expected_revision);
@@ -3112,38 +3121,35 @@ export class ExactReviewQueue {
31123121
}
31133122
try {
31143123
const result = this.storage.transactionSync(() => {
3115-
const stored = readTargetFanoutCursor(
3116-
this.storage.kv.get(targetFanoutCursorKey(mode)),
3117-
mode,
3118-
);
3124+
const stored = readOperationalCursor(this.storage.kv.get(operationalCursorKey(mode)), mode);
31193125
if (stored === "invalid") return { kind: "invalid" as const };
3120-
const current = stored ?? emptyTargetFanoutCursor(mode);
3126+
const current = stored ?? emptyOperationalCursor(mode);
31213127
if (current.revision !== expectedRevision) {
31223128
return { kind: "conflict" as const, current };
31233129
}
31243130
if (current.revision >= Number.MAX_SAFE_INTEGER) {
31253131
return { kind: "invalid" as const };
31263132
}
3127-
const next: TargetFanoutCursor = {
3133+
const next: OperationalCursor = {
31283134
mode,
31293135
nextCursor,
31303136
revision: current.revision + 1,
31313137
updatedAt: Date.now(),
31323138
};
3133-
this.storage.kv.put(targetFanoutCursorKey(mode), next);
3139+
this.storage.kv.put(operationalCursorKey(mode), next);
31343140
return { kind: "written" as const, cursor: next };
31353141
});
31363142
if (result.kind === "invalid") return json({ error: "fanout_cursor_store_invalid" }, 500);
31373143
if (result.kind === "conflict") {
31383144
return json(
31393145
{
31403146
error: "fanout_cursor_revision_conflict",
3141-
current: targetFanoutCursorJson(result.current),
3147+
current: operationalCursorJson(result.current),
31423148
},
31433149
409,
31443150
);
31453151
}
3146-
return json(targetFanoutCursorJson(result.cursor), 202);
3152+
return json(operationalCursorJson(result.cursor), 202);
31473153
} catch (error) {
31483154
console.error(`fanout cursor write failed: ${sanitizedServerError(error)}`);
31493155
return json({ error: "fanout_cursor_store_unavailable" }, 503);
@@ -13659,23 +13665,26 @@ function objectValue(value) {
1365913665
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1366013666
}
1366113667

13662-
function targetFanoutModeFromPath(path: string): TargetFanoutMode | null {
13663-
const match = /^\/cursors\/(hot-intake|normal-review|audit)$/.exec(path);
13664-
return (match?.[1] as TargetFanoutMode | undefined) ?? null;
13668+
function operationalCursorModeFromPath(path: string): OperationalCursorMode | null {
13669+
const match =
13670+
/^\/cursors\/(hot-intake|normal-review|audit|review-placeholder-[a-f0-9]{16}-(?:open|closed))$/.exec(
13671+
path,
13672+
);
13673+
return (match?.[1] as OperationalCursorMode | undefined) ?? null;
1366513674
}
1366613675

13667-
function targetFanoutCursorKey(mode: TargetFanoutMode): string {
13668-
return `${TARGET_FANOUT_CURSOR_KEY_PREFIX}${mode}`;
13676+
function operationalCursorKey(mode: OperationalCursorMode): string {
13677+
return `${OPERATIONAL_CURSOR_KEY_PREFIX}${mode}`;
1366913678
}
1367013679

13671-
function emptyTargetFanoutCursor(mode: TargetFanoutMode): TargetFanoutCursor {
13680+
function emptyOperationalCursor(mode: OperationalCursorMode): OperationalCursor {
1367213681
return { mode, nextCursor: 0, revision: 0, updatedAt: 0 };
1367313682
}
1367413683

13675-
function readTargetFanoutCursor(
13684+
function readOperationalCursor(
1367613685
value: unknown,
13677-
mode: TargetFanoutMode,
13678-
): TargetFanoutCursor | "invalid" | null {
13686+
mode: OperationalCursorMode,
13687+
): OperationalCursor | "invalid" | null {
1367913688
if (value === undefined) return null;
1368013689
const cursor = objectValue(value);
1368113690
const nextCursor = Number(cursor.nextCursor);
@@ -13695,7 +13704,7 @@ function readTargetFanoutCursor(
1369513704
return { mode, nextCursor, revision, updatedAt };
1369613705
}
1369713706

13698-
function targetFanoutCursorJson(cursor: TargetFanoutCursor) {
13707+
function operationalCursorJson(cursor: OperationalCursor) {
1369913708
return {
1370013709
ok: true,
1370113710
mode: cursor.mode,

‎dashboard/worker.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -550,10 +550,11 @@ export default {
550550
return authenticatedExactReviewQueueRequest(request, env, "/source-authority");
551551
if (url.pathname === "/internal/review-coverage/inventory" && request.method === "POST")
552552
return authenticatedExactReviewQueueRequest(request, env, "/review-coverage/inventory");
553-
const fanoutCursorPath = /^\/internal\/state\/cursors\/(hot-intake|normal-review|audit)$/.exec(
554-
url.pathname,
555-
);
556-
if (fanoutCursorPath && (request.method === "GET" || request.method === "PUT"))
553+
const operationalCursorPath =
554+
/^\/internal\/state\/cursors\/(hot-intake|normal-review|audit|review-placeholder-[a-f0-9]{16}-(?:open|closed))$/.exec(
555+
url.pathname,
556+
);
557+
if (operationalCursorPath && (request.method === "GET" || request.method === "PUT"))
557558
return authenticatedExactReviewQueueCursorRequest(
558559
request,
559560
env,

‎docs/limits.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -318,9 +318,11 @@ and hot intake `14`. Existing repair lanes keep their
318318
the two most recently updated pages for sponsorship commands, then alternates
319319
newest/oldest created-order scans. Reaction-only revival can lag in very large
320320
archives; raise this override to scan deeper per run.
321-
- `REVIEW_PLACEHOLDER_MAX_CHECKS` overrides the number of open search candidates
322-
examined by each 15-minute orphaned-placeholder recovery pass; the default is
323-
20 and the maximum is 1000.
321+
- `REVIEW_PLACEHOLDER_MAX_CHECKS` overrides the number of search candidates
322+
examined per open and closed state class by each 15-minute
323+
orphaned-placeholder recovery pass; the default is 20 and the maximum is
324+
1000. Independent durable cursors rotate both state classes so non-actionable
325+
matches cannot permanently pin later placeholders behind the bounded pass.
324326
- `REVIEW_PLACEHOLDER_MIN_AGE_HOURS` overrides how old the latest ClawSweeper bot
325327
review-start placeholder must be before recovery; the default is 2 hours and
326328
the maximum is 720 hours.

‎docs/state-storage.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ operational paths that have not migrated yet.
88
| Logical paths | Canonical owner | Git state status |
99
| --- | --- | --- |
1010
| `records/**` | Durable Object record store with R2 snapshots | Never checked out or written |
11-
| fanout cursor per mode | ExactReviewQueue Durable Object KV | Never checked out or written |
11+
| fanout and placeholder-recovery cursors per mode | ExactReviewQueue Durable Object KV | Never checked out or written |
1212
| `ledger/v1/**` | R2 immutable blobs | Never checked out or written |
1313
| `assets/**` | R2 mutable blobs | Never checked out or written |
1414
| `jobs/**` | `clawsweeper-state` `state` branch | Retained until its own migration |
@@ -26,12 +26,12 @@ ordinary fetch/commit/push. The former Git lease refs, atomic multi-ref pushes,
2626
shallow-history deepening, remote-head rebuilds, record reconciliation, and
2727
immutable-ledger scratch branches no longer exist.
2828

29-
Target fanout reads and updates `/internal/state/cursors/<mode>` with the same
30-
HMAC authentication as canonical record operations. Each record carries a
31-
monotonic revision so concurrent writers cannot silently overwrite one another.
32-
Cursor reads and writes are fail-open: an unavailable store emits a prominent
33-
warning, but repository dispatch continues so bookkeeping cannot block fleet
34-
coverage.
29+
Target fanout and bounded placeholder recovery read and update
30+
`/internal/state/cursors/<mode>` with the same HMAC authentication as canonical
31+
record operations. Each record carries a monotonic revision so concurrent
32+
writers cannot silently overwrite one another. Cursor reads and writes are
33+
fail-open: an unavailable store emits a prominent warning, but productive work
34+
continues and remains safe to retry.
3535

3636
Git-backed reports, dashboard status, and post-dispatch cursors are best-effort
3737
after their productive side effect or canonical publication succeeds. Git

‎src/durable-cursor-store.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { createHmac } from "node:crypto";
2+
3+
type JsonRecord = Record<string, unknown>;
4+
5+
export interface DurableCursorSnapshot<Mode extends string = string> {
6+
mode: Mode;
7+
nextCursor: number;
8+
revision: number;
9+
updatedAt: string | null;
10+
}
11+
12+
export type DurableCursorStoreOptions<Mode extends string = string> = {
13+
baseUrl: string;
14+
webhookSecret: string;
15+
mode: Mode;
16+
attempts?: number;
17+
fetchImpl?: typeof globalThis.fetch;
18+
sleep?: (milliseconds: number) => Promise<void>;
19+
};
20+
21+
export async function fetchDurableCursor<Mode extends string>(
22+
options: DurableCursorStoreOptions<Mode>,
23+
): Promise<DurableCursorSnapshot<Mode>> {
24+
const payload = await durableCursorRequest(options, "GET", "");
25+
if (payload.mode !== options.mode) throw new Error("durable cursor response mode mismatch");
26+
return {
27+
mode: options.mode,
28+
nextCursor: nonNegativeNumber(payload.next_cursor, "durable cursor next_cursor"),
29+
revision: nonNegativeNumber(payload.revision, "durable cursor revision"),
30+
updatedAt:
31+
payload.updated_at === null || typeof payload.updated_at === "string"
32+
? payload.updated_at
33+
: null,
34+
};
35+
}
36+
37+
export async function putDurableCursor<Mode extends string>(
38+
options: DurableCursorStoreOptions<Mode>,
39+
nextCursor: number,
40+
expectedRevision: number,
41+
): Promise<DurableCursorSnapshot<Mode>> {
42+
const body = JSON.stringify({
43+
next_cursor: nonNegativeNumber(nextCursor, "durable cursor next_cursor"),
44+
expected_revision: nonNegativeNumber(expectedRevision, "durable cursor expected_revision"),
45+
});
46+
const payload = await durableCursorRequest(options, "PUT", body);
47+
if (payload.mode !== options.mode) throw new Error("durable cursor response mode mismatch");
48+
return {
49+
mode: options.mode,
50+
nextCursor: nonNegativeNumber(payload.next_cursor, "durable cursor next_cursor"),
51+
revision: nonNegativeNumber(payload.revision, "durable cursor revision"),
52+
updatedAt: typeof payload.updated_at === "string" ? payload.updated_at : null,
53+
};
54+
}
55+
56+
async function durableCursorRequest<Mode extends string>(
57+
options: DurableCursorStoreOptions<Mode>,
58+
method: "GET" | "PUT",
59+
body: string,
60+
): Promise<JsonRecord> {
61+
const baseUrl = options.baseUrl.replace(/\/$/, "");
62+
if (!baseUrl.startsWith("https://")) throw new Error("durable cursor store URL must use HTTPS");
63+
if (!options.webhookSecret) throw new Error("durable cursor webhook secret is required");
64+
const signature = `sha256=${createHmac("sha256", options.webhookSecret).update(body).digest("hex")}`;
65+
const attempts = Math.max(1, Math.min(5, Math.floor(options.attempts ?? 3)));
66+
const request = options.fetchImpl ?? globalThis.fetch;
67+
const sleep =
68+
options.sleep ??
69+
((milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
70+
let lastFailure = "durable cursor request failed";
71+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
72+
try {
73+
const init: RequestInit = {
74+
method,
75+
headers: {
76+
"content-type": "application/json",
77+
"x-clawsweeper-exact-review-signature": signature,
78+
},
79+
signal: AbortSignal.timeout(5_000),
80+
};
81+
if (method === "PUT") init.body = body;
82+
const response = await request(
83+
`${baseUrl}/internal/state/cursors/${encodeURIComponent(options.mode)}`,
84+
init,
85+
);
86+
const payload = record(await response.json().catch(() => ({})), "durable cursor response");
87+
if (response.ok && payload.ok === true) return payload;
88+
lastFailure =
89+
typeof payload.error === "string" && payload.error
90+
? payload.error
91+
: `http_${response.status}`;
92+
if (response.status >= 400 && response.status < 500 && response.status !== 429) break;
93+
} catch (error) {
94+
lastFailure = errorMessage(error);
95+
}
96+
if (attempt < attempts) await sleep(attempt * 1_000);
97+
}
98+
throw new Error(`${method} durable cursor failed: ${lastFailure}`);
99+
}
100+
101+
function nonNegativeNumber(value: unknown, label: string): number {
102+
const parsed = Number(value);
103+
if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error(`${label} must be non-negative`);
104+
return parsed;
105+
}
106+
107+
function record(value: unknown, label: string): JsonRecord {
108+
if (!value || typeof value !== "object" || Array.isArray(value)) {
109+
throw new Error(`${label} must be an object`);
110+
}
111+
return value as JsonRecord;
112+
}
113+
114+
function errorMessage(error: unknown): string {
115+
return (error instanceof Error ? error.message : String(error))
116+
.replace(/[\r\n]+/g, " ")
117+
.slice(0, 300);
118+
}

0 commit comments

Comments
 (0)