GeezerVison is showing github.com — fix(core): recover sessions and jobs from transient storage failures by kitlangton · Pull Request #53704 · anomalyco/opencode
fix(core): recover sessions and jobs from transient storage failures
#53704
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.ts
(4)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(core): settle background jobs when their outcome cannot be persisted
A background job persisted its outcome inside settlement, so a write that
failed on a full disk aborted settlement entirely: the job stayed running
forever, its waiters never resumed, and the parent of a background subagent
was never told the child had failed. Later continuations joined the stuck
job and skipped notification too.
Persisting the outcome now retries transient storage failures and then
settles regardless, logging the lost marker. Delivering the outcome to the
parent retries through longer outages, which is safe because the notice
reuses its notification ID, and failures are logged instead of vanishing.
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit 5faeabb2a8d5b01eba8f707e5dfaada7512f5ae6
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2,6 +2,7 @@ export * as Job from "./job.js"
import { Array, Cause, Clock, Context, Deferred, Effect, Exit, Layer, Schema, Scope, SynchronizedRef } from "effect"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { StorageRetry } from "./database/storage-retry.js"
import { KV } from "./kv.js"
import { SessionMessage } from "./session/message.js"
import { SessionSchema } from "./session/schema.js"
Expand Down
Expand Up
@@ -232,7 +233,19 @@ export const make = Effect.gen(function* () {
...(Exit.isFailure(exit) ? { error: errorText(exit.cause) } : {}),
},
}
if (status !== "cancelled") yield* persistBackground(next)
// The durable marker only matters after a restart, while a job left running here would
// never resolve its waiters, so an outcome that cannot be persisted still settles.
if (status !== "cancelled")
yield* persistBackground(next).pipe(
StorageRetry.retry(),
Effect.catchCauseIf(
(cause) => !Cause.hasInterrupts(cause),
(cause) =>
Effect.logError("Failed to persist background job outcome", cause).pipe(
Effect.annotateLogs({ jobID: id }),
),
),
)
return [{ info: snapshot(next), done: job.done, scope: job.scope }, new Map(jobs).set(id, next)]
}),
)
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,7 @@
export * as SubagentJob from "./subagent-job.js"
import { Effect, Scope } from "effect"
import { Cause, Effect, Scope } from "effect"
import { StorageRetry } from "../database/storage-retry.js"
import { Job } from "../job.js"
import { Session } from "../session.js"
import { SubagentCompletion } from "./subagent-completion.js"
Expand All
@@ -26,8 +27,19 @@ export const make: Effect.Effect<Runner, never, Session.Service | Job.Service |
notifications.add(key)
yield* Effect.gen(function* () {
const info = (yield* jobs.wait({ id: recovery.childSessionID })).info
if (info) yield* SubagentCompletion.deliver(sessions, jobs, { ...info, recovery })
// Delivery reuses the notification ID, so a retried admission cannot duplicate the notice.
if (info)
yield* SubagentCompletion.deliver(sessions, jobs, { ...info, recovery }).pipe(
StorageRetry.retry(StorageRetry.settlement),
)
}).pipe(
Effect.tapCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.void
: Effect.logError("Failed to notify parent of subagent outcome", cause).pipe(
Effect.annotateLogs({ sessionID: recovery.parentSessionID, childID: recovery.childSessionID }),
),
),
Effect.ensuring(Effect.sync(() => notifications.delete(key))),
Effect.forkIn(scope, { startImmediately: true }),
)
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -22,6 +22,7 @@ import { SessionMessage } from "@opencode/core/session/message"
import { SessionRunner } from "@opencode/core/session/runner/index"
import { SessionInboxTable, SessionTable } from "@opencode/core/session/sql"
import { SessionStore } from "@opencode/core/session/store"
import { SubagentJob } from "@opencode/core/session/subagent-job"
import { Cause, Context, Deferred, Effect, Exit, Fiber, Layer, LayerMap, Option, Scope, Stream } from "effect"
import { eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
Expand Down
Expand Up
@@ -1321,6 +1322,61 @@ describe("SessionExecution on a full disk", () => {
expect((yield* claims(database))[sessionID]).toBe(true)
}),
)
itFullDisk.effect("a subagent that dies on a full disk reports its failure to the parent", () =>
Effect.gen(function* () {
const database = yield* Database.Service
const jobs = yield* Job.Service
const parentID = Session.ID.make("ses_disk_full_parent")
const childID = Session.ID.make("ses_disk_full_child")
yield* seedSessions(database, [parentID])
yield* seedSessions(database, [childID], { parent_id: parentID })
const backgrounded = yield* Deferred.make<void>()
const scope = yield* Scope.make()
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
const context = yield* buildExecution(scope, ({ sessionID }) =>
sessionID !== childID
? Effect.void
: Effect.gen(function* () {
yield* Deferred.await(backgrounded)
yield* disk.fill
yield* database.db
.update(SessionTable)
.set({ title: "unsaved" })
.where(eq(SessionTable.id, childID))
.run()
.pipe(Effect.orDie)
}),
)
const sessions = Context.get(context, Session.Service)
const execution = Context.get(context, SessionExecution.Service)
const subagents = yield* SubagentJob.make.pipe(
Effect.provideService(Session.Service, Session.Service.of({ ...sessions, resume: execution.resume })),
Effect.provideService(Scope.Scope, scope),
)
const recovery = {
kind: "subagent" as const,
parentSessionID: parentID,
childSessionID: childID,
agent: "general",
description: "Child work",
}
yield* subagents.start(recovery)
yield* subagents.background(recovery)
yield* Deferred.succeed(backgrounded, undefined)
yield* StorageFault.elapse(120_000)
yield* disk.free
yield* StorageFault.elapse(30_000)
const notices = (yield* SessionInbox.list(database.db, parentID)).filter((item) => item.type === "synthetic")
expect(notices).toHaveLength(1)
expect(notices[0]).toMatchObject({ payload: { metadata: { childID, state: "error" } } })
expect(notices[0]?.type === "synthetic" ? notices[0].payload.text : "").toContain("database or disk is full")
expect(yield* jobs.pendingBackground).toEqual([])
}),
)
})
function seedBackground(
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,23 @@
import { describe, expect, test } from "bun:test"
import { Database as Native } from "bun:sqlite"
import { Cause, Effect, Exit, Fiber, Schema } from "effect"
import { Cause, Deferred, Effect, Exit, Fiber, Schema } from "effect"
import { Bus } from "@opencode/core/bus"
import { Event } from "@opencode/schema/event"
import { Database } from "@opencode/core/database/database"
import { StorageRetry } from "@opencode/core/database/storage-retry"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { EventTable } from "@opencode/core/event/sql"
import { Job } from "@opencode/core/job"
import { KV } from "@opencode/core/kv"
import { SessionSchema } from "@opencode/core/session/schema"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { eq } from "drizzle-orm"
import { testEffect } from "./lib/effect"
import { StorageFault } from "./lib/storage-fault"
const disk = StorageFault.make()
const it = testEffect(
AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node]), [
AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, Job.node, KV.node ]), [
Database.node.replace(disk.node),
Bus.node.replace(Bus.configured({ persist: true })),
]),
Expand Down
Expand Up
@@ -104,4 +107,63 @@ describe("StorageRetry", () => {
expect(yield* stored("agg_lost")).toEqual([])
}),
)
it.effect("a background job settles even when its outcome cannot be persisted", () =>
Effect.gen(function* () {
const jobs = yield* Job.Service
const release = yield* Deferred.make<void>()
const recovery = {
kind: "shell" as const,
sessionID: SessionSchema.ID.make("ses_disk_full_shell"),
shellID: "sh_disk_full",
command: "echo done",
}
yield* jobs.start({
id: recovery.shellID,
type: "shell",
recovery,
run: Deferred.await(release).pipe(Effect.as("done")),
})
yield* jobs.background(recovery.shellID)
const waiting = yield* jobs.wait({ id: recovery.shellID }).pipe(Effect.forkScoped)
yield* disk.fill
yield* Deferred.succeed(release, undefined)
yield* StorageFault.elapse(40_000)
expect((yield* Fiber.join(waiting)).info).toMatchObject({ status: "completed", output: "done" })
yield* disk.free
}),
)
it.effect("a background job persists its outcome once a briefly full disk frees", () =>
Effect.gen(function* () {
const jobs = yield* Job.Service
const release = yield* Deferred.make<void>()
const recovery = {
kind: "shell" as const,
sessionID: SessionSchema.ID.make("ses_disk_brief_shell"),
shellID: "sh_disk_brief",
command: "echo done",
}
yield* jobs.start({
id: recovery.shellID,
type: "shell",
recovery,
run: Deferred.await(release).pipe(Effect.as("done")),
})
yield* jobs.background(recovery.shellID)
const waiting = yield* jobs.wait({ id: recovery.shellID }).pipe(Effect.forkScoped)
yield* disk.fill
yield* Deferred.succeed(release, undefined)
yield* StorageFault.elapse(5_000)
yield* disk.free
yield* StorageFault.elapse(3_000)
expect((yield* Fiber.join(waiting)).info).toMatchObject({ status: "completed" })
expect((yield* jobs.pendingBackground).find((item) => item.id === recovery.shellID)).toMatchObject({
status: "completed",
output: "done",
})
}),
)
})
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.