GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(core): close subagent and stale-snapshot gaps in claim ownership … · anomalyco/opencode@12e7d27

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • AGENTS.md
  • packages/core
    • src
      • job.ts
      • session/execution
        • restart.ts
    • test
      • session-execution.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎AGENTS.md‎

Copy file name to clipboardExpand all lines: AGENTS.md
+1-1Lines changed: 1 addition & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ const table = sqliteTable("session", {
183183
- Keep `SessionExecution` process-global and Session-ID based. Its local implementation owns the process-local Session coordinator and discovers placement through `SessionStore` plus `LocationServiceMap.get(session.location)` only when a drain starts; no layer should take a Session ID. V2 interruption targets the active process-local ownership chain for that Session; interruption of a known but idle or locally unowned Session is a no-op, while the public API rejects an unknown Session.
184184
- Keep `SessionRunner`, model resolution, tool registry, permissions, and filesystem Location-scoped. Omitted `Location.workspaceID` means implicit-local placement; explicit workspace identity remains reserved for future placement semantics.
185185
- Preserve one explicit `llm.stream(request)` call per Physical Attempt and reload projected history before durable continuation. A logical Step may use generic pre-output retries, one full-context retry after continuation rejection, incomplete-stream continuation, or one overflow-compaction rebuild. Generic retries retain the logical step number and do not consume another agent-step allowance. Do not delegate orchestration to an in-memory tool loop.
186-
- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. A write-ahead execution claim marks a process-local busy period for restart recovery: terminal completion, failure, or user interruption releases it, while shutdown interruption and process death preserve it. Startup recovery resumes claimed top-level Sessions with durable per-execution attempt accounting. The claim is a recovery marker, not clustered ownership, fencing, or an exactly-once guarantee.
186+
- Keep local Session drains process-local until clustering is implemented. `SessionRunCoordinator` joins explicit same-Session resumes, coalesces prompt wakeups, and allows different Sessions to run concurrently. A write-ahead execution claim marks a process-local busy period for restart recovery: terminal completion, failure, or user interruption releases it, while shutdown interruption and process death preserve it. Startup recovery resumes claimed top-level Sessions with durable per-execution attempt accounting, skipping claims whose recorded process is still alive on this host. The claim is a recovery marker, not clustered ownership, fencing, or an exactly-once guarantee.
187187
- Keep provider-specific native compaction mechanisms in `@opencode/ai` behind `LLMClient.compact`. `SessionCompaction` chooses a summary or native compaction from the model's `compaction` setting and owns route provenance, request shrinking, the retry policy, interruption, usage accounting, and checkpoint persistence.
188188
- Keep delivery vocabulary explicit. Prompts steer by default. At safe step boundaries, steered compaction takes priority up to the first steered move control; other steers retain enqueue order. At an idle boundary, steers take priority; otherwise exactly one queued item delivers before the runner reevaluates continuation. Inbox items may be cancelled or changed between queue and steer before delivery. Promoting new user input resets the selected agent's step allowance; a batch of steers resets it once.
189189
- One step is one logical LLM call; its durable record covers only the model-visible span. Do not write "provider turn", and do not use bare "turn" for a single call: "turn" is reserved for the future assistant-turn unit containing all steps from prompt promotion until the session would go idle.
Collapse file

‎packages/core/src/job.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/job.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const Background = Schema.Struct({
2727
status: Schema.Literals(["running", "completed", "error", "cancelled"]),
2828
output: Schema.optionalKey(Schema.String),
2929
error: Schema.optionalKey(Schema.String),
30-
pid: Schema.optionalKey(Schema.Number),
30+
pid: Schema.optionalKey(Schema.Int),
3131
})
3232

3333
export type Background = typeof Background.Type
Collapse file

‎packages/core/src/session/execution/restart.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/execution/restart.ts
+25-12Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,10 @@ export const layer = (options?: Options) =>
139139
background: Job.Background,
140140
recovery: Extract<Job.Recovery, { kind: "subagent" }>,
141141
suspended: ReadonlySet<SessionSchema.ID>,
142+
foreign: ReadonlySet<SessionSchema.ID>,
142143
) {
144+
// The live owner still runs the child and delivers its result to the parent.
145+
if (foreign.has(recovery.parentSessionID) || foreign.has(recovery.childSessionID)) return
143146
const child = yield* store.get(recovery.childSessionID)
144147
if (!child || child.parentID !== recovery.parentSessionID || !(yield* store.get(recovery.parentSessionID))) {
145148
yield* jobs.completeBackground(background.notificationID)
@@ -189,15 +192,20 @@ export const layer = (options?: Options) =>
189192
)
190193
})
191194

