Skip to content

Commit 1908fcb

Browse files
authored
fix(core): release location holders on shutdown (anomalyco#59399)
1 parent e469e85 commit 1908fcb

10 files changed

Lines changed: 357 additions & 15 deletions

File tree

‎packages/core/src/location-activity.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { Bus } from "./bus.js"
66
import { Config } from "./config.js"
77
import { Job } from "./job.js"
88
import { Location } from "./location.js"
9+
import { LocationLifecycle } from "./location-lifecycle.js"
910
import { LocationServiceMap } from "./location-service-map.js"
1011
import { SessionEvent } from "./session/event.js"
1112
import { SessionExecution } from "./session/execution.js"
@@ -50,6 +51,22 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
5051
Effect.orElseSucceed(() => timeToLive),
5152
)
5253

54+
// An open terminal or client MCP socket keeps its Location loaded: eviction would end the shell under the user,
55+
// and the client would reconnect and boot a fresh Location right away.
56+
const retained = (ref: Location.Ref) =>
57+
locations
58+
.contextEffectOption(ref)
59+
.pipe(
60+
Effect.map(
61+
Option.exists((context) =>
62+
Option.exists(Context.getOption(context, LocationLifecycle.Service), (lifecycle) =>
63+
lifecycle.isRetained(),
64+
),
65+
),
66+
),
67+
Effect.scoped,
68+
)
69+
5370
const unsubscribe = yield* bus.listen((event) => {
5471
if (!isSessionEvent(event) || !event.location) return Effect.void
5572
const location = LocationServiceMap.canonical(event.location)
@@ -87,14 +104,16 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
87104
)
88105
yield* Effect.forEach(
89106
expired,
90-
(entry) => {
91-
if (occupied.has(key(entry.ref))) return touch(entry.ref)
92-
entries.delete(key(entry.ref))
93-
return Effect.logInfo("location services evicted", {
94-
directory: entry.ref.directory,
95-
workspaceID: entry.ref.workspaceID,
96-
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
97-
},
107+
(entry) =>
108+
Effect.gen(function* () {
109+
if (occupied.has(key(entry.ref)) || (yield* retained(entry.ref))) return yield* touch(entry.ref)
110+
entries.delete(key(entry.ref))
111+
yield* Effect.logInfo("location services evicted", {
112+
directory: entry.ref.directory,
113+
workspaceID: entry.ref.workspaceID,
114+
})
115+
yield* locations.invalidate(entry.ref)
116+
}),
98117
{ discard: true },
99118
)
100119
}).pipe(Effect.forever, Effect.forkScoped)

‎packages/core/src/location-lifecycle.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export * as LocationLifecycle from "./location-lifecycle.js"
22

3-
import { Context, Deferred, Effect, Layer, Schema } from "effect"
3+
import { Context, Deferred, Effect, Layer, Schema, Scope } from "effect"
44
import { makeLocationNode } from "@opencode/util/effect/app-node"
55
import { LocationEvent } from "@opencode/schema/location-event"
66
import { Bus } from "./bus.js"
@@ -16,7 +16,15 @@ const isSessionEvent = Schema.is(SessionEvent.Durable)
1616

1717
export class Service extends Context.Service<
1818
Service,
19-
{ readonly isClosed: () => boolean; readonly shutdown: Effect.Effect<void> }
19+
{
20+
readonly isClosed: () => boolean
21+
readonly shutdown: Effect.Effect<void>
22+
/** Completes once shutdown has run. Long-lived holders release the Location on it so its scope can close. */
23+
readonly awaitShutdown: Effect.Effect<void>
24+
/** Keeps the idle sweep from evicting the Location for the calling scope, for open client connections. */
25+
readonly retain: Effect.Effect<void, never, Scope.Scope>
26+
readonly isRetained: () => boolean
27+
}
2028
>()("@opencode/LocationLifecycle") {}
2129

2230
const layer = Layer.effect(
@@ -39,6 +47,7 @@ const layer = Layer.effect(
3947
})
4048
yield* Effect.addFinalizer(() => unsubscribe)
4149
let closed = false
50+
let retained = 0
4251
const done = yield* Deferred.make<void>()
4352
const shutdown = Effect.suspend(() => {
4453
if (closed) return Deferred.await(done)
@@ -59,6 +68,17 @@ const layer = Layer.effect(
5968
return Service.of({
6069
isClosed: () => closed,
6170
shutdown,
71+
awaitShutdown: Deferred.await(done),
72+
retain: Effect.acquireRelease(
73+
Effect.sync(() => {
74+
retained++
75+
}),
76+
() =>
77+
Effect.sync(() => {
78+
retained--
79+
}),
80+
),
81+
isRetained: () => retained > 0,
6282
})
6383
}),
6484
)

‎packages/core/src/location-services.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ export { LocationServiceMap } from "./location-service-map.js"
99

1010
export type LocationServices = Instance.Services
1111

12+
const HELD_WARNING_AFTER = "30 seconds"
13+
1214
export function buildLocationServiceMap(
1315
replacements: LayerNode.Replacements = [],
1416
): Layer.Layer<LocationServiceMap.Service> {
@@ -77,10 +79,34 @@ export function buildLocationServiceMap(
7779
const key = LocationServiceMap.canonical(ref)
7880
const build = Option.getOrUndefined(MutableHashMap.get(builds, key))
7981
MutableHashMap.remove(builds, key)
82+
const state = inner.rcMap.state
83+
const held = state._tag === "Open" ? Option.getOrUndefined(MutableHashMap.get(state.map, key)) : undefined
8084
// Detach routing first, then cancel interactions and notify clients. Running
8185
// steps retain their borrowed graph until they can hand off at a boundary.
8286
// Do not await a boot here: failed/in-flight builds have their own cleanup path.
83-
return inner.invalidate(key).pipe(Effect.andThen(build?.close ?? Effect.void))
87+
return inner.invalidate(key).pipe(
88+
Effect.andThen(build?.close ?? Effect.void),
89+
Effect.andThen(
90+
// Borrowers release on shutdown; one that does not keeps every service of this Location running.
91+
// The timer lives in the Location's scope, so it stops as soon as the last borrower lets go
92+
// (forking into an already closed scope never starts it).
93+
held
94+
? Effect.sleep(HELD_WARNING_AFTER).pipe(
95+
Effect.andThen(
96+
Effect.suspend(() =>
97+
Effect.logWarning("location still held after shutdown", {
98+
directory: key.directory,
99+
workspaceID: key.workspaceID,
100+
holders: held.refCount,
101+
}),
102+
),
103+
),
104+
Effect.forkIn(held.scope),
105+
Effect.asVoid,
106+
)
107+
: Effect.void,
108+
),
109+
)
84110
}).pipe(Effect.uninterruptible),
85111
}
86112
// Cached instances borrow their owner instead of retaining its Layer scope.

