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
24 changes: 24 additions & 0 deletions apps/server/src/orchestration-v2/ModelAlertReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,30 @@ it("deduplicates a stranded queue until the queue advances or drains", () => {
assert.isTrue(step("queued:3", true, 11));
});

it("an open-PR lane-ended report dropped undelivered can report again on the next run end", () => {
const judged = {
threadId: "thread:fleet",
evaluated: ["lane-ended"] as const,
findings: [finding("lane-ended", "open-prs:github.com/o/r#7")],
};
const first = recordThreadEvents(EMPTY_MODEL_ALERT_STATE, judged, eventAlert, ["watcher"], 0);
assert.isTrue(first.enqueued);
// A later run with the same open pull requests shares the report while it is queued.
assert.isFalse(recordThreadEvents(first.state, judged, eventAlert, ["watcher"], 1).enqueued);
const [queued] = first.state.outbox;
assert.isDefined(queued);
const dropped = afterDrop(first.state, queued, 2);
assert.deepEqual(dropped.outbox, []);
assert.isTrue(recordThreadEvents(dropped, judged, eventAlert, ["watcher"], 3).enqueued);
// A run-keyed report keeps its dedupe after a drop: that run will not end again.
const failedRun = { ...judged, findings: [finding("lane-ended", "run:1")] };
const failed = recordThreadEvents(EMPTY_MODEL_ALERT_STATE, failedRun, eventAlert, ["watcher"], 0);
const afterFailedDrop = afterDrop(failed.state, failed.state.outbox[0]!, 1);
assert.isFalse(
recordThreadEvents(afterFailedDrop, failedRun, eventAlert, ["watcher"], 2).enqueued,
);
});