195+
const foreignClaims = store
196+
.listClaimOwners()
197+
.pipe(
198+
Effect.map(
199+
(owners) =>
200+
new Set(owners.flatMap((owner) => (heldByOtherLiveProcess(owner.pid) ? [owner.sessionID] : []))),
201+
),
202+
)
203+
192204
return Service.of({
193205
resumeSuspendedSessions: Effect.gen(function* () {
194206
const active = yield* execution.active
195207
// Unregistered servers can share this database; their live work is not orphaned.
196-
const foreign = new Set(
197-
(yield* store.listClaimOwners()).flatMap((owner) =>
198-
heldByOtherLiveProcess(owner.pid) ? [owner.sessionID] : [],
199-
),
200-
)
208+
const foreign = yield* foreignClaims
201209
const pending = (yield* jobs.pendingBackground).filter(
202210
(background) => background.pid === undefined || !heldByOtherLiveProcess(background.pid),
203211
)
@@ -208,9 +216,7 @@ export const layer = (options?: Options) =>
208216
)
209217
// Early notices wait for recovery's accounting, including Sessions that exhaust their budget.
210218
const suspended = new Set(
211-
[...(yield* store.listSuspended()), ...children].filter(
212-
(sessionID) => !active.has(sessionID) && !foreign.has(sessionID),
213-
),
219+
[...(yield* store.listSuspended()), ...children].filter((sessionID) => !active.has(sessionID)),
214220
)
215221
yield* store.releaseChildClaims([...children, ...foreign])
216222
yield* Effect.forEach(
@@ -221,15 +227,19 @@ export const layer = (options?: Options) =>
221227
const recovery = background.recovery
222228
yield* recovery.kind === "shell"
223229
? recoverShell(background, recovery)
224-
: recoverSubagent(background, recovery, suspended)
230+
: recoverSubagent(background, recovery, suspended, foreign)
225231
}),
226232
{ discard: true },
227233
)
228234

229235
// Background completion can wake a parent, so inspect local ownership only after recovery.
236+
// Another server may have claimed Sessions while jobs recovered, so read owners again.
230237
const resumed = yield* execution.active
238+
const stillForeign = yield* foreignClaims
231239
yield* Effect.forEach(
232-
(yield* store.listSuspended()).filter((sessionID) => !resumed.has(sessionID) && !foreign.has(sessionID)),
240+
(yield* store.listSuspended()).filter(
241+
(sessionID) => !resumed.has(sessionID) && !stillForeign.has(sessionID),
242+
),
233243
(sessionID) =>
234244
execution
235245
.resume(sessionID)
@@ -244,8 +254,11 @@ export const layer = (options?: Options) =>
244254
)
245255

246256
function heldByOtherLiveProcess(pid: number) {
247-
if (pid === process.pid) return false
248-
// Signal 0 probes existence only; EPERM still means the process is alive.
257+
// kill(0|-1, 0) probes a process group and pid 1 is always init, so those prove nothing.
258+
if (!Number.isSafeInteger(pid) || pid <= 1 || pid === process.pid) return false
259+
// Signal 0 probes existence only; EPERM still means the process is alive. Unlike
260+
// retained-image.ts, any other failure (including a runtime without process.kill) counts
261+
// as dead so recovery falls back to resuming rather than stranding the claim.
249262
try {
250263
process.kill(pid, 0)
251264
return true
Collapse file

‎packages/core/test/session-execution.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/session-execution.test.ts
+146-2Lines changed: 146 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1355,15 +1355,159 @@ describe("SessionRestart claim ownership", () => {
13551355
expect((yield* jobs.pendingBackground).map((job) => job.pid)).toEqual([process.pid])
13561356
}),
13571357
)
1358+
1359+
it.effect("the sweep keeps child claims held by another live process", () =>
1360+
Effect.gen(function* () {
1361+
const database = yield* Database.Service
1362+
const parent = Session.ID.make("ses_claim_owner_child_parent")
1363+
const child = Session.ID.make("ses_claim_owner_child_live")
1364+
yield* seedSessions(database, [parent])
1365+
yield* seedSessions(database, [child], {
1366+
parent_id: parent,
1367+
time_suspended: Date.now(),
1368+
claim_pid: yield* liveProcess,
1369+
})
1370+
1371+
const scope = yield* Scope.make()
1372+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
1373+
const context = yield* buildExecution(scope, () => Effect.void)
1374+
yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
1375+
1376+
expect((yield* claims(database))[child]).toBe(true)
1377+
}),
1378+
)
1379+
1380+
it.effect("treats pid 1 as an unknown owner and resumes the claim", () =>
1381+
Effect.gen(function* () {
1382+
const database = yield* Database.Service
1383+
const sessionID = Session.ID.make("ses_claim_owner_pid_one")
1384+
yield* seedSessions(database, [sessionID], { time_suspended: Date.now(), claim_pid: 1 })
1385+
1386+
const drained = yield* Deferred.make<string>()
1387+
const scope = yield* Scope.make()
1388+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
1389+
const context = yield* buildExecution(scope, ({ sessionID: id }) => Deferred.succeed(drained, id))
1390+
yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
1391+
1392+
expect(yield* Deferred.await(drained)).toBe(sessionID)
1393+
}),
1394+
)
1395+
1396+
it.effect("resumes only the orphaned claims when a live owner holds others", () =>
1397+
Effect.gen(function* () {
1398+
const database = yield* Database.Service
1399+
const orphaned = Session.ID.make("ses_claim_owner_mixed_dead")
1400+
const held = Session.ID.make("ses_claim_owner_mixed_live")
1401+
yield* seedSessions(database, [orphaned], { time_suspended: Date.now(), claim_pid: yield* exitedProcess })
1402+
yield* seedSessions(database, [held], { time_suspended: Date.now(), claim_pid: yield* liveProcess })
1403+
1404+
const drained: string[] = []
1405+
const orphanedDrained = yield* Deferred.make<void>()
1406+
const scope = yield* Scope.make()
1407+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
1408+
const context = yield* buildExecution(scope, ({ sessionID: id }) =>
1409+
Effect.sync(() => void drained.push(id)).pipe(
1410+
Effect.andThen(id === orphaned ? Deferred.succeed(orphanedDrained, undefined) : Effect.void),
1411+
),
1412+
)
1413+
yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
1414+
yield* Deferred.await(orphanedDrained)
1415+
1416+
expect(drained).toEqual([orphaned])
1417+
expect(yield* attempts(database, held)).toBe(0)
1418+
expect((yield* claims(database))[held]).toBe(true)
1419+
}),
1420+
)
1421+
1422+
it.effect("skips subagent jobs whose child is held by another live process", () =>
1423+
Effect.gen(function* () {
1424+
const database = yield* Database.Service
1425+
const kv = yield* KV.Service
1426+
const parent = Session.ID.make("ses_subagent_owner_parent")
1427+
const child = Session.ID.make("ses_subagent_owner_child_live")
1428+
yield* seedSessions(database, [parent])
1429+
yield* seedSessions(database, [child], {
1430+
parent_id: parent,
1431+
time_suspended: Date.now(),
1432+
claim_pid: yield* liveProcess,
1433+
})
1434+
yield* seedSubagentJob(kv, parent, child, "running")
1435+
1436+
const drained: string[] = []
1437+
const scope = yield* Scope.make()
1438+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
1439+
const restarted = yield* Job.make.pipe(Effect.provideService(Scope.Scope, scope))
1440+
const context = yield* buildExecution(
1441+
scope,
1442+
({ sessionID: id }) => Effect.sync(() => void drained.push(id)),
1443+
undefined,
1444+
restarted,
1445+
)
1446+
yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
1447+
yield* Context.get(context, SessionExecution.Service).awaitIdle(child)
1448+
1449+
expect(drained).toEqual([])
1450+
expect(yield* attempts(database, child)).toBe(0)
1451+
expect((yield* restarted.pendingBackground).map((job) => job.id)).toEqual(["call-subagent-owner"])
1452+
}),
1453+
)
1454+
1455+
it.effect("leaves subagent results for a parent held by another live process undelivered", () =>
1456+
Effect.gen(function* () {
1457+
const database = yield* Database.Service
1458+
const kv = yield* KV.Service
1459+
const store = yield* SessionStore.Service
1460+
const parent = Session.ID.make("ses_subagent_owner_parent_live")
1461+
const child = Session.ID.make("ses_subagent_owner_child_done")
1462+
yield* seedSessions(database, [parent], { time_suspended: Date.now(), claim_pid: yield* liveProcess })
1463+
yield* seedSessions(database, [child], { parent_id: parent })
1464+
yield* seedSubagentJob(kv, parent, child, "completed")
1465+
1466+
const drained: string[] = []
1467+
const scope = yield* Scope.make()
1468+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
1469+
const restarted = yield* Job.make.pipe(Effect.provideService(Scope.Scope, scope))
1470+
const context = yield* buildExecution(
1471+
scope,
1472+
({ sessionID: id }) => Effect.sync(() => void drained.push(id)),
1473+
undefined,
1474+
restarted,
1475+
)
1476+
yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions
1477+
yield* Context.get(context, SessionExecution.Service).awaitIdle(parent)
1478+
1479+
expect(drained).toEqual([])
1480+
expect((yield* store.context(parent)).filter((message) => message.type === "synthetic")).toEqual([])
1481+
expect((yield* restarted.pendingBackground).map((job) => job.id)).toEqual(["call-subagent-owner"])
1482+
}),
1483+
)
13581484
})
13591485

