Skip to content

Commit ceb3665

Browse files
committed
fix(scheduler): separate allocator observations
1 parent 08d2c10 commit ceb3665

9 files changed

Lines changed: 289 additions & 26 deletions

File tree

‎dashboard/adaptive-hot-review.ts‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
type AdaptiveHotDecisionRecord,
1818
type AdaptiveHotExecutionObservation,
1919
type AdaptiveHotActualAllocation,
20+
type AdaptiveHotPlannerLane,
2021
type AdaptiveHotPlannerObservation,
2122
type AdaptiveHotRepositoryObservationSnapshot,
2223
} from "../src/repair/adaptive-hot-review-contract.ts";
@@ -267,6 +268,42 @@ export class AdaptiveHotReviewStore {
267268
}
268269

269270
snapshot(now = Date.now()): AdaptiveHotControlSnapshot {
271+
return this.buildSnapshot({
272+
now,
273+
policyVersion: null,
274+
lane: null,
275+
targetRepositories: null,
276+
observationLimit: ADAPTIVE_HOT_PUBLIC_OBSERVATION_LIMIT,
277+
});
278+
}
279+
280+
allocatorSnapshot(
281+
options: {
282+
policyVersion: string;
283+
lane: AdaptiveHotPlannerLane;
284+
targetRepositories: readonly string[];
285+
},
286+
now = Date.now(),
287+
): AdaptiveHotControlSnapshot {
288+
return this.buildSnapshot({
289+
now,
290+
policyVersion: options.policyVersion,
291+
lane: options.lane,
292+
targetRepositories: new Set(
293+
options.targetRepositories.map((repository) => repository.toLowerCase()),
294+
),
295+
observationLimit: ADAPTIVE_HOT_PLANNER_RETENTION_MAX,
296+
});
297+
}
298+
299+
private buildSnapshot(options: {
300+
now: number;
301+
policyVersion: string | null;
302+
lane: AdaptiveHotPlannerLane | null;
303+
targetRepositories: ReadonlySet<string> | null;
304+
observationLimit: number;
305+
}): AdaptiveHotControlSnapshot {
306+
const { now } = options;
270307
this.storage.transactionSync(() => this.pruneSync(now));
271308
const plannerTotals = new Map<string, Record<string, number>>();
272309
for (const row of this.storage.sql.exec(
@@ -335,13 +372,21 @@ export class AdaptiveHotReviewStore {
335372
ORDER BY observed_at DESC, observation_id DESC
336373
) AS rank
337374
FROM ${ADAPTIVE_HOT_PLANNER_OBSERVATION_TABLE}
375+
WHERE (? IS NULL OR policy_version = ?)
376+
AND (? IS NULL OR lane = ?)
338377
) WHERE rank = 1
339378
ORDER BY observed_at DESC, observation_id DESC, target_repo, lane, policy_version
340379
LIMIT ?`,
341-
ADAPTIVE_HOT_PUBLIC_OBSERVATION_LIMIT,
380+
options.policyVersion,
381+
options.policyVersion,
382+
options.lane,
383+
options.lane,
384+
options.observationLimit,
342385
)) {
343386
const latest = normalizeAdaptiveHotPlannerObservationJson(String(row.observation_json || ""));
344387
if (!latest) continue;
388+
if (options.targetRepositories && !options.targetRepositories.has(latest.targetRepo))
389+
continue;
345390
const planner =
346391
plannerTotals.get(
347392
repoLanePolicyKey(latest.targetRepo, latest.lane, latest.policyVersion),
@@ -402,7 +447,8 @@ export class AdaptiveHotReviewStore {
402447
const decision = normalizeAdaptiveHotDecisionJson(String(row.decision_json || ""));
403448
if (decision) recentDecisions.push(decision);
404449
}
405-
const readinessPolicyVersion = recentDecisions[0]?.policyVersion ?? null;
450+
const readinessPolicyVersion =
451+
options.policyVersion ?? recentDecisions[0]?.policyVersion ?? null;
406452
return {
407453
schemaVersion: ADAPTIVE_HOT_CONTROL_SNAPSHOT_SCHEMA_VERSION,
408454
generatedAt: new Date(now).toISOString(),

‎dashboard/exact-review-queue.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { stableJson } from "../src/stable-json.ts";
2+
import { isAdaptiveHotRepositorySlug } from "../src/repair/adaptive-hot-review-contract.ts";
23
import {
34
normalizeStateWriterOperation,
45
normalizeStateWriterProgress,
@@ -90,6 +91,7 @@ const RECENT_DURABLE_PUBLICATION_EVENTS_CACHE_MS = 60_000;
9091

9192
const GITHUB_TIMEOUT_MS = 4500;
9293
const CLAWSWEEPER_REVIEW_REPO = "openclaw/clawsweeper";
94+
const ADAPTIVE_HOT_ALLOCATOR_TARGET_MAX = 20_000;
9395

9496
const FAILED_REVIEW_SHARD_RECOVERY_SOURCE_ACTION = "failed_review_shard_recovery";
9597
const EXACT_REVIEW_ARTIFACT_PUBLISH_SOURCE_ACTION = "exact_review_artifact_publish";
@@ -744,6 +746,36 @@ export class ExactReviewQueue {
744746
);
745747
return result.ok ? json(result, 202) : json({ error: result.error }, 400);
746748
}
749+
if (request.method === "POST" && url.pathname === "/adaptive-hot-review/control-plane") {
750+
const body = objectValue(await request.json().catch(() => null));
751+
const policyVersion = String(body.policyVersion || "").trim();
752+
const lane = String(body.lane || "");
753+
const targetRepositories = Array.isArray(body.targetRepositories)
754+
? body.targetRepositories.map((repository) => String(repository).trim().toLowerCase())
755+
: [];
756+
if (
757+
!policyVersion ||
758+
policyVersion.length > 100 ||
759+
[...policyVersion].some((character) => {
760+
const point = character.codePointAt(0) ?? 0;
761+
return point <= 31 || point === 127;
762+
}) ||
763+
lane !== "hot_intake" ||
764+
targetRepositories.length > ADAPTIVE_HOT_ALLOCATOR_TARGET_MAX ||
765+
new Set(targetRepositories).size !== targetRepositories.length ||
766+
targetRepositories.some((repository) => !isAdaptiveHotRepositorySlug(repository))
767+
) {
768+
return json({ error: "invalid_adaptive_hot_control_plane_request" }, 400);
769+
}
770+
return json({
771+
ok: true,
772+
adaptive_hot_review: this.adaptiveHotReviewStore.allocatorSnapshot({
773+
policyVersion,
774+
lane,
775+
targetRepositories,
776+
}),
777+
});
778+
}
747779
if (request.method === "POST" && url.pathname === "/adaptive-hot-review/decision") {
748780
const result = this.adaptiveHotReviewStore.recordDecision(
749781
await request.json().catch(() => null),

‎dashboard/worker.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,12 @@ export default {
566566
return authenticatedExactReviewQueueRequest(request, env, "/review-coverage/inventory");
567567
if (url.pathname === "/internal/adaptive-hot-review/observation" && request.method === "POST")
568568
return authenticatedExactReviewQueueRequest(request, env, "/adaptive-hot-review/observation");
569+
if (url.pathname === "/internal/adaptive-hot-review/control-plane" && request.method === "POST")
570+
return authenticatedExactReviewQueueRequest(
571+
request,
572+
env,
573+
"/adaptive-hot-review/control-plane",
574+
);
569575
if (url.pathname === "/internal/adaptive-hot-review/decision" && request.method === "POST")
570576
return authenticatedExactReviewQueueRequest(request, env, "/adaptive-hot-review/decision");
571577
if (

‎docs/adaptive-hot-review.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,15 @@ round-by-round reasons, offer reduction, an observation-based dedupe/shed
102102
avoidance estimate, and fairness age before and after the bounded proposal.
103103
Those estimates are diagnostic comparisons, not admission inputs.
104104

105+
The 100-partition public projection is display-only. Adaptive fanout signs its
106+
current policy version, hot lane, and eligible repository inventory to
107+
`POST /internal/adaptive-hot-review/control-plane`; the Durable Object returns
108+
the matching retained observations through that authenticated boundary. The
109+
allocator therefore does not lose fleet observations when normal-lane, older
110+
policy, or other public partitions fill the dashboard cap. An unavailable or
111+
invalid private view follows the same shadow fail-open and active-mode
112+
fail-closed rules as the rest of the control plane.
113+
105114
## Modes and controls
106115

107116
The target-fanout job reads these repository variables:

‎docs/proof/adaptive-hot-review/run-proof.mjs‎

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@ try {
4444

4545
await signedRequest("/internal/adaptive-hot-review/observation", "POST", observation, 202);
4646
await signedRequest("/internal/adaptive-hot-review/observation", "POST", observation, 202);
47+
const allocatorSnapshot = await signedJson(
48+
"/internal/adaptive-hot-review/control-plane",
49+
"POST",
50+
{
51+
policyVersion: "adaptive-hot-v1",
52+
lane: "hot_intake",
53+
targetRepositories: ["example/alpha"],
54+
},
55+
200,
56+
);
57+
assert.equal(allocatorSnapshot.adaptive_hot_review.observations.length, 1);
58+
assert.equal(allocatorSnapshot.adaptive_hot_review.observations[0].targetRepo, "example/alpha");
4759

4860
const planned = decisionRecord({ observedAt, status: "planned" });
4961
const dispatched = decisionRecord({ observedAt, status: "dispatched" });
@@ -64,16 +76,12 @@ try {
6476
202,
6577
);
6678
assert.equal(reserved.reservation_id, reservationId);
67-
const blockedDirectWrite = await fetchSigned(
68-
"/internal/state/cursors/hot-intake",
69-
"PUT",
70-
{ next_cursor: 99, expected_revision: 0 },
71-
);
79+
const blockedDirectWrite = await fetchSigned("/internal/state/cursors/hot-intake", "PUT", {
80+
next_cursor: 99,
81+
expected_revision: 0,
82+
});
7283
assert.equal(blockedDirectWrite.status, 409);
73-
assert.equal(
74-
(await blockedDirectWrite.json()).error,
75-
"adaptive_hot_cursor_reservation_active",
76-
);
84+
assert.equal((await blockedDirectWrite.json()).error, "adaptive_hot_cursor_reservation_active");
7785
await assertCursors(cursorUpdates, 0, 0);
7886

7987
await stopWorker(worker);
@@ -186,7 +194,10 @@ try {
186194
assert.equal(recoveredSummary.adaptive_cursor_persisted, true);
187195
assert.equal(recoveredSummary.adaptive_probe_cursor_persisted, true);
188196
const commandCursors = await readCursors(cursorUpdates);
189-
assert.equal(commandCursors.every((cursor) => cursor.revision === 2), true);
197+
assert.equal(
198+
commandCursors.every((cursor) => cursor.revision === 2),
199+
true,
200+
);
190201

191202
const shadowCommitFault = await runTargetFanoutCommand({
192203
ghPath: ghProof.path,
@@ -298,6 +309,8 @@ try {
298309
durable_object: "persisted SQLite ExactReviewQueue",
299310
restarts: 2,
300311
invalid_signature_status: unsigned.status,
312+
authenticated_allocator_observations:
313+
allocatorSnapshot.adaptive_hot_review.observations.length,
301314
loopback_tls_proxy: true,
302315
},
303316
telemetry: {
@@ -369,6 +382,7 @@ try {
369382
"",
370383
`- Exact head: ${actualHead}.`,
371384
`- Auth boundary: unsigned observation returned HTTP ${unsigned.status}.`,
385+
"- Allocator boundary: a signed current-policy hot-lane view returned the eligible repository independently of the bounded public projection.",
372386
"- Telemetry: duplicate observation and decision receipts collapsed to one durable record each across a restart.",
373387
"- Cursor fencing: reservation left all three cursors at revision 0 until the post-restart commit.",
374388
`- Direct-write fencing: a covered cursor write during the reservation returned HTTP ${blockedDirectWrite.status}.`,
@@ -389,15 +403,22 @@ try {
389403

390404
console.log(`exact head: ${actualHead}`);
391405
console.log(`auth boundary: HTTP ${unsigned.status}`);
406+
console.log("allocator view: signed current-policy hot lane returned 1 observation");
392407
console.log("telemetry persistence: 1 observation, 1 dispatched decision after restart");
393408
console.log("cursor fencing: unchanged before commit; 3 cursors advanced atomically");
394409
console.log("commit retry after second restart: identical durable receipt");
395410
console.log(`committed reservation identity reuse: HTTP ${reusedReservation.status}`);
396411
console.log(`direct write during reservation: HTTP ${blockedDirectWrite.status}`);
397412
console.log("dispatch failure recovery: aborted unchanged; replacement reservation acquired");
398-
console.log("actual target-fanout: injected zero-dispatch failure aborted; recovery dispatched 2 and committed");
399-
console.log("shadow commit failure: legacy cursor advanced; next cycle selected the next repository");
400-
console.log("kill switch rollback: malformed inactive controls bypassed; legacy dispatch persisted");
413+
console.log(
414+
"actual target-fanout: injected zero-dispatch failure aborted; recovery dispatched 2 and committed",
415+
);
416+
console.log(
417+
"shadow commit failure: legacy cursor advanced; next cycle selected the next repository",
418+
);
419+
console.log(
420+
"kill switch rollback: malformed inactive controls bypassed; legacy dispatch persisted",
421+
);
401422
console.log("public snapshot: bounded and sanitized");
402423
console.log("RESULT: PASS");
403424
} finally {
@@ -549,7 +570,12 @@ async function publicSnapshot() {
549570
return response.json();
550571
}
551572

552-
function assertAdaptiveSnapshot(snapshot, observationCount, decisionCount, latestStatus = "dispatched") {
573+
function assertAdaptiveSnapshot(
574+
snapshot,
575+
observationCount,
576+
decisionCount,
577+
latestStatus = "dispatched",
578+
) {
553579
assert.equal(snapshot.adaptive_hot_review.observations.length, observationCount);
554580
assert.equal(snapshot.adaptive_hot_review.observations[0].targetRepo, "example/alpha");
555581
assert.equal(snapshot.adaptive_hot_review.recentDecisions.length, decisionCount);

‎src/repair/adaptive-hot-control-plane.ts‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,55 @@ export type AdaptiveHotControlPlaneResult =
2020

2121
export async function fetchAdaptiveHotControlPlane(options: {
2222
queueUrl: string;
23+
webhookSecret: string;
24+
policyVersion: string;
25+
targetRepositories: readonly string[];
2326
fetchImpl?: typeof fetch;
2427
timeoutMs?: number;
2528
}): Promise<AdaptiveHotControlPlaneResult> {
2629
const request = options.fetchImpl ?? fetch;
2730
const controller = new AbortController();
2831
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 10_000);
2932
try {
30-
const response = await request(
31-
new URL("/api/exact-review-queue", `${options.queueUrl.replace(/\/+$/, "")}/`),
32-
{ signal: controller.signal },
33-
);
33+
const baseUrl = options.queueUrl.replace(/\/+$/, "");
34+
if (!baseUrl.startsWith("https://")) {
35+
return { ok: false, reason: "adaptive hot-review URL must use HTTPS" };
36+
}
37+
if (!options.webhookSecret) {
38+
return { ok: false, reason: "adaptive hot-review webhook secret is required" };
39+
}
40+
const allocatorRequestBody = JSON.stringify({
41+
policyVersion: options.policyVersion,
42+
lane: "hot_intake",
43+
targetRepositories: options.targetRepositories,
44+
});
45+
const signature = `sha256=${createHmac("sha256", options.webhookSecret)
46+
.update(allocatorRequestBody)
47+
.digest("hex")}`;
48+
const [response, allocatorResponse] = await Promise.all([
49+
request(new URL("/api/exact-review-queue", `${baseUrl}/`), {
50+
signal: controller.signal,
51+
}),
52+
request(new URL("/internal/adaptive-hot-review/control-plane", `${baseUrl}/`), {
53+
method: "POST",
54+
headers: {
55+
"content-type": "application/json",
56+
"x-clawsweeper-exact-review-signature": signature,
57+
},
58+
body: allocatorRequestBody,
59+
signal: controller.signal,
60+
}),
61+
]);
3462
if (!response.ok) return { ok: false, reason: `http_${response.status}` };
63+
if (!allocatorResponse.ok) {
64+
return { ok: false, reason: `allocator_http_${allocatorResponse.status}` };
65+
}
3566
const body = record(await response.json(), "exact-review queue status");
36-
const snapshot = adaptiveHotControlSnapshot(body.adaptive_hot_review);
67+
const allocatorBody = record(
68+
await allocatorResponse.json(),
69+
"adaptive hot-review allocator status",
70+
);
71+
const snapshot = adaptiveHotControlSnapshot(allocatorBody.adaptive_hot_review);
3772
const review = record(record(body.lanes, "lanes").review, "lanes.review");
3873
const publication = record(record(body.lanes, "lanes").publication, "lanes.publication");
3974
const scheduledFeed = record(body.scheduled_feed, "scheduled_feed");

‎src/repair/target-fanout.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,12 @@ export async function runTargetFanout(argv: string[]): Promise<void> {
299299
) {
300300
throw new Error("adaptive hot-review cursors must be durable before active dispatch");
301301
}
302-
const control = await fetchAdaptiveHotControlPlane({ queueUrl: options.cursorStoreUrl });
302+
const control = await fetchAdaptiveHotControlPlane({
303+
queueUrl: options.cursorStoreUrl,
304+
webhookSecret: process.env.CLAWSWEEPER_WEBHOOK_SECRET ?? "",
305+
policyVersion: adaptive.policy.allocation.policyVersion,
306+
targetRepositories: planningRepositories.map((repository) => repository.targetRepo),
307+
});
303308
if (!control.ok && adaptive.runtime.effectiveMode !== "shadow") {
304309
throw new Error(`adaptive hot-review control plane unavailable: ${control.reason}`);
305310
}

0 commit comments

Comments
 (0)