it("a thread holding a question and an inbox flip reports each once, not on every trigger", () => {
const both = [finding("needs-person", "request:1"), finding("needs-person", "inbox:kameron")];
let state = EMPTY_MODEL_ALERT_STATE;
Expand Down
81 changes: 77 additions & 4 deletions apps/server/src/orchestration-v2/ModelAlertReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { runModelSignals, workerAlert } from "@t3tools/provider-core/server/suba
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Option from "effect/Option";
Expand All @@ -42,6 +43,11 @@ import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as PeerMcpClient from "../peer/PeerMcpClient.ts";
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import {
normalizeThreadPullRequestKey,
threadPullRequestKeyOf,
} from "../sourceControl/threadPullRequests.ts";
import { forkParked } from "../serverActivation.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as Orchestrator from "./Orchestrator.ts";
Expand All @@ -55,18 +61,21 @@ import {
withCursor,
} from "./eventSubscription.ts";
import {
isOpenPrLaneEndedSignature,
isStrandedQueueSignature,
judgeThread,
keepStrandedQueueReport,
type StrandedQueue,
threadEventAlert,
launchingThreadId,
openPullRequestLinks,
ThreadEventAlert,
type ThreadEventKind,
threadEventMessage,
REJUDGE_TRIGGER,
threadEventStillHolds,
type ThreadEventTrigger,
withPullRequestStates,
type ThreadFinding,
} from "./ThreadEventAlerts.ts";
import {
Expand Down Expand Up @@ -369,6 +378,32 @@ function setReported(
};
}

function openPrLaneEndedSignature(alert: WatcherAlert): string | undefined {
if (alert.type !== "thread-event" || alert.kind !== "lane-ended") return undefined;
const prefix = `${alert.environmentId}:${alert.threadId}:${alert.kind}:`;
const suffix = `:${alert.occurredAt}`;
if (!alert.id.startsWith(prefix) || !alert.id.endsWith(suffix)) return undefined;
const signature = alert.id.slice(prefix.length, -suffix.length);
return isOpenPrLaneEndedSignature(signature) ? signature : undefined;
}

/**
* An open-PR lane-ended report is shared by every run with the same open pull requests, so one
* dropped undelivered must be forgotten, or the next run that ends that way stays silent too.
*/
function forgetDroppedOpenPrReport(reported: ModelAlertState["reported"], entry: Delivery) {
const signature = openPrLaneEndedSignature(entry.alert);
if (signature === undefined || entry.alert.type !== "thread-event") return reported;
const key = reportedKey(entry.alert.threadId, "lane-ended");
const known = (reported[key] ?? "").split("\n").filter(Boolean);
if (!known.includes(signature)) return reported;
return setReported(
reported,
key,
known.filter((candidate) => candidate !== signature),
);
}

function recordStrandedDelivery(
reported: ModelAlertState["reported"],
entry: Delivery,
Expand Down Expand Up @@ -632,7 +667,7 @@ export const afterDrop = (
(candidate) => candidate.alert.id === entry.alert.id && !sameDelivery(candidate, entry),
)
? state.reported
: recordStrandedDelivery(state.reported, entry, false),
: forgetDroppedOpenPrReport(recordStrandedDelivery(state.reported, entry, false), entry),
outbox: state.outbox.flatMap((candidate) => {
if (!sameDelivery(candidate, entry)) return [candidate];
if (
Expand Down Expand Up @@ -1016,6 +1051,7 @@ export const make = Effect.gen(function* () {
const subscriptionStore = yield* Effect.serviceOption(
EventSubscriptionStore.EventSubscriptionStore,
);
const pullRequestService = yield* Effect.serviceOption(PullRequestService.PullRequestService);
let eventWakeSeq = 0;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const settings = yield* ServerSettings.ServerSettingsService;
Expand Down Expand Up @@ -1144,10 +1180,15 @@ export const make = Effect.gen(function* () {
alert.type === "model-degraded"
? { providerInstanceId: alert.providerInstanceId, newerRunSupersedes: false }
: undefined;
if (!(yield* stillCurrent(alert.threadId, alert.runId, about))) return null;
// An open-PR report covers later runs too, so a newer run does not supersede it; the
// re-judge below still drops it once the run is live, failed, or the open set changed.
const runId = openPrLaneEndedSignature(alert) === undefined ? alert.runId : null;
if (!(yield* stillCurrent(alert.threadId, runId, about))) return null;
if (alert.type === "thread-event") {
const shell = yield* projections.getThreadShell(ThreadId.make(alert.threadId));
if (shell === null) return null;
const stored = yield* projections.getThreadShell(ThreadId.make(alert.threadId));
if (stored === null) return null;
const shell =
openPrLaneEndedSignature(alert) === undefined ? stored : yield* withHostPrStates(stored);
const holds = threadEventStillHolds({
hasStalenessWait: yield* hasActiveStalenessWait(shell, REJUDGE_TRIGGER[alert.kind]),
alert,
Expand All @@ -1160,6 +1201,38 @@ export const make = Effect.gen(function* () {
return alert;
});

/**
* The stored snapshot can predate a merge or close by a sync interval, so an open-PR alert
* rereads its open links from the host. A failed read keeps the stored state.
*/
const withHostPrStates = Effect.fnUntraced(function* (shell: OrchestrationV2ThreadShell) {
if (Option.isNone(pullRequestService)) return shell;
const service = pullRequestService.value;
const read = yield* Effect.forEach(
openPullRequestLinks(shell),
(link) =>
service
.summary(
{
projectId: shell.projectId,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
},
{ bypassCache: true, recoverTransientFailure: false },
)
.pipe(
Effect.map((summary) => [[threadPullRequestKeyOf(link), summary.state] as const]),
Effect.catchCauseIf(
(cause) => !Cause.hasInterruptsOnly(cause),
() => Effect.succeed([]),
),
),
{ concurrency: 4 },
);
return withPullRequestStates(shell, new Map(read.flat()));
});

/** What the shell does not carry: open delegated tasks elsewhere, and children's last activity. */
const hasActiveStalenessWait = Effect.fnUntraced(function* (
shell: OrchestrationV2ThreadShell,
Expand Down
22 changes: 18 additions & 4 deletions apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1456,7 +1456,7 @@ describe("PullRequestSyncReactor", () => {
}),
);

it.effect("reads a settled thread's links once when it settles, then until unsettled", () =>
it.effect("refreshes open links on settled threads on the slow cadence until terminal", () =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
Expand All @@ -1468,14 +1468,19 @@ describe("PullRequestSyncReactor", () => {
makeLink(5, { state: "open" }),
makeLink(6, { state: "closed" }),
makeLink(7),
makeLink(8, { state: "merged", mergedAt: "2026-08-20T00:00:00.000Z" }),
],
}),
]),
});

yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
// Open (#5) and unsynced (#7) links on settled thread are swept; closed (#6) and merged (#8) are not.
assert.deepStrictEqual(
(yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(),
[5, 7],
);

const threadId = ThreadId.make("settled");
const at = DateTime.makeUnsafe(NOW);
Expand Down Expand Up @@ -1515,9 +1520,17 @@ describe("PullRequestSyncReactor", () => {
(yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(),
[5, 6],
);
for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
// Before SLOW_SYNC_INTERVAL_MS (15m), open link #5 is not re-swept.
for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);

// At 15m, open (#5) and unsynced (#7) links are refreshed on the slow cadence; closed (#6) and merged (#8) stay quiet.
yield* sweepAgain(fixture, reactor);
assert.deepStrictEqual(
(yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(),
[5, 7],
);

yield* Ref.update(fixture.snapshots, (snapshot) => ({
...snapshot,
threads: snapshot.threads.map((thread) => ({
Expand All @@ -1527,9 +1540,10 @@ describe("PullRequestSyncReactor", () => {
})),
}));
yield* sweepAgain(fixture, reactor);
// After unsettling, #6 (closed, 15m since last read) and #7 (unsynced) are due; #5 was just refreshed 1m ago and is in quiet cooldown.
assert.deepStrictEqual(
(yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
[5, 6, 7],
[6, 7],
);
}).pipe(Effect.provide(fixture.layer));
}),
Expand Down
14 changes: 11 additions & 3 deletions apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,10 +380,18 @@ export const make = Effect.gen(function* () {
const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
if ((failedReads.get(key)?.retryAtMs ?? 0) > nowMs) return false;
if (requested.has(key)) return true;
const active = entries.filter((entry) => isUnsettled(entry.thread));
if (active.length === 0) return false;
const last = lastSyncedAt.get(key);
const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last;
const active = entries.filter((entry) => isUnsettled(entry.thread));
if (active.length === 0) {
// Settled threads still refresh open/unsynced pull requests on the slow cadence so PRs
// merged or closed after settlement reach a terminal snapshot instead of staying "open".
const hasOpenSettled = entries.some(
(entry) => entry.link.snapshot === null || entry.link.snapshot.state === "open",
);
if (!hasOpenSettled) return false;
return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
}
if (missing.has(key)) return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
if (retryStacks.has(key) || active.some((entry) => entry.link.snapshot === null)) return true;
// Merged snapshots without mergedAt cannot settle threads; reread slowly until supplied.
Expand Down Expand Up @@ -873,7 +881,7 @@ export const make = Effect.gen(function* () {
// Every reaction skips a running command, so only an ended one forks.
return active ? Effect.void : inThreadOrder(event.threadId, reaction);
}
// Settled threads are not swept, so read their links once to settle with fresh status.
// Settling reads the links at once rather than waiting for the slow settled cadence.
case "thread.settled":
return inThreadOrder(event.threadId, refreshUnmergedLinks(event.threadId));
case "run.updated":
Expand Down
53 changes: 53 additions & 0 deletions apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
threadEventStillHolds,
type ThreadEventTrigger,
type WatchedShell,
withPullRequestStates,
} from "./ThreadEventAlerts.ts";
import { threadPullRequestKeyOf } from "../sourceControl/threadPullRequests.ts";

const NOW = Date.parse("2026-11-19T05:00:00.000Z");
const at = (minutesAgo: number) => DateTime.makeUnsafe(NOW - minutesAgo * 60_000);
Expand Down Expand Up @@ -130,6 +132,45 @@ it("lane-ended stays quiet for a failure the model alert already reported as a u
assert.deepEqual(findings, []);
});

it("lane-ended with open pull requests dedupes by open-PR set across runs, and clears on settle", () => {
const run1 = judge(
shellWith({
status: "completed",
latestRunId: "run:1",
pullRequests: [openPullRequest],
} as never),
"run-ended",
);
const run2 = judge(
shellWith({
status: "completed",
latestRunId: "run:2",
pullRequests: [openPullRequest],
} as never),
"run-ended",
);
const finding1 = run1.findings.find((finding) => finding.kind === "lane-ended");
const finding2 = run2.findings.find((finding) => finding.kind === "lane-ended");
assert.ok(finding1 && finding2);
assert.strictEqual(finding1.signature, finding2.signature);
assert.ok(finding1.signature.startsWith("open-prs:"));

const settled = judge(
shellWith({
status: "completed",
latestRunId: "run:2",
settledOverride: "settled",
pullRequests: [openPullRequest],
} as never),
"settled",
);
assert.ok(settled.evaluated.includes("lane-ended"));
assert.deepEqual(
settled.findings.filter((finding) => finding.kind === "lane-ended"),
[],
);
});

it.each([
{ settledOverride: "settled" },
{ archivedAt: at(1) },
Expand Down Expand Up @@ -395,6 +436,18 @@ const asking = {
} as never;
const promised = { status: "idle", latestVisibleMessage: assistantSays(FLEET_PROMISE) } as never;

it("an open-PR lane-ended alert stops holding once a host reread finds its pull request merged", () => {
const alert = fired(openWithPr, "run-ended");
const stored = shellWith(openWithPr);
const key = threadPullRequestKeyOf(openPullRequest);
const reread = (state: "open" | "merged") =>
withPullRequestStates(stored, new Map([[key, state]]));
assert.isTrue(threadEventStillHolds({ alert, shell: reread("open"), stuckMinutes: 20 }));
assert.isFalse(threadEventStillHolds({ alert, shell: reread("merged"), stuckMinutes: 20 }));
// A newer run that ended the same way keeps the open-PR report, so it is not superseded.
assert.isTrue(stillHolds(alert, { latestRunId: "run:8" } as never, openWithPr));
});

it.each([
["lane-ended, nothing changed", failed, "run-ended", {}, true],
["lane-ended, the lane restarted itself", failed, "run-ended", quietRun, false],
Expand Down
Loading
Loading