1486+
/** A subagent job persisted without a pid, as servers from before claim ownership write them. */
1487+
function seedSubagentJob(kv: KV.Interface, parent: Session.ID, child: Session.ID, status: "running" | "completed") {
1488+
const notificationID = SessionMessage.ID.create()
1489+
return kv.set(`job.background/${notificationID}`, {
1490+
id: "call-subagent-owner",
1491+
notificationID,
1492+
recovery: {
1493+
kind: "subagent",
1494+
parentSessionID: parent,
1495+
childSessionID: child,
1496+
agent: "general",
1497+
description: "review",
1498+
},
1499+
status,
1500+
...(status === "completed" ? { output: "done" } : {}),
1501+
})
1502+
}
1503+
13601504
const liveProcess = Effect.acquireRelease(
1361-
Effect.sync(() => Bun.spawn(["sleep", "60"])),
1505+
Effect.sync(() => Bun.spawn([process.execPath, "-e", "setTimeout(() => {}, 60_000)"])),
13621506
(child) => Effect.sync(() => child.kill()),
13631507
).pipe(Effect.map((child) => child.pid))
13641508

13651509
const exitedProcess = Effect.promise(async () => {
1366-
const child = Bun.spawn(["true"])
1510+
const child = Bun.spawn([process.execPath, "-e", ""])
13671511
await child.exited
13681512
return child.pid
13691513
})

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.