Skip to content

Commit 4769a48

Browse files
authored
fix(core): settle bursts of watched status changes into one wake (#66332)
1 parent d97b226 commit 4769a48

2 files changed

Lines changed: 206 additions & 18 deletions

File tree

‎packages/core/src/plugin/provider/opencode-watches.ts‎

Lines changed: 98 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ export const ACK_LIMIT = 1000
2727
const POLL_WAIT = 25
2828
/** How long the client polls before it tries the WebSocket again. */
2929
const POLL_RETRY_WEBSOCKET = Duration.minutes(10)
30+
/**
31+
* How long a session's status changes wait for another before they wake it, and the longest the first one waits. A
32+
* merge's checks, its merge and the runs it starts arrive seconds apart, often while the agent checks them itself.
33+
*/
34+
export const SETTLE = Duration.seconds(15)
35+
export const MAX_SETTLE = Duration.seconds(30)
3036
/** Wakes in 10 minutes, and since the user's last prompt, before updates wait for a person, so agents can't loop. */
3137
export const WINDOW_LIMIT = 5
3238
export const PROMPT_LIMIT = 20
@@ -511,6 +517,11 @@ function stream(hub: Hub) {
511517
const reader = yield* socket.reader.pipe(Effect.option)
512518
if (Option.isNone(reader)) return "refused" as const
513519
const writer = yield* socket.writer
520+
const handle = yield* settle(hub, (ids) =>
521+
Effect.forEach(chunks(ids), (chunk) => writer.write(JSON.stringify({ type: "ack", ids: chunk })), {
522+
discard: true,
523+
}),
524+
)
514525
return yield* reader.value.pull.pipe(
515526
Effect.timeoutOrElse({
516527
duration: SILENCE,
@@ -524,10 +535,7 @@ function stream(hub: Hub) {
524535
const message = decodeServerMessage(typeof frame === "string" ? frame : decoder.decode(frame))
525536
if (Option.isNone(message))
526537
return yield* Effect.logWarning("ignored an event stream message this version can't read")
527-
const ids = yield* (yield* leader(hub)).deliver(message.value.events)
528-
yield* Effect.forEach(chunks(ids), (chunk) => writer.write(JSON.stringify({ type: "ack", ids: chunk })), {
529-
discard: true,
530-
})
538+
yield* handle(message.value.events)
531539
}),
532540
{ discard: true },
533541
),
@@ -553,6 +561,18 @@ function stream(hub: Hub) {
553561
function poll(hub: Hub) {
554562
return Effect.gen(function* () {
555563
const started = yield* Clock.currentTimeMillis
564+
const handle = yield* settle(hub, (ids) =>
565+
Effect.forEach(
566+
chunks(ids),
567+
(chunk) =>
568+
leader(hub).pipe(
569+
Effect.flatMap((member) => call(member, "POST", "/api/event-watches/ack", { ids: chunk })),
570+
Effect.flatMap(HttpClientResponse.filterStatusOk),
571+
Effect.scoped,
572+
),
573+
{ discard: true },
574+
),
575+
)
556576
let cursor: string | undefined
557577
let polled = false
558578
while (true) {
@@ -569,20 +589,81 @@ function poll(hub: Hub) {
569589
)
570590
if (Option.isNone(page)) return polled ? ("polled" as const) : ("failed" as const)
571591
polled = true
572-
const ids = yield* member.deliver(page.value.events)
573-
const acked = yield* Effect.forEach(chunks(ids), (chunk) =>
574-
call(member, "POST", "/api/event-watches/ack", { ids: chunk }).pipe(
575-
Effect.flatMap(HttpClientResponse.filterStatusOk),
576-
Effect.scoped,
577-
),
578-
).pipe(Effect.option)
592+
const acked = yield* handle(page.value.events).pipe(Effect.option)
579593
if (Option.isNone(acked)) return "polled" as const
580594
// A full page means more is waiting: the next poll after its cursor answers at once.
581595
cursor = page.value.cursor
582596
}
583-
})
597+
}).pipe(Effect.scoped)
598+
}
599+
600+
/** A session's status changes waiting to wake it: since when, the latest's arrival, and the fiber that sends them. */
601+
interface Held {
602+
readonly events: WatchEvent[]
603+
readonly first: number
604+
last: number
605+
fiber?: Fiber.Fiber<void>
584606
}
585607

608+
/**
609+
* Delivers each session's events through the connection's leader, then acknowledges them with `ack`. A session's
610+
* status changes wait until `SETTLE` passes without another, at most `MAX_SETTLE`, so a burst of them wakes it once.
611+
* Anything someone wrote goes at once, with whatever was waiting. Events still waiting when the connection's scope
612+
* closes stay unacknowledged, so the next connection gets them again.
613+
*/
614+
const settle = Effect.fnUntraced(function* (
615+
hub: Hub,
616+
ack: (ids: ReadonlyArray<string>) => Effect.Effect<unknown, unknown>,
617+
) {
618+
const scope = yield* Scope.Scope
619+
const waiting = new Map<string, Held>()
620+
const send = (events: ReadonlyArray<WatchEvent>) =>
621+
leader(hub).pipe(
622+
Effect.flatMap((member) => member.deliver(events)),
623+
Effect.flatMap(ack),
624+
)
625+
const wait = (sessionID: string, held: Held) =>
626+
Effect.gen(function* () {
627+
while (true) {
628+
const now = yield* Clock.currentTimeMillis
629+
const due = Math.min(held.last + Duration.toMillis(SETTLE), held.first + Duration.toMillis(MAX_SETTLE))
630+
if (now >= due) break
631+
yield* Effect.sleep(Duration.millis(due - now))
632+
}
633+
// Once taken, the events are delivered and acknowledged even if the connection closes meanwhile.
634+
yield* Effect.uninterruptible(
635+
Effect.suspend(() => {
636+
waiting.delete(sessionID)
637+
return send(held.events)
638+
}),
639+
)
640+
}).pipe(Effect.catch((cause) => Effect.logWarning("failed to deliver settled watch events", { sessionID, cause })))
641+
return Effect.fnUntraced(function* (events: ReadonlyArray<WatchEvent>) {
642+
const now = yield* Clock.currentTimeMillis
643+
const ready = yield* Effect.forEach(Map.groupBy(events, (event) => event.sessionID), ([sessionID, batch]) =>
644+
Effect.gen(function* () {
645+
const held = waiting.get(sessionID)
646+
if (batch.every(settles)) {
647+
if (held) {
648+
held.events.push(...batch)
649+
held.last = now
650+
return []
651+
}
652+
const fresh: Held = { events: [...batch], first: now, last: now }
653+
waiting.set(sessionID, fresh)
654+
fresh.fiber = yield* wait(sessionID, fresh).pipe(Effect.forkIn(scope, { startImmediately: true }))
655+
return []
656+
}
657+
if (!held) return batch
658+
waiting.delete(sessionID)
659+
if (held.fiber) yield* Fiber.interrupt(held.fiber)
660+
return [...held.events, ...batch]
661+
}),
662+
)
663+
yield* send(ready.flat())
664+
})
665+
})
666+
586667
function chunks(ids: ReadonlyArray<string>) {
587668
return Array.from({ length: Math.ceil(ids.length / ACK_LIMIT) }, (_, index) =>
588669
ids.slice(index * ACK_LIMIT, (index + 1) * ACK_LIMIT),
@@ -742,6 +823,11 @@ const actions = new Map<string, (target: string) => string>([
742823
["review", (target) => `reviewed ${target}`],
743824
])
744825

826+
/** A status change, which waits for the others that follow it; not something someone wrote or a server's own event. */
827+
function settles(event: WatchEvent) {
828+
return !actions.has(event.kind) && event.kind !== "event" && event.kind !== "channel_post"
829+
}
830+
745831
/**
746832
* The member's own words read as theirs, so a reply from their phone steers the agent. Anyone else's, and anything a
747833
* bot wrote, are information for the task, never a source of new actions. So is a new message in a channel the session

‎packages/core/test/plugin/provider-opencode-watches.test.ts‎

Lines changed: 108 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,33 @@ const deliver = Effect.fnUntraced(function* (console: ReturnType<typeof fakeCons
249249
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes(event.id)))
250250
})
251251

252+
/**
253+
* Pushes status changes and waits until the client holds them. Frames are read in order, so once a marker pushed after
254+
* them is acknowledged, their wait has begun. The marker's session is marked deleted, so it acknowledges without a wake.
255+
*/
256+
const hold = Effect.fnUntraced(function* (
257+
console: ReturnType<typeof fakeConsole>,
258+
host: PluginContext.Context,
259+
...events: WatchEvent[]
260+
) {
261+
const marker = `evt_marker_${crypto.randomUUID()}`
262+
yield* host.storage.set("watch-deleted:ses_marker", 0)
263+
console.push(...events)
264+
console.push(watchEvent("ses_marker", marker))
265+
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes(marker)))
266+
})
267+
268+
/** Pushes status changes, lets them settle, and waits until the plugin acknowledges them. */
269+
const settle = Effect.fnUntraced(function* (
270+
console: ReturnType<typeof fakeConsole>,
271+
host: PluginContext.Context,
272+
...events: WatchEvent[]
273+
) {
274+
yield* hold(console, host, ...events)
275+
yield* TestClock.adjust(OpencodeWatches.SETTLE)
276+
yield* waitUntil(Effect.sync(() => events.every((event) => console.state.acks.flat().includes(event.id))))
277+
})
278+
252279
const watchTools = Effect.gen(function* () {
253280
const tools = yield* Tool.Service
254281
return (yield* tools.list()).filter((tool) => tool.options?.namespace === "console_watch").map((tool) => tool.name)
@@ -339,7 +366,9 @@ describe("OpencodePlugin event watches", () => {
339366
const own = yield* host.session.create({})
340367
const ci = yield* host.session.create({})
341368
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
342-
console.push(
369+
yield* settle(
370+
console,
371+
host,
343372
watchEvent(own.id, "evt_own", {
344373
source: "slack",
345374
kind: "message",
@@ -351,7 +380,6 @@ describe("OpencodePlugin event watches", () => {
351380
}),
352381
watchEvent(ci.id, "evt_ci", { kind: "workflow_run", status: "failure", body: "Run tests: exit 1" }),
353382
)
354-
yield* waitUntil(Effect.sync(() => console.state.acks.flat().length === 2))
355383

356384
const text = (sessionID: Session.ID) => wakes.find((wake) => wake.sessionID === sessionID)?.text ?? ""
357385
expect(text(own.id)).toContain(
@@ -651,8 +679,9 @@ describe("OpencodePlugin event watches", () => {
651679
yield* (yield* watchTool("watch")).execute({ target: "acme/app#1", unattended: true }, context(session.id))
652680
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
653681
for (const index of [1, 2, 3, 4, 5, 6])
654-
yield* deliver(
682+
yield* settle(
655683
console,
684+
host,
656685
watchEvent(session.id, `evt_${index}`, { watchID: "ew_new", kind: "workflow_run", status: "success" }),
657686
)
658687
expect(wakes.map((wake) => wake.resume)).toEqual([true, true, true, true, true, false])
@@ -694,7 +723,7 @@ describe("OpencodePlugin event watches", () => {
694723
const session = yield* host.session.create({})
695724
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
696725
for (const index of [1, 2, 3, 4, 5, 6])
697-
yield* deliver(console, watchEvent(session.id, `evt_${index}`, { kind: "workflow_run", status: "success" }))
726+
yield* settle(console, host, watchEvent(session.id, `evt_${index}`, { kind: "workflow_run", status: "success" }))
698727
yield* deliver(
699728
console,
700729
watchEvent(session.id, "evt_reply", { source: "slack", kind: "message", status: null }),
@@ -711,7 +740,7 @@ describe("OpencodePlugin event watches", () => {
711740
const session = yield* host.session.create({})
712741
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
713742
for (const index of Array.from({ length: 21 }, (_, index) => index))
714-
yield* deliver(console, watchEvent(session.id, `evt_${index}`, { kind: "workflow_job", status: "failure" }))
743+
yield* settle(console, host, watchEvent(session.id, `evt_${index}`, { kind: "workflow_job", status: "failure" }))
715744
expect(wakes.map((wake) => wake.resume)).toEqual([...Array.from({ length: 20 }, () => true), false])
716745
}),
717746
),
@@ -730,13 +759,86 @@ describe("OpencodePlugin event watches", () => {
730759
)
731760
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes(`evt_review_${index}`)))
732761
}
733-
yield* deliver(console, watchEvent(session.id, "evt_ci_6", { kind: "workflow_run", status: "success" }))
762+
yield* settle(console, host, watchEvent(session.id, "evt_ci_6", { kind: "workflow_run", status: "success" }))
734763
yield* deliver(console, watchEvent(session.id, "evt_review_6"))
735764
expect(wakes.map((wake) => wake.resume)).toEqual([true, true, true, true, true, true, false])
736765
}),
737766
),
738767
)
739768

769+
it.effect("wakes once for status changes seconds apart, once 15 seconds pass without another or 30 at most", () =>
770+
withConsole({}, (console) =>
771+
Effect.gen(function* () {
772+
const { host, wakes } = yield* start(console)
773+
const session = yield* host.session.create({})
774+
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
775+
const status = (id: string, kind: string, status: string) => watchEvent(session.id, id, { kind, status })
776+
yield* hold(console, host, status("evt_checks", "check", "all 1 passed"))
777+
yield* TestClock.adjust("10 seconds")
778+
yield* hold(console, host, status("evt_merged", "state", "merged"))
779+
yield* TestClock.adjust("14 seconds")
780+
expect(wakes).toEqual([])
781+
yield* TestClock.adjust("1 second")
782+
yield* waitUntil(Effect.sync(() => wakes.length === 1))
783+
expect(wakes[0]?.metadata?.events).toEqual(["evt_checks", "evt_merged"])
784+
expect(wakes[0]?.text).toStartWith("2 updates arrived")
785+
expect(wakes[0]?.text).not.toContain("Looks good")
786+
787+
// Each arrives before the last has been quiet for 15 seconds, so the cap sends them 30 seconds after the first.
788+
for (const index of [1, 2, 3]) {
789+
yield* hold(console, host, status(`evt_slow_${index}`, "workflow_run", "success"))
790+
yield* TestClock.adjust("10 seconds")
791+
}
792+
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes("evt_slow_3")))
793+
expect(wakes[1]?.metadata?.events).toEqual(["evt_slow_1", "evt_slow_2", "evt_slow_3"])
794+
expect(console.state.acks.flat().filter((id) => !id.startsWith("evt_marker"))).toEqual([
795+
"evt_checks",
796+
"evt_merged",
797+
"evt_slow_1",
798+
"evt_slow_2",
799+
"evt_slow_3",
800+
])
801+
}),
802+
),
803+
)
804+
805+
it.effect("wakes at once for something someone wrote, with the status changes still settling", () =>
806+
withConsole({}, (console) =>
807+
Effect.gen(function* () {
808+
const { host, wakes } = yield* start(console)
809+
const session = yield* host.session.create({})
810+
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
811+
yield* hold(console, host, watchEvent(session.id, "evt_ci", { kind: "workflow_run", status: "failure" }))
812+
yield* deliver(console, watchEvent(session.id, "evt_review"))
813+
expect(wakes.map((wake) => wake.metadata?.events)).toEqual([["evt_ci", "evt_review"]])
814+
815+
// The wait it was in is over: the clock moving on wakes nothing more.
816+
yield* TestClock.adjust(OpencodeWatches.MAX_SETTLE)
817+
yield* Effect.promise(() => Bun.sleep(50))
818+
expect(wakes).toHaveLength(1)
819+
}),
820+
),
821+
)
822+
823+
it.effect("leaves status changes still settling unacknowledged when the socket closes, and settles them again", () =>
824+
withConsole({}, (console) =>
825+
Effect.gen(function* () {
826+
const { host, wakes } = yield* start(console)
827+
const session = yield* host.session.create({})
828+
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
829+
yield* hold(console, host, watchEvent(session.id, "evt_ci", { kind: "workflow_run", status: "success" }))
830+
console.state.sockets.forEach((socket) => socket.close(OpencodeWatches.LEASE_CLOSE_CODE, "lease"))
831+
yield* waitUntil(Effect.sync(() => console.state.opens === 2))
832+
expect(console.state.acks.flat()).not.toContain("evt_ci")
833+
834+
// The next connection's snapshot sends it again, and it waits there anew.
835+
yield* settle(console, host)
836+
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes("evt_ci")))
837+
expect(wakes.map((wake) => wake.metadata?.events)).toEqual([["evt_ci"]])
838+
}),
839+
),
840+
)
841+
740842
it.effect("resumes a held session with a later wake once 10 minutes pass", () =>
741843
withConsole({}, (console) =>
742844
Effect.gen(function* () {

0 commit comments

Comments
 (0)