‎packages/core/test/location-layer.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { describe, expect } from "bun:test"
55
import { Event } from "@opencode/schema/config"
66
import { Money } from "@opencode/schema/money"
77
import {
8+
Context,
89
DateTime,
910
Deferred,
1011
Duration,
@@ -15,6 +16,7 @@ import {
1516
Hash,
1617
Layer,
1718
LayerMap,
19+
Logger,
1820
Option,
1921
RcMap,
2022
Schema,
@@ -29,6 +31,7 @@ import { Global } from "@opencode/util/global"
2931
import { LocationServiceMap, type LocationServices } from "@opencode/core/location-services"
3032
import { LocationActivity } from "@opencode/core/location-activity"
3133
import { Location } from "@opencode/core/location"
34+
import { LocationLifecycle } from "@opencode/core/location-lifecycle"
3235
import { Config } from "@opencode/core/config"
3336
import { LocationWatcher } from "@opencode/core/filesystem/location-watcher"
3437
import { Plugin } from "@opencode/core/plugin"
@@ -316,6 +319,39 @@ describe("LocationServiceMap", () => {
316319
}),
317320
)
318321

322+
for (const holder of ["stays", "releases on shutdown"] as const)
323+
it.effect(
324+
`warns when a borrower ${holder === "stays" ? "still holds" : "lets go of"} an invalidated location`,
325+
() => {
326+
const warnings: unknown[] = []
327+
const logger = Logger.map(Logger.formatStructured, (entry) => {
328+
if (entry.level === "WARN") warnings.push(entry.message)
329+
})
330+
return Effect.gen(function* () {
331+
const dir = yield* tmpdirScoped()
332+
const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
333+
const locations = yield* LocationServiceMap.Service
334+
const borrow = yield* Scope.make()
335+
const context = yield* locations.contextEffect(ref).pipe(Scope.provide(borrow))
336+
if (holder === "releases on shutdown")
337+
yield* Context.get(context, LocationLifecycle.Service).awaitShutdown.pipe(
338+
Effect.andThen(Scope.close(borrow, Exit.void)),
339+
Effect.forkScoped,
340+
)
341+
342+
yield* locations.invalidate(ref)
343+
yield* Effect.yieldNow
344+
yield* TestClock.adjust("30 seconds")
345+
expect(warnings).toEqual(
346+
holder === "stays"
347+
? [["location still held after shutdown", { directory: dir.path, workspaceID: undefined, holders: 1 }]]
348+
: [],
349+
)
350+
yield* Scope.close(borrow, Exit.void)
351+
}).pipe(Effect.provide(Logger.layer([logger])))
352+
},
353+
)
354+
319355
it.live("retries a location after its missing directory is recreated", () =>
320356
Effect.acquireRelease(
321357
Effect.promise(() => tmpdir()),
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import { expect } from "bun:test"
2+
import { Clock, Context, Duration, Effect, Exit, Layer, RcMap, Schedule, Scope } from "effect"
3+
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
4+
import { LayerNode } from "@opencode/util/effect/layer-node"
5+
import { makeGlobalNode } from "@opencode/util/effect/app-node"
6+
import { Global } from "@opencode/util/global"
7+
import { Bus } from "@opencode/core/bus"
8+
import { Database } from "@opencode/core/database/database"
9+
import { Job } from "@opencode/core/job"
10+
import { Location } from "@opencode/core/location"
11+
import { LocationActivity } from "@opencode/core/location-activity"
12+
import { LocationLifecycle } from "@opencode/core/location-lifecycle"
13+
import { LocationServiceMap } from "@opencode/core/location-services"
14+
import { AbsolutePath } from "@opencode/core/schema"
15+
import { Session } from "@opencode/core/session"
16+
import { SessionExecution } from "@opencode/core/session/execution"
17+
import { SessionStore } from "@opencode/core/session/store"
18+
import { tempGlobalLayer } from "./fixture/global"
19+
import { offlineModels } from "./fixture/models"
20+
import { tmpdirScoped } from "./fixture/tmpdir"
21+
import { testEffect } from "./lib/effect"
22+
23+
// LocationActivity measures idleness on this clock; only the test moves it past the TTL (see browser-idle.test.ts).
24+
const timeToLive = Duration.minutes(1)
25+
const idle = { millis: 0 }
26+
const live = Clock.Clock.defaultValue()
27+
const activityClock: Clock.Clock = {
28+
currentTimeMillisUnsafe: () => live.currentTimeMillisUnsafe() + idle.millis,
29+
currentTimeMillis: Effect.sync(() => live.currentTimeMillisUnsafe() + idle.millis),
30+
currentTimeNanosUnsafe: () => live.currentTimeNanosUnsafe() + BigInt(idle.millis) * 1_000_000n,
31+
currentTimeNanos: Effect.sync(() => live.currentTimeNanosUnsafe() + BigInt(idle.millis) * 1_000_000n),
32+
monotonicTimeNanosUnsafe: () => live.monotonicTimeNanosUnsafe(),
33+
monotonicTimeNanos: live.monotonicTimeNanos,
34+
sleep: (duration) => live.sleep(duration),
35+
}
36+
37+
const it = testEffect(
38+
AppNodeBuilder.build(
39+
LayerNode.group([Database.node, Bus.node, Session.node, LocationServiceMap.node, LocationActivity.node]),
40+
[
41+
Global.node.replace(tempGlobalLayer),
42+
offlineModels,
43+
LocationActivity.node.replace(
44+
makeGlobalNode({
45+
service: LocationActivity.Service,
46+
layer: LocationActivity.layer({ timeToLive, sweepInterval: "100 millis" }).pipe(
47+
Layer.provide(Layer.succeed(Clock.Clock, activityClock)),
48+
),
49+
deps: [Bus.node, Job.node, LocationServiceMap.node, SessionExecution.node, SessionStore.node],
50+
}),
51+
),
52+
],
53+
),
54+
)
55+
56+
it.live(
57+
"idle sweep keeps a retained location and evicts it once released",
58+
() =>
59+
Effect.gen(function* () {
60+
const locations = yield* LocationServiceMap.Service
61+
const [retained, sibling] = yield* Effect.forEach([0, 1], () =>
62+
tmpdirScoped().pipe(
63+
Effect.map((dir) =>
64+
LocationServiceMap.canonical(Location.Ref.make({ directory: AbsolutePath.make(dir.path) })),
65+
),
66+
),
67+
)
68+
const lifecycle = Context.get(
69+
yield* locations.contextEffect(retained).pipe(Effect.scoped),
70+
LocationLifecycle.Service,
71+
)
72+
yield* locations.contextEffect(sibling).pipe(Effect.scoped)
73+
const hold = yield* Scope.make()
74+
yield* lifecycle.retain.pipe(Scope.provide(hold))
75+
const cached = (ref: Location.Ref) => RcMap.has(locations.rcMap, ref)
76+
// Each poll idles every location for a full TTL, whenever the sweep first saw it.
77+
const until = (check: Effect.Effect<boolean>) =>
78+
Effect.sync(() => {
79+
idle.millis += Duration.toMillis(timeToLive)
80+
}).pipe(
81+
Effect.andThen(check),
82+
Effect.flatMap((done) => (done ? Effect.void : Effect.fail("pending"))),
83+
Effect.retry(Schedule.spaced("20 millis")),
84+
Effect.timeout("10 seconds"),
85+
Effect.orDie,
86+
)
87+
88+
// Both expired; the sweep that evicts the sibling skips the retained location.
89+
yield* until(cached(sibling).pipe(Effect.map((has) => !has)))
90+
expect(yield* cached(retained)).toBe(true)
91+
expect(lifecycle.isClosed()).toBe(false)
92+
93+
yield* Scope.close(hold, Exit.void)
94+
yield* until(cached(retained).pipe(Effect.map((has) => !has)))
95+
expect(lifecycle.isClosed()).toBe(true)
96+
}),
97+
30_000,
98+
)

‎packages/server/src/handlers/mcp.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { Socket } from "effect/socket"
1111
import { Api } from "../api"
1212
import { CorsConfig, isAllowedRequestOrigin } from "../cors"
1313
import { locationErrors, requestRef, response } from "../location"
14-
import { type Outbound, runPtySocket } from "./pty-socket"
14+
import { holdLocation, type Outbound, runPtySocket } from "./pty-socket"
1515

1616
const notFound = <A, R>(effect: Effect.Effect<A, Mcp.NotFoundError, R>) =>
1717
effect.pipe(Effect.mapError((error) => new McpServerNotFoundError({ server: error.server, message: error.message })))
@@ -112,6 +112,7 @@ export const McpHandler = HttpApiBuilder.group(Api, "server.mcp", (handlers) =>
112112
const { McpSocketClient } = yield* Effect.promise(() => import("@opencode/core/mcp/socket-client"))
113113
const socket = yield* Effect.orDie(ctx.request.upgrade)
114114
const outbox = yield* Queue.unbounded<Outbound>()
115+
yield* holdLocation(outbox)
115116
const state = { attached: false, disconnected: false }
116117
const transport = McpSocketClient.make({
117118
send: (text) => Queue.offerUnsafe(outbox, text),

‎packages/server/src/handlers/pty-socket.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { LocationLifecycle } from "@opencode/core/location-lifecycle"
12
import { Effect, Queue } from "effect"
23
import { Socket } from "effect/socket"
34

@@ -31,3 +32,16 @@ export function runPtySocket<R>(input: {
3132
Effect.orDie,
3233
)
3334
}
35+
36+
// A socket borrows its Location for as long as it stays open. Its client reconnects right away when the socket
37+
// closes, so it keeps the idle sweep from evicting the Location (eviction would only boot a fresh one). Any other
38+
// shutdown (reload, VCS init, debug eviction) closes the socket with 1012, which releases the borrow so the
39+
// Location's scope can close, and the client reconnects to the replacement.
40+
export const holdLocation = Effect.fnUntraced(function* (outbox: Queue.Enqueue<Outbound>) {
41+
const lifecycle = yield* LocationLifecycle.Service
42+
yield* lifecycle.retain
43+
yield* lifecycle.awaitShutdown.pipe(
44+
Effect.andThen(Queue.offer(outbox, new Socket.CloseEvent(1012, "location shut down"))),
45+
Effect.forkChild,
46+
)
47+
})

‎packages/server/src/handlers/pty.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
PTY_CONNECT_TOKEN_HEADER_VALUE,
1717
} from "@opencode/protocol/groups/pty"
1818
import { locationErrors, requestRef, response } from "../location"
19-
import { type Outbound, runPtySocket } from "./pty-socket"
19+
import { holdLocation, type Outbound, runPtySocket } from "./pty-socket"
2020

2121
const notFound = (ptyID: Pty.ID) => new PtyNotFoundError({ ptyID, message: `PTY session not found: ${ptyID}` })
2222

@@ -137,6 +137,7 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
137137
const socket = yield* Effect.orDie(ctx.request.upgrade)
138138
// TODO: Integrate graceful-shutdown socket tracking before clients migrate to this route.
139139
const outbox = yield* Queue.unbounded<Outbound>()
140+
yield* holdLocation(outbox)
140141
const attachment = yield* pty
141142
.attach(ctx.params.ptyID, {
142143
cursor,
@@ -173,7 +174,7 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
173174
detach: () => attachment?.detach(),
174175
})
175176
return HttpServerResponse.empty()
176-
}).pipe(Effect.provide(locations.get(ref)), locationErrors)
177+
}).pipe(Effect.scoped, Effect.provide(locations.get(ref)), locationErrors)
177178
}),
178179
)
179180
}),

0 commit comments

Comments
 (0)