mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
fix(core): settle bursts of watched status changes into one wake (#66332)
This commit is contained in:
parent
d97b2265ee
commit
4769a48e5d
2 changed files with 206 additions and 18 deletions
|
|
@ -27,6 +27,12 @@ export const ACK_LIMIT = 1000
|
|||
const POLL_WAIT = 25
|
||||
/** How long the client polls before it tries the WebSocket again. */
|
||||
const POLL_RETRY_WEBSOCKET = Duration.minutes(10)
|
||||
/**
|
||||
* How long a session's status changes wait for another before they wake it, and the longest the first one waits. A
|
||||
* merge's checks, its merge and the runs it starts arrive seconds apart, often while the agent checks them itself.
|
||||
*/
|
||||
export const SETTLE = Duration.seconds(15)
|
||||
export const MAX_SETTLE = Duration.seconds(30)
|
||||
/** Wakes in 10 minutes, and since the user's last prompt, before updates wait for a person, so agents can't loop. */
|
||||
export const WINDOW_LIMIT = 5
|
||||
export const PROMPT_LIMIT = 20
|
||||
|
|
@ -511,6 +517,11 @@ function stream(hub: Hub) {
|
|||
const reader = yield* socket.reader.pipe(Effect.option)
|
||||
if (Option.isNone(reader)) return "refused" as const
|
||||
const writer = yield* socket.writer
|
||||
const handle = yield* settle(hub, (ids) =>
|
||||
Effect.forEach(chunks(ids), (chunk) => writer.write(JSON.stringify({ type: "ack", ids: chunk })), {
|
||||
discard: true,
|
||||
}),
|
||||
)
|
||||
return yield* reader.value.pull.pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration: SILENCE,
|
||||
|
|
@ -524,10 +535,7 @@ function stream(hub: Hub) {
|
|||
const message = decodeServerMessage(typeof frame === "string" ? frame : decoder.decode(frame))
|
||||
if (Option.isNone(message))
|
||||
return yield* Effect.logWarning("ignored an event stream message this version can't read")
|
||||
const ids = yield* (yield* leader(hub)).deliver(message.value.events)
|
||||
yield* Effect.forEach(chunks(ids), (chunk) => writer.write(JSON.stringify({ type: "ack", ids: chunk })), {
|
||||
discard: true,
|
||||
})
|
||||
yield* handle(message.value.events)
|
||||
}),
|
||||
{ discard: true },
|
||||
),
|
||||
|
|
@ -553,6 +561,18 @@ function stream(hub: Hub) {
|
|||
function poll(hub: Hub) {
|
||||
return Effect.gen(function* () {
|
||||
const started = yield* Clock.currentTimeMillis
|
||||
const handle = yield* settle(hub, (ids) =>
|
||||
Effect.forEach(
|
||||
chunks(ids),
|
||||
(chunk) =>
|
||||
leader(hub).pipe(
|
||||
Effect.flatMap((member) => call(member, "POST", "/api/event-watches/ack", { ids: chunk })),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.scoped,
|
||||
),
|
||||
{ discard: true },
|
||||
),
|
||||
)
|
||||
let cursor: string | undefined
|
||||
let polled = false
|
||||
while (true) {
|
||||
|
|
@ -569,20 +589,81 @@ function poll(hub: Hub) {
|
|||
)
|
||||
if (Option.isNone(page)) return polled ? ("polled" as const) : ("failed" as const)
|
||||
polled = true
|
||||
const ids = yield* member.deliver(page.value.events)
|
||||
const acked = yield* Effect.forEach(chunks(ids), (chunk) =>
|
||||
call(member, "POST", "/api/event-watches/ack", { ids: chunk }).pipe(
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
Effect.scoped,
|
||||
),
|
||||
).pipe(Effect.option)
|
||||
const acked = yield* handle(page.value.events).pipe(Effect.option)
|
||||
if (Option.isNone(acked)) return "polled" as const
|
||||
// A full page means more is waiting: the next poll after its cursor answers at once.
|
||||
cursor = page.value.cursor
|
||||
}
|
||||
})
|
||||
}).pipe(Effect.scoped)
|
||||
}
|
||||
|
||||
/** A session's status changes waiting to wake it: since when, the latest's arrival, and the fiber that sends them. */
|
||||
interface Held {
|
||||
readonly events: WatchEvent[]
|
||||
readonly first: number
|
||||
last: number
|
||||
fiber?: Fiber.Fiber<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers each session's events through the connection's leader, then acknowledges them with `ack`. A session's
|
||||
* status changes wait until `SETTLE` passes without another, at most `MAX_SETTLE`, so a burst of them wakes it once.
|
||||
* Anything someone wrote goes at once, with whatever was waiting. Events still waiting when the connection's scope
|
||||
* closes stay unacknowledged, so the next connection gets them again.
|
||||
*/
|
||||
const settle = Effect.fnUntraced(function* (
|
||||
hub: Hub,
|
||||
ack: (ids: ReadonlyArray<string>) => Effect.Effect<unknown, unknown>,
|
||||
) {
|
||||
const scope = yield* Scope.Scope
|
||||
const waiting = new Map<string, Held>()
|
||||
const send = (events: ReadonlyArray<WatchEvent>) =>
|
||||
leader(hub).pipe(
|
||||
Effect.flatMap((member) => member.deliver(events)),
|
||||
Effect.flatMap(ack),
|
||||
)
|
||||
const wait = (sessionID: string, held: Held) =>
|
||||
Effect.gen(function* () {
|
||||
while (true) {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const due = Math.min(held.last + Duration.toMillis(SETTLE), held.first + Duration.toMillis(MAX_SETTLE))
|
||||
if (now >= due) break
|
||||
yield* Effect.sleep(Duration.millis(due - now))
|
||||
}
|
||||
// Once taken, the events are delivered and acknowledged even if the connection closes meanwhile.
|
||||
yield* Effect.uninterruptible(
|
||||
Effect.suspend(() => {
|
||||
waiting.delete(sessionID)
|
||||
return send(held.events)
|
||||
}),
|
||||
)
|
||||
}).pipe(Effect.catch((cause) => Effect.logWarning("failed to deliver settled watch events", { sessionID, cause })))
|
||||
return Effect.fnUntraced(function* (events: ReadonlyArray<WatchEvent>) {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const ready = yield* Effect.forEach(Map.groupBy(events, (event) => event.sessionID), ([sessionID, batch]) =>
|
||||
Effect.gen(function* () {
|
||||
const held = waiting.get(sessionID)
|
||||
if (batch.every(settles)) {
|
||||
if (held) {
|
||||
held.events.push(...batch)
|
||||
held.last = now
|
||||
return []
|
||||
}
|
||||
const fresh: Held = { events: [...batch], first: now, last: now }
|
||||
waiting.set(sessionID, fresh)
|
||||
fresh.fiber = yield* wait(sessionID, fresh).pipe(Effect.forkIn(scope, { startImmediately: true }))
|
||||
return []
|
||||
}
|
||||
if (!held) return batch
|
||||
waiting.delete(sessionID)
|
||||
if (held.fiber) yield* Fiber.interrupt(held.fiber)
|
||||
return [...held.events, ...batch]
|
||||
}),
|
||||
)
|
||||
yield* send(ready.flat())
|
||||
})
|
||||
})
|
||||
|
||||
function chunks(ids: ReadonlyArray<string>) {
|
||||
return Array.from({ length: Math.ceil(ids.length / ACK_LIMIT) }, (_, index) =>
|
||||
ids.slice(index * ACK_LIMIT, (index + 1) * ACK_LIMIT),
|
||||
|
|
@ -742,6 +823,11 @@ const actions = new Map<string, (target: string) => string>([
|
|||
["review", (target) => `reviewed ${target}`],
|
||||
])
|
||||
|
||||
/** A status change, which waits for the others that follow it; not something someone wrote or a server's own event. */
|
||||
function settles(event: WatchEvent) {
|
||||
return !actions.has(event.kind) && event.kind !== "event" && event.kind !== "channel_post"
|
||||
}
|
||||
|
||||
/**
|
||||
* The member's own words read as theirs, so a reply from their phone steers the agent. Anyone else's, and anything a
|
||||
* bot wrote, are information for the task, never a source of new actions. So is a new message in a channel the session
|
||||
|
|
|
|||
|
|
@ -249,6 +249,33 @@ const deliver = Effect.fnUntraced(function* (console: ReturnType<typeof fakeCons
|
|||
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes(event.id)))
|
||||
})
|
||||
|
||||
/**
|
||||
* Pushes status changes and waits until the client holds them. Frames are read in order, so once a marker pushed after
|
||||
* them is acknowledged, their wait has begun. The marker's session is marked deleted, so it acknowledges without a wake.
|
||||
*/
|
||||
const hold = Effect.fnUntraced(function* (
|
||||
console: ReturnType<typeof fakeConsole>,
|
||||
host: PluginContext.Context,
|
||||
...events: WatchEvent[]
|
||||
) {
|
||||
const marker = `evt_marker_${crypto.randomUUID()}`
|
||||
yield* host.storage.set("watch-deleted:ses_marker", 0)
|
||||
console.push(...events)
|
||||
console.push(watchEvent("ses_marker", marker))
|
||||
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes(marker)))
|
||||
})
|
||||
|
||||
/** Pushes status changes, lets them settle, and waits until the plugin acknowledges them. */
|
||||
const settle = Effect.fnUntraced(function* (
|
||||
console: ReturnType<typeof fakeConsole>,
|
||||
host: PluginContext.Context,
|
||||
...events: WatchEvent[]
|
||||
) {
|
||||
yield* hold(console, host, ...events)
|
||||
yield* TestClock.adjust(OpencodeWatches.SETTLE)
|
||||
yield* waitUntil(Effect.sync(() => events.every((event) => console.state.acks.flat().includes(event.id))))
|
||||
})
|
||||
|
||||
const watchTools = Effect.gen(function* () {
|
||||
const tools = yield* Tool.Service
|
||||
return (yield* tools.list()).filter((tool) => tool.options?.namespace === "console_watch").map((tool) => tool.name)
|
||||
|
|
@ -339,7 +366,9 @@ describe("OpencodePlugin event watches", () => {
|
|||
const own = yield* host.session.create({})
|
||||
const ci = yield* host.session.create({})
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
console.push(
|
||||
yield* settle(
|
||||
console,
|
||||
host,
|
||||
watchEvent(own.id, "evt_own", {
|
||||
source: "slack",
|
||||
kind: "message",
|
||||
|
|
@ -351,7 +380,6 @@ describe("OpencodePlugin event watches", () => {
|
|||
}),
|
||||
watchEvent(ci.id, "evt_ci", { kind: "workflow_run", status: "failure", body: "Run tests: exit 1" }),
|
||||
)
|
||||
yield* waitUntil(Effect.sync(() => console.state.acks.flat().length === 2))
|
||||
|
||||
const text = (sessionID: Session.ID) => wakes.find((wake) => wake.sessionID === sessionID)?.text ?? ""
|
||||
expect(text(own.id)).toContain(
|
||||
|
|
@ -651,8 +679,9 @@ describe("OpencodePlugin event watches", () => {
|
|||
yield* (yield* watchTool("watch")).execute({ target: "acme/app#1", unattended: true }, context(session.id))
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
for (const index of [1, 2, 3, 4, 5, 6])
|
||||
yield* deliver(
|
||||
yield* settle(
|
||||
console,
|
||||
host,
|
||||
watchEvent(session.id, `evt_${index}`, { watchID: "ew_new", kind: "workflow_run", status: "success" }),
|
||||
)
|
||||
expect(wakes.map((wake) => wake.resume)).toEqual([true, true, true, true, true, false])
|
||||
|
|
@ -694,7 +723,7 @@ describe("OpencodePlugin event watches", () => {
|
|||
const session = yield* host.session.create({})
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
for (const index of [1, 2, 3, 4, 5, 6])
|
||||
yield* deliver(console, watchEvent(session.id, `evt_${index}`, { kind: "workflow_run", status: "success" }))
|
||||
yield* settle(console, host, watchEvent(session.id, `evt_${index}`, { kind: "workflow_run", status: "success" }))
|
||||
yield* deliver(
|
||||
console,
|
||||
watchEvent(session.id, "evt_reply", { source: "slack", kind: "message", status: null }),
|
||||
|
|
@ -711,7 +740,7 @@ describe("OpencodePlugin event watches", () => {
|
|||
const session = yield* host.session.create({})
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
for (const index of Array.from({ length: 21 }, (_, index) => index))
|
||||
yield* deliver(console, watchEvent(session.id, `evt_${index}`, { kind: "workflow_job", status: "failure" }))
|
||||
yield* settle(console, host, watchEvent(session.id, `evt_${index}`, { kind: "workflow_job", status: "failure" }))
|
||||
expect(wakes.map((wake) => wake.resume)).toEqual([...Array.from({ length: 20 }, () => true), false])
|
||||
}),
|
||||
),
|
||||
|
|
@ -730,13 +759,86 @@ describe("OpencodePlugin event watches", () => {
|
|||
)
|
||||
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes(`evt_review_${index}`)))
|
||||
}
|
||||
yield* deliver(console, watchEvent(session.id, "evt_ci_6", { kind: "workflow_run", status: "success" }))
|
||||
yield* settle(console, host, watchEvent(session.id, "evt_ci_6", { kind: "workflow_run", status: "success" }))
|
||||
yield* deliver(console, watchEvent(session.id, "evt_review_6"))
|
||||
expect(wakes.map((wake) => wake.resume)).toEqual([true, true, true, true, true, true, false])
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("wakes once for status changes seconds apart, once 15 seconds pass without another or 30 at most", () =>
|
||||
withConsole({}, (console) =>
|
||||
Effect.gen(function* () {
|
||||
const { host, wakes } = yield* start(console)
|
||||
const session = yield* host.session.create({})
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
const status = (id: string, kind: string, status: string) => watchEvent(session.id, id, { kind, status })
|
||||
yield* hold(console, host, status("evt_checks", "check", "all 1 passed"))
|
||||
yield* TestClock.adjust("10 seconds")
|
||||
yield* hold(console, host, status("evt_merged", "state", "merged"))
|
||||
yield* TestClock.adjust("14 seconds")
|
||||
expect(wakes).toEqual([])
|
||||
yield* TestClock.adjust("1 second")
|
||||
yield* waitUntil(Effect.sync(() => wakes.length === 1))
|
||||
expect(wakes[0]?.metadata?.events).toEqual(["evt_checks", "evt_merged"])
|
||||
expect(wakes[0]?.text).toStartWith("2 updates arrived")
|
||||
expect(wakes[0]?.text).not.toContain("Looks good")
|
||||
|
||||
// Each arrives before the last has been quiet for 15 seconds, so the cap sends them 30 seconds after the first.
|
||||
for (const index of [1, 2, 3]) {
|
||||
yield* hold(console, host, status(`evt_slow_${index}`, "workflow_run", "success"))
|
||||
yield* TestClock.adjust("10 seconds")
|
||||
}
|
||||
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes("evt_slow_3")))
|
||||
expect(wakes[1]?.metadata?.events).toEqual(["evt_slow_1", "evt_slow_2", "evt_slow_3"])
|
||||
expect(console.state.acks.flat().filter((id) => !id.startsWith("evt_marker"))).toEqual([
|
||||
"evt_checks",
|
||||
"evt_merged",
|
||||
"evt_slow_1",
|
||||
"evt_slow_2",
|
||||
"evt_slow_3",
|
||||
])
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("wakes at once for something someone wrote, with the status changes still settling", () =>
|
||||
withConsole({}, (console) =>
|
||||
Effect.gen(function* () {
|
||||
const { host, wakes } = yield* start(console)
|
||||
const session = yield* host.session.create({})
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
yield* hold(console, host, watchEvent(session.id, "evt_ci", { kind: "workflow_run", status: "failure" }))
|
||||
yield* deliver(console, watchEvent(session.id, "evt_review"))
|
||||
expect(wakes.map((wake) => wake.metadata?.events)).toEqual([["evt_ci", "evt_review"]])
|
||||
|
||||
// The wait it was in is over: the clock moving on wakes nothing more.
|
||||
yield* TestClock.adjust(OpencodeWatches.MAX_SETTLE)
|
||||
yield* Effect.promise(() => Bun.sleep(50))
|
||||
expect(wakes).toHaveLength(1)
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("leaves status changes still settling unacknowledged when the socket closes, and settles them again", () =>
|
||||
withConsole({}, (console) =>
|
||||
Effect.gen(function* () {
|
||||
const { host, wakes } = yield* start(console)
|
||||
const session = yield* host.session.create({})
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 1))
|
||||
yield* hold(console, host, watchEvent(session.id, "evt_ci", { kind: "workflow_run", status: "success" }))
|
||||
console.state.sockets.forEach((socket) => socket.close(OpencodeWatches.LEASE_CLOSE_CODE, "lease"))
|
||||
yield* waitUntil(Effect.sync(() => console.state.opens === 2))
|
||||
expect(console.state.acks.flat()).not.toContain("evt_ci")
|
||||
|
||||
// The next connection's snapshot sends it again, and it waits there anew.
|
||||
yield* settle(console, host)
|
||||
yield* waitUntil(Effect.sync(() => console.state.acks.flat().includes("evt_ci")))
|
||||
expect(wakes.map((wake) => wake.metadata?.events)).toEqual([["evt_ci"]])
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("resumes a held session with a later wake once 10 minutes pass", () =>
|
||||
withConsole({}, (console) =>
|
||||
Effect.gen(function* () {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue