diff --git a/packages/core/src/instance.ts b/packages/core/src/instance.ts index 1335e4d9657..39b862cebbb 100644 --- a/packages/core/src/instance.ts +++ b/packages/core/src/instance.ts @@ -139,7 +139,19 @@ export interface Options { // AGENTS.md instructions — that is session-time context, not boot-time // population. readonly discovery?: boolean + // Child replacements for this instance (or all replacements when `host` is omitted). With `host`, global + // replacements are rejected because the host already built them into `host.context`. readonly replacements?: LayerNode.Replacements + // Global services and inherited replacements the host built once for all of its instances (see `globals`). + // Without it, the instance builds its globals through the enclosing memo map. + readonly host?: LayerNode.Host +} + +/** The global nodes instances read from `hostContext`, which a host builds with its `replacements`. */ +export function globals(replacements: LayerNode.Replacements = []) { + return LayerNode.group( + LayerNode.tagged(LayerNode.group([graph, ...Location.dependencies]), Node.tags.values.global, replacements), + ) } // Vanilla neutralizes the discovery inputs; the plugin list stays untouched. @@ -166,7 +178,11 @@ export function layer(ref: Location.Ref, options: Options = {}): Layer.Layer => diff --git a/packages/core/src/location-service-map.ts b/packages/core/src/location-service-map.ts index 60e0f2c57e6..4194e0d7f80 100644 --- a/packages/core/src/location-service-map.ts +++ b/packages/core/src/location-service-map.ts @@ -1,4 +1,4 @@ -import { Context, Effect, Exit, Layer, LayerMap, RcMap } from "effect" +import { Context, Effect, Exit, Layer, LayerMap, RcMap, Scope } from "effect" import { LayerNode } from "@opencode/util/effect/layer-node" import { Node } from "@opencode/util/effect/app-node" import { AbsolutePath } from "@opencode/schema/schema" @@ -6,10 +6,14 @@ import path from "path" import { Location } from "./location.js" import type { Instance } from "./instance.js" -export class Service extends Context.Service< - Service, - LayerMap.LayerMap ->()("@opencode/example/LocationServiceMap") { +export interface Interface extends LayerMap.LayerMap { + /** The global services and replacements the host built for its instances; absent on hand-built maps. */ + readonly host?: Effect.Effect + /** Closes before the host's Stage-1 globals, so secondary instance containers (e.g. SDK instances) release first. */ + readonly instanceScope?: Scope.Closeable +} + +export class Service extends Context.Service()("@opencode/example/LocationServiceMap") { static get(ref: Location.Ref) { return Layer.unwrap(Effect.map(Service, (locations) => locations.get(ref))) } diff --git a/packages/core/src/location-services.ts b/packages/core/src/location-services.ts index 8112afd929c..f84db19c8ec 100644 --- a/packages/core/src/location-services.ts +++ b/packages/core/src/location-services.ts @@ -1,4 +1,18 @@ -import { Context, Duration, Effect, Exit, Layer, LayerMap, MutableHashMap, Option, Scope } from "effect" +import { + Context, + Deferred, + Duration, + Effect, + Exit, + Fiber, + Layer, + LayerMap, + MutableHashMap, + Option, + RcMap, + Scope, +} from "effect" +import { Node } from "@opencode/util/effect/app-node" import { LayerNode } from "@opencode/util/effect/layer-node" import { Instance } from "./instance.js" import { Location } from "./location.js" @@ -14,43 +28,99 @@ const HELD_WARNING_AFTER = "30 seconds" export function buildLocationServiceMap( replacements: LayerNode.Replacements = [], ): Layer.Layer { - return Layer.effect( - LocationServiceMap.Service, + // Memoized like any other layer, and given the host's memo map so Stage 1 reuses the globals it already built. + return Layer.fromBuildMemo((memoMap, owner) => Effect.gen(function* () { - const owner = yield* Effect.scope + // Forked first so it closes last: Locations and secondary instance containers shut down before Stage-1 globals. + const globalScope = yield* Scope.fork(owner) + const instanceScope = yield* Scope.fork(owner) + let closed = false + let deferred: Deferred.Deferred | undefined + let buildingFiber: Fiber.Fiber | undefined + yield* Scope.addFinalizer( + globalScope, + Effect.sync(() => { + closed = true + if (deferred) Deferred.doneUnsafe(deferred, Exit.interrupt()) + }), + ) + // Synchronous re-entrancy from the Stage-1 builder fiber would deadlock (including on the same Location ref + // already in flight in RcMap); concurrent or background fibers can safely wait on the shared Deferred. + const reentrant = () => buildingFiber !== undefined && Fiber.getCurrent() === buildingFiber + const reentrantError = () => + new Error("A global service booted a Location while its host was still building globals; boot it after startup") + const host: Effect.Effect = Effect.suspend(() => { + if (closed) return Effect.interrupt + if (deferred) { + if (reentrant()) return Effect.die(reentrantError()) + return Deferred.await(deferred) + } + const pending = Deferred.makeUnsafe() + deferred = pending + const build = Effect.suspend(() => { + buildingFiber = Fiber.getCurrent() + return Layer.buildWithMemoMap( + LayerNode.compile(Instance.globals(stage1), { replacements: stage1 }), + memoMap, + globalScope, + ) + }).pipe( + // Like a Location's other boot failures, a global that fails to build is a defect. + Effect.orDie, + Effect.onExit((exit) => + Effect.sync(() => { + buildingFiber = undefined + Deferred.doneUnsafe( + pending, + Exit.map(exit, (context) => ({ tag: Node.tags.values.global, context, replacements })), + ) + }), + ), + ) + // Fork into globalScope so one cancelled Location boot cannot interrupt the shared Stage-1 build, + // while closing the host cleanly interrupts it. + return build.pipe( + Effect.forkIn(globalScope, { startImmediately: true }), + Effect.andThen(Deferred.await(pending)), + ) + }) const builds = MutableHashMap.empty }>() const inner: LayerMap.LayerMap = yield* LayerMap.make( (ref: Location.Ref) => { const build: { close?: Effect.Effect } = {} MutableHashMap.set(builds, ref, build) return Layer.fromBuild((memoMap, scope) => - Effect.suspend(() => - Layer.buildWithMemoMap(Instance.layer(ref, { replacements: bindings }), memoMap, scope), - ).pipe( - Effect.onExit((exit) => { - const finish = Effect.suspend(() => { - if (Exit.isSuccess(exit)) { - return Effect.gen(function* () { - const lifecycle = Context.get(exit.value, LocationLifecycle.Service) - // A boot detached while in flight still needs shutdown and cancellation. - if (Option.getOrUndefined(MutableHashMap.get(builds, ref)) !== build) - return yield* lifecycle.shutdown - build.close = lifecycle.shutdown - }) - } - // An explicitly invalidated build must not evict its replacement. - if (Option.getOrUndefined(MutableHashMap.get(builds, ref)) !== build) return Effect.void - MutableHashMap.remove(builds, ref) - // Evict once per failed build, before its result reaches borrowers. - return Exit.isFailure(exit) ? inner.invalidate(ref) : Effect.void - }) - // With no borrowers, invalidation closes the entry's scope and - // joins this lookup fiber. Let the owner finish that cleanup. - return Exit.isFailure(exit) - ? finish.pipe(Effect.forkIn(owner, { startImmediately: true }), Effect.asVoid) - : finish - }), - ), + host + .pipe( + Effect.flatMap((resolved) => + Layer.buildWithMemoMap(Instance.layer(ref, { host: resolved }), memoMap, scope), + ), + ) + .pipe( + Effect.onExit((exit) => { + const finish = Effect.suspend(() => { + if (Exit.isSuccess(exit)) { + return Effect.gen(function* () { + const lifecycle = Context.get(exit.value, LocationLifecycle.Service) + // A boot detached while in flight still needs shutdown and cancellation. + if (Option.getOrUndefined(MutableHashMap.get(builds, ref)) !== build) + return yield* lifecycle.shutdown + build.close = lifecycle.shutdown + }) + } + // An explicitly invalidated build must not evict its replacement. + if (Option.getOrUndefined(MutableHashMap.get(builds, ref)) !== build) return Effect.void + MutableHashMap.remove(builds, ref) + // Evict once per failed build, before its result reaches borrowers. + return Exit.isFailure(exit) ? inner.invalidate(ref) : Effect.void + }) + // With no borrowers, invalidation closes the entry's scope and + // joins this lookup fiber. Let the owner finish that cleanup. + return Exit.isFailure(exit) + ? finish.pipe(Effect.forkIn(owner, { startImmediately: true }), Effect.asVoid) + : finish + }), + ), ) }, // Retain healthy graphs. Boot failures, not local filesystem probes, @@ -69,10 +139,18 @@ export function buildLocationServiceMap( }), ), ) - const map = { + const map: LocationServiceMap.Interface = { ...inner, - get: (ref: Location.Ref) => inner.get(LocationServiceMap.canonical(ref)), - contextEffect: (ref: Location.Ref) => inner.contextEffect(LocationServiceMap.canonical(ref)), + host, + instanceScope, + get: (ref: Location.Ref) => + Layer.suspend(() => + reentrant() ? Layer.unwrap(Effect.die(reentrantError())) : inner.get(LocationServiceMap.canonical(ref)), + ), + contextEffect: (ref: Location.Ref) => + Effect.suspend(() => + reentrant() ? Effect.die(reentrantError()) : inner.contextEffect(LocationServiceMap.canonical(ref)), + ), contextEffectOption: (ref: Location.Ref) => inner.contextEffectOption(LocationServiceMap.canonical(ref)), invalidate: (ref: Location.Ref) => Effect.suspend(() => { @@ -109,17 +187,20 @@ export function buildLocationServiceMap( ) }).pipe(Effect.uninterruptible), } - // Cached instances borrow their owner instead of retaining its Layer scope. - const bindings: LayerNode.Replacements = [ + // Stage 1 runs lazily on the first Location or SDK instance boot, into globalScope (which closes last), so + // hosts that never open a Location skip Location-only globals while hosts that do build them once for life. + const stage1: LayerNode.Replacements = [ + // The default selector, for hosts that bring none of their own. Instance.node.replace( Layer.succeed(Instance.Service, { provide: (session) => Effect.provide(map.get(session.location)), + live: (session) => RcMap.has(inner.rcMap, LocationServiceMap.canonical(session.location)), }), ), ...replacements, LocationServiceMap.node.replace(Layer.succeed(LocationServiceMap.Service, map)), ] - return map - }), + return Context.make(LocationServiceMap.Service, map) + }).pipe(Scope.provide(owner)), ) } diff --git a/packages/core/src/location.ts b/packages/core/src/location.ts index ef799dfd9ff..775d8df951f 100644 --- a/packages/core/src/location.ts +++ b/packages/core/src/location.ts @@ -41,9 +41,12 @@ const layer = (ref: Ref) => }), ) +// What every bound Location stands on, whatever its directory. +export const dependencies = [CrossSpawnSpawner.node, FSUtil.node, Project.node] as const + export const boundNode = (ref: Ref) => makeLocationNode({ service: Service, layer: layer(ref), - deps: [CrossSpawnSpawner.node, FSUtil.node, Project.node], + deps: dependencies, }) diff --git a/packages/core/test/effect/layer-node/compile-child.test.ts b/packages/core/test/effect/layer-node/compile-child.test.ts new file mode 100644 index 00000000000..37d842417ac --- /dev/null +++ b/packages/core/test/effect/layer-node/compile-child.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, test } from "bun:test" +import { Context, Effect, Layer } from "effect" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { testEffect } from "../../lib/effect" + +class Value extends Context.Service()("test/ChildValue") {} +class Other extends Context.Service()("test/ChildOther") {} +class Local extends Context.Service()("test/ChildLocal") {} + +const it = testEffect(Layer.empty) +const tags = LayerNode.tags({ location: ["global"], global: [] }) +const global = tags.make("global") +const location = tags.make("location") +const shared = tags.values.global + +function counted() { + const acquired = { value: 0, other: 0, local: 0 } + const value = global({ + service: Value, + layer: Layer.effect( + Value, + Effect.sync(() => Value.of({ value: `value-${++acquired.value}` })), + ), + deps: [], + }) + const other = global({ + service: Other, + layer: Layer.effect( + Other, + Effect.map(Value, (value) => Other.of({ value: `other-${++acquired.other} of ${value.value}` })), + ), + deps: [value], + }) + const local = location({ + service: Local, + layer: Layer.effect( + Local, + Effect.gen(function* () { + const value = yield* Value + return Local.of({ value: `local-${++acquired.local} of ${value.value}` }) + }), + ), + deps: [value], + }) + return { acquired, value, other, local } +} + +describe("LayerNode.tagged", () => { + test("collects every reachable tagged node including transitive dependencies, after replacements", () => { + const graph = counted() + const replacement = location({ + service: Local, + layer: Layer.effect( + Local, + Effect.map(Other, (other) => Local.of({ value: other.value })), + ), + deps: [graph.other], + }) + expect(LayerNode.tagged(LayerNode.group([graph.local]), shared).map((node) => node.name)).toEqual([ + "test/ChildValue", + ]) + // Other depends on Value, so both are exposed in hostContext for any child replacement that needs Value directly. + expect( + LayerNode.tagged(LayerNode.group([graph.local, LayerNode.group([graph.local])]), shared, [ + graph.local.replace(replacement), + ]).map((node) => node.name), + ).toEqual(["test/ChildOther", "test/ChildValue"]) + }) +}) + +describe("LayerNode.compileChild", () => { + it.effect("reads globals from the host context and builds locals fresh for every child", () => + Effect.gen(function* () { + const graph = counted() + const context = yield* Layer.build(LayerNode.compile(LayerNode.group([graph.value]))) + expect(graph.acquired).toEqual({ value: 1, other: 0, local: 0 }) + const child = LayerNode.compileChild(LayerNode.group([graph.local, graph.value]), { + host: { tag: shared, context }, + }) + + const first = yield* Layer.build(child) + const second = yield* Layer.build(child) + expect(Context.get(first, Value)).toBe(Context.get(context, Value)) + expect(Context.get(first, Local).value).toBe("local-1 of value-1") + expect(Context.get(second, Local).value).toBe("local-2 of value-1") + expect(graph.acquired).toEqual({ value: 1, other: 0, local: 2 }) + }), + ) + + it.effect("exposes transitive globals built on the host to child-only replacements", () => + Effect.gen(function* () { + const graph = counted() + const localViaOther = location({ + service: Local, + layer: Layer.effect( + Local, + Effect.map(Other, (other) => Local.of({ value: other.value })), + ), + deps: [graph.other], + }) + const context = yield* Layer.build(LayerNode.compile(LayerNode.group(LayerNode.tagged(localViaOther, shared)))) + const child = yield* Layer.build( + LayerNode.compileChild(localViaOther, { + host: { tag: shared, context }, + replacements: [localViaOther.replace(graph.local)], + }), + ) + expect(Context.get(child, Local).value).toBe("local-1 of value-1") + expect(graph.acquired).toEqual({ value: 1, other: 1, local: 1 }) + }), + ) + + test("fails loudly when the host context lacks a global the child reaches", () => { + const graph = counted() + expect(() => LayerNode.compileChild(graph.local, { host: { tag: shared, context: Context.empty() } })).toThrow( + "Host context is missing test/ChildValue", + ) + }) + + test("rejects a child replacement of a global node", () => { + const graph = counted() + expect(() => + LayerNode.compileChild(graph.local, { + host: { tag: shared, context: Context.empty() }, + replacements: [graph.value.replace(Layer.succeed(Value, Value.of({ value: "child" })))], + }), + ).toThrow("Cannot replace test/ChildValue in a child graph") + }) + + it.effect("applies the host's local replacements and skips the global ones it already built", () => + Effect.gen(function* () { + const graph = counted() + const inherited = [ + graph.value.replace(Layer.succeed(Value, Value.of({ value: "host" }))), + graph.local.replace( + location({ + service: Local, + layer: Layer.effect( + Local, + Effect.map(Value, (value) => Local.of({ value: `replaced of ${value.value}` })), + ), + deps: [graph.value], + }), + ), + ] + const context = yield* Layer.build(LayerNode.compile(graph.value, { replacements: inherited })) + const child = yield* Layer.build( + LayerNode.compileChild(graph.local, { host: { tag: shared, context, replacements: inherited } }), + ) + expect(Context.get(child, Local).value).toBe("replaced of host") + expect(graph.acquired).toEqual({ value: 0, other: 0, local: 0 }) + }), + ) +}) diff --git a/packages/core/test/location-host.test.ts b/packages/core/test/location-host.test.ts new file mode 100644 index 00000000000..cebf065de22 --- /dev/null +++ b/packages/core/test/location-host.test.ts @@ -0,0 +1,176 @@ +import { describe, expect } from "bun:test" +import { Cause, Context, Deferred, Effect, Exit, Layer, Scope } from "effect" +import { makeGlobalNode } from "@opencode/util/effect/app-node" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Global } from "@opencode/util/global" +import { Bus } from "@opencode/core/bus" +import { CodeModeApi } from "@opencode/core/codemode/api" +import { Database } from "@opencode/core/database/database" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Watcher } from "@opencode/core/filesystem/watcher" +import { Instance } from "@opencode/core/instance" +import { Location } from "@opencode/core/location" +import { LocationServiceMap } from "@opencode/core/location-service-map" +import { AbsolutePath } from "@opencode/core/schema" +import { tempGlobalLayer } from "./fixture/global" +import { offlineModels } from "./fixture/models" +import { tmpdirScoped } from "./fixture/tmpdir" +import { testEffect } from "./lib/effect" + +const it = testEffect(Layer.empty) + +// CodeModeApi is a global every Location reaches but no host root below does: only Stage 1 builds it. +function codeModeApi(build: (locations: LocationServiceMap.Interface) => Effect.Effect) { + const state = { acquired: 0, locations: undefined as LocationServiceMap.Interface | undefined } + const replacement = CodeModeApi.node.replace( + makeGlobalNode({ + service: CodeModeApi.Service, + layer: Layer.unwrap( + Effect.gen(function* () { + state.acquired++ + state.locations = yield* LocationServiceMap.Service + yield* build(state.locations) + return Layer.succeed(CodeModeApi.Service, CodeModeApi.unavailable) + }), + ), + deps: [LocationServiceMap.node], + }), + ) + return { + state, + replacements: [ + Global.node.replace(tempGlobalLayer), + Watcher.node.replace(Watcher.configured({ enabled: false })), + offlineModels, + replacement, + ], + } +} + +const locationAt = Effect.fn(function* () { + const dir = yield* tmpdirScoped() + return Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) +}) + +describe("location host", () => { + it.live("does not build Location globals until a Location actually boots", () => + Effect.gen(function* () { + const api = codeModeApi(() => Effect.void) + yield* Layer.build(AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node]), api.replacements)) + expect(api.state.acquired).toBe(0) + yield* Layer.build(AppNodeBuilder.build(LocationServiceMap.node, api.replacements)) + expect(api.state.acquired).toBe(0) + }), + ) + + it.live("builds Location globals once on first Location boot, and every Location reads them across reloads", () => + Effect.gen(function* () { + // Create temp directories before building the host so their cleanup runs after Locations close. + const [first, second] = [yield* locationAt(), yield* locationAt()] + const api = codeModeApi(() => Effect.void) + const context = yield* Layer.build(AppNodeBuilder.build(LocationServiceMap.node, api.replacements)) + expect(api.state.acquired).toBe(0) + const locations = Context.get(context, LocationServiceMap.Service) + const directory = (ref: Location.Ref) => + Location.Service.pipe( + Effect.provide(locations.get(ref)), + Effect.scoped, + Effect.map((info) => info.directory), + ) + + expect(yield* Effect.all([directory(first), directory(second)], { concurrency: "unbounded" })).toEqual([ + first.directory, + second.directory, + ]) + expect(api.state.acquired).toBe(1) + yield* locations.invalidate(first) + expect(yield* directory(first)).toBe(first.directory) + expect(api.state.acquired).toBe(1) + }), + ) + + it.live("rejects global replacements passed to Instance.layer alongside a host", () => + Effect.gen(function* () { + const ref = yield* locationAt() + const api = codeModeApi(() => Effect.void) + const context = yield* Layer.build(AppNodeBuilder.build(LocationServiceMap.node, api.replacements)) + const locations = Context.get(context, LocationServiceMap.Service) + const host = yield* locations.host ?? Effect.die(new Error("no host")) + expect(() => + Instance.layer(ref, { + host, + replacements: [CodeModeApi.node.replace(Layer.succeed(CodeModeApi.Service, CodeModeApi.unavailable))], + }), + ).toThrow("Cannot replace @opencode/CodeModeApi in a child graph") + }), + ) + + it.live("fails a synchronous Location boot from inside Stage 1 instead of deadlocking", () => + Effect.gen(function* () { + const ref = yield* locationAt() + const api = codeModeApi((locations) => + Effect.scoped(locations.contextEffect(ref)).pipe(Effect.orDie, Effect.asVoid), + ) + const context = yield* Layer.build(AppNodeBuilder.build(LocationServiceMap.node, api.replacements)) + const locations = Context.get(context, LocationServiceMap.Service) + const exit = yield* Effect.scoped(locations.contextEffect(ref)).pipe(Effect.exit) + expect(Exit.isFailure(exit) && Cause.pretty(exit.cause)).toContain("still building globals") + }), + ) + + it.live("lets a forked background fiber during Stage 1 await hostContext instead of failing", () => + Effect.gen(function* () { + const ref = yield* locationAt() + const result = yield* Deferred.make() + const api = codeModeApi((locations) => + Effect.gen(function* () { + yield* Effect.scoped( + locations.contextEffect(ref).pipe(Effect.map((ctx) => Context.get(ctx, Location.Service).directory)), + ).pipe( + Effect.flatMap((dir) => Deferred.succeed(result, dir)), + Effect.forkDetach, + ) + // Give the forked fiber a turn to hit locations.host before Stage 1 finishes. + yield* Effect.yieldNow + }), + ) + const context = yield* Layer.build(AppNodeBuilder.build(LocationServiceMap.node, api.replacements)) + const locations = Context.get(context, LocationServiceMap.Service) + expect( + yield* Effect.scoped( + locations.contextEffect(ref).pipe(Effect.map((ctx) => Context.get(ctx, Location.Service).directory)), + ), + ).toBe(ref.directory) + expect(yield* Deferred.await(result)).toBe(ref.directory) + expect(api.state.acquired).toBe(1) + }), + ) + + it.live("fails the host context when Stage 1 fails", () => + Effect.gen(function* () { + const ref = yield* locationAt() + const api = codeModeApi(() => Effect.die(new Error("stage 1 broke"))) + const context = yield* Layer.build(AppNodeBuilder.build(LocationServiceMap.node, api.replacements)) + const locations = Context.get(context, LocationServiceMap.Service) + const exit = yield* Effect.scoped(locations.contextEffect(ref)).pipe(Effect.exit) + expect(Exit.isFailure(exit) && Cause.pretty(exit.cause)).toContain("stage 1 broke") + const host = yield* Effect.exit(locations.host ?? Effect.die(new Error("no host"))) + expect(Exit.isFailure(host) && Cause.pretty(host.cause)).toContain("stage 1 broke") + }), + ) + + it.live("interrupts host lookup cleanly after the host scope closes", () => + Effect.gen(function* () { + const api = codeModeApi(() => Effect.void) + const scope = yield* Scope.make() + const context = yield* Layer.buildWithScope( + AppNodeBuilder.build(LocationServiceMap.node, api.replacements), + scope, + ) + const locations = Context.get(context, LocationServiceMap.Service) + yield* Scope.close(scope, Exit.void) + const exit = yield* Effect.exit(locations.host ?? Effect.die(new Error("no host"))) + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true) + }), + ) +}) diff --git a/packages/sdk/src/internal/host.ts b/packages/sdk/src/internal/host.ts index 35b5911f020..363393160b3 100644 --- a/packages/sdk/src/internal/host.ts +++ b/packages/sdk/src/internal/host.ts @@ -43,7 +43,7 @@ export const create = Effect.fn("EmbeddedHost.create")(function* ( workspaceProviders ? [...(embed.overrides ?? []), WorkspaceDriver.node.replace(WorkspaceDriver.registryNode(workspaceProviders))] : embed.overrides, - selector ? (replacements) => SdkInstances.node(selector, replacements) : undefined, + selector ? SdkInstances.node(selector) : undefined, ).pipe(Layer.provide(HttpServer.layerServices), Layer.provideMerge(layer(log))), ) diff --git a/packages/sdk/src/internal/instances.ts b/packages/sdk/src/internal/instances.ts index f48440a6a5b..366e09e1cfb 100644 --- a/packages/sdk/src/internal/instances.ts +++ b/packages/sdk/src/internal/instances.ts @@ -6,8 +6,7 @@ import { Plugin } from "@opencode/core/plugin" import type { InstancePlugins } from "@opencode/core/plugin/instance" import type { Session } from "@opencode/schema/session" import { makeGlobalNode } from "@opencode/util/effect/app-node" -import type { LayerNode } from "@opencode/util/effect/layer-node" -import { Context, Duration, Effect, Layer, LayerMap, RcMap, Scope } from "effect" +import { Context, Duration, Effect, Exit, Layer, LayerMap, RcMap, Scope } from "effect" export interface Configuration { readonly plugins: InstancePlugins.List @@ -36,26 +35,30 @@ export function provide(options: Options, context: Context.Context): Op } } -/** Replaces the host's `Instance.node`; `replacements` resolves lazily so instances inherit the final host graph. */ -export function node(options: Options, replacements: () => LayerNode.Replacements) { +/** Replaces the host's `Instance.node` with per-session instances backed by the host's `LocationServiceMap`. */ +export function node(options: Options) { return makeGlobalNode({ service: Instance.Service, - layer: layer(options, replacements), + layer: layer(options), deps: [LocationServiceMap.node], }) } -export function layer(options: Options, replacements: () => LayerNode.Replacements) { +function layer(options: Options) { return Layer.effect( Instance.Service, Effect.gen(function* () { - const scope = yield* Effect.scope const locations = yield* LocationServiceMap.Service + const host = locations.host + const instanceScope = locations.instanceScope + if (!host || !instanceScope) + return yield* Effect.die(new Error("SdkInstances needs the host's own LocationServiceMap")) const key = (session: Session.Info) => ({ key: options.key(session), ...LocationServiceMap.canonical(session.location), }) const provide = (session: Session.Info) => Effect.provide(instances.get(key(session))) + // Owned by instanceScope so every private instance closes before Stage-1 globals tear down. const instances: LayerMap.LayerMap< ReturnType, Instance.Services, @@ -65,15 +68,11 @@ export function layer(options: Options, replacements: () => LayerNode.Replacemen Layer.unwrap( Effect.gen(function* () { const configuration = yield* options.configure(input.key).pipe(Effect.orDie) + // Instances read this selector and the host's Location map from the host context, so they never + // retain their Layer scopes; retaining the selector would block its shutdown on its own entries. return Instance.layer(input, { plugins: configuration.plugins, - replacements: [ - ...replacements(), - // Instances borrow this selector and the host's Location map instead of retaining - // their Layer scopes; retaining the selector would block its shutdown on its own entries. - Instance.node.replace(Layer.succeed(Instance.Service, { provide })), - LocationServiceMap.node.replace(Layer.succeed(LocationServiceMap.Service, locations)), - ], + host: yield* host, }).pipe( Layer.tap((context) => Effect.gen(function* () { @@ -96,10 +95,24 @@ export function layer(options: Options, replacements: () => LayerNode.Replacemen ).pipe( // Eviction can close the lookup's scope; do not make that fiber wait on itself. Layer.tapCause(() => - instances.invalidate(input).pipe(Effect.forkIn(scope, { startImmediately: true }), Effect.asVoid), + instances.invalidate(input).pipe(Effect.forkIn(instanceScope, { startImmediately: true }), Effect.asVoid), ), ), { idleTimeToLive: Duration.infinity }, + ).pipe(Scope.provide(instanceScope)) + // Close all open private instances concurrently before instanceScope tears down the RcMap and before + // Stage-1 globals release. + yield* Scope.addFinalizer( + instanceScope, + Effect.suspend(() => + instances.rcMap.state._tag === "Closed" + ? Effect.void + : Effect.forEach( + instances.rcMap.state.map, + ([, entry]) => Effect.exit(Scope.close(entry.scope, Exit.void)), + { concurrency: "unbounded", discard: true }, + ), + ), ) return Instance.Service.of({ provide, live: (session) => RcMap.has(instances.rcMap, key(session)) }) }), diff --git a/packages/sdk/test/instances-effect.test.ts b/packages/sdk/test/instances-effect.test.ts index 2e04d2fb216..17b16c95f82 100644 --- a/packages/sdk/test/instances-effect.test.ts +++ b/packages/sdk/test/instances-effect.test.ts @@ -6,7 +6,9 @@ import { TestLLM } from "@opencode/ai/testing" import { llmClient } from "@opencode/core/effect/app-node-platform" import { makeMemoryDriver } from "@opencode/core/environment/index" import { SessionRunnerModel } from "@opencode/core/session/runner/model" +import { SharedCache } from "@opencode/core/shared-cache" import { WorkspaceDriver } from "@opencode/core/workspace/driver" +import { EmbeddedHost } from "../src/internal/host" import { Plugin } from "@opencode/plugin/effect" import { Context, Deferred, Effect, Exit, Layer, Schema, Scope } from "effect" import { tmpdirScoped } from "../../core/test/fixture/tmpdir" @@ -100,7 +102,10 @@ it.live( overrides: [ llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { + select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), + resolve: () => Effect.succeed(model), + }), ), ], } @@ -193,7 +198,11 @@ it.live( overrides: [ llmClient.replace(Layer.succeed(LLMClient.Service, llm)), SessionRunnerModel.node.replace( - Layer.succeed(SessionRunnerModel.Service, { select: (session) => Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), resolve: () => Effect.succeed(model) }), + Layer.succeed(SessionRunnerModel.Service, { + select: (session) => + Effect.fail(new SessionRunnerModel.ModelNotSelectedError({ sessionID: session.id })), + resolve: () => Effect.succeed(model), + }), ), ], }, @@ -300,3 +309,45 @@ it.live( }), 15_000, ) + +it.live("closes private SDK instances before releasing Stage-1 host globals", () => + Effect.gen(function* () { + const directory = yield* tmpdirScoped() + const order: string[] = [] + const host = yield* EmbeddedHost.create( + { + config: { directory: directory.path, project: false, content: "{}" }, + models: { fetch: false }, + fs: { filewatcher: false }, + instances: { + key: (session) => metadata(session.metadata).threadID, + configure: () => + Effect.gen(function* () { + order.push("instance:acquire") + yield* Effect.addFinalizer(() => Effect.sync(() => order.push("instance:release"))) + return { plugins: [] } + }), + }, + }, + { + overrides: [ + SharedCache.node.replace( + SharedCache.node.mapLayer((layer) => + layer.pipe( + Layer.tap(() => Effect.addFinalizer(() => Effect.sync(() => order.push("global:SharedCache:release")))), + ), + ), + ), + ], + }, + ) + const session = yield* host.sessions.create({ + title: "Shutdown order fixture", + location: Location.Ref.make({ directory: AbsolutePath.make(directory.path) }), + metadata: { threadID: "thread-shutdown" }, + }) + yield* host.sessions.prompt({ sessionID: session.id, text: "Hello", resume: false }) + yield* Effect.promise(() => host.close()) + expect(order).toEqual(["instance:acquire", "instance:release", "global:SharedCache:release"]) + }), +) diff --git a/packages/server/src/routes.ts b/packages/server/src/routes.ts index 2d6c4a56007..ec29882ec90 100644 --- a/packages/server/src/routes.ts +++ b/packages/server/src/routes.ts @@ -129,9 +129,7 @@ export function createRoutes( return makeRoutes(options.password ? Option.some(options.password) : Option.none(), options, serviceURLs, overrides) } -type InstanceNode = ( - replacements: () => LayerNode.Replacements, -) => LayerNode.Provider +type InstanceNode = LayerNode.Provider export function createEmbeddedRoutes( options: ServerOptions = {}, @@ -207,15 +205,12 @@ function makeRoutes( }), ), ] - const build = (overrides: LayerNode.Replacements) => { - const replacements: LayerNode.Replacements = [ + const build = (overrides: LayerNode.Replacements) => + AppNodeBuilder.build(applicationServices, [ ...standard, - // Private instances resolve this list lazily so they inherit the complete host graph, including the selector. - ...(instances ? [Instance.node.replace(instances(() => replacements))] : []), + ...(instances ? [Instance.node.replace(instances)] : []), ...overrides, - ] - return AppNodeBuilder.build(applicationServices, replacements) - } + ]) const serviceLayer = options.simulation ? Layer.unwrap( Effect.gen(function* () { diff --git a/packages/server/src/workerd.ts b/packages/server/src/workerd.ts index ba12f191400..b136973c559 100644 --- a/packages/server/src/workerd.ts +++ b/packages/server/src/workerd.ts @@ -52,7 +52,7 @@ export interface Options { readonly password?: string /** Inline opencode config content (JSON), same as `ServerOptions.config.content`. */ readonly config?: { readonly content?: string } - /** models.dev catalog options; the bundled snapshot is the boot-time floor either way. */ + /** models.dev catalog options. Fetching is off by default, so a wake serves the bundled snapshot with no network. */ readonly models?: ServerOptions["models"] /** Replaces `globalThis.fetch` for OpenCode's own HTTP requests, e.g. to route them through a Service Binding. */ readonly fetch?: ServerOptions["fetch"] @@ -98,7 +98,7 @@ export function serverOptions(options: Options): ServerOptions { // cannot opt out of it, so this is not exposed as an option. events: { persist: true }, config: { content: options.config?.content }, - models: options.models, + models: { ...options.models, fetch: options.models?.fetch ?? false }, fetch: options.fetch, } } diff --git a/packages/server/test/workerd.test.ts b/packages/server/test/workerd.test.ts index 32e57dcba92..8ad7315e9db 100644 --- a/packages/server/test/workerd.test.ts +++ b/packages/server/test/workerd.test.ts @@ -54,6 +54,14 @@ it.live("boots the workerd profile over durable object storage", () => }), ) +it.effect("serves the bundled models.dev snapshot unless fetching is turned back on", () => + Effect.sync(() => { + const storage = makeDurableObjectStorage() + expect(ServerWorkerd.serverOptions({ storage }).models).toEqual({ fetch: false }) + expect(ServerWorkerd.serverOptions({ storage, models: { fetch: true } }).models).toEqual({ fetch: true }) + }), +) + it.effect("fails Npm.add with a clear workerd error instead of running the installer", () => Effect.gen(function* () { const npm = yield* Npm.Service diff --git a/packages/util/src/effect/layer-node.ts b/packages/util/src/effect/layer-node.ts index 529c60c576d..58a4d4c31cf 100644 --- a/packages/util/src/effect/layer-node.ts +++ b/packages/util/src/effect/layer-node.ts @@ -350,17 +350,77 @@ type Resolved = { readonly implementation: RuntimeLayer readonly dependencies: readonly Resolved[] readonly shared: boolean + readonly borrowed?: boolean +} + +export interface Host { + readonly tag: T + /** What the host built for the `tag` nodes its children reach (see `tagged`). */ + readonly context: Context.Context + /** The host's replacements: its `tag` ones are already built into `context`, the rest apply to children too. */ + readonly replacements?: Replacements +} + +export interface ChildOptions { + readonly host: Host + /** This child's own replacements, applied after `host.replacements`. They cannot target `host.tag` nodes. */ + readonly replacements?: Replacements +} + +/** Every `tag` node `root` reaches, after `replacements`, including transitive `tag` dependencies. */ +export function tagged(root: Graph, tag: Tag, replacements: Replacements = []) { + const targets = replacementTargets(replacements) + const seen = new Set() + const found: Graph[] = [] + const visit = (graph: AnyGraph): void => { + if (seen.has(graph)) return + seen.add(graph) + const replacement = targets.get(graph) + if (replacement && replacement !== graph) return visit(replacement) + if (graph instanceof NodeValue && graph.tag === tag) found.push(graph) + const definition = graph[GraphTypeId] + if (definition.kind !== "unbound") definition.dependencies.forEach(visit) + } + visit(root) + return found } /** Resolve the final overrides before validating or acquiring anything. Effect owns acquisition and finalization. */ export function compile(root: Graph, options: CompileOptions = {}): Layer.Layer { - const shared = options.shared - const replacements = new Map( - options.replacements?.map((item) => { + return compileGraph(root, options.replacements ?? [], options.shared) +} + +/** + * Compile a graph that stands on a host: every `host.tag` node reads its service from `host.context` instead of + * being built, so children never acquire, retain, or release the host's services. The rest is fresh for each build. + */ +export function compileChild(root: Graph, options: ChildOptions): Layer.Layer { + const own = options.replacements ?? [] + const rejected = own.find((item) => item[ReplacementTypeId].source.tag === options.host.tag) + if (rejected) { + throw new Error( + `Cannot replace ${rejected[ReplacementTypeId].source.name} in a child graph: its host builds ${options.host.tag} nodes`, + ) + } + return compileGraph(root, [...(options.host.replacements ?? []), ...own], undefined, options.host) +} + +function replacementTargets(replacements: Replacements) { + return new Map( + replacements.map((item) => { const replacement = item[ReplacementTypeId] return [replacement.source, replacement.target] as const }), ) +} + +function compileGraph( + root: Graph, + list: Replacements, + shared: Tag | undefined, + host?: Host, +): Layer.Layer { + const replacements = replacementTargets(list) const makeDomain = (isShared: boolean) => ({ shared: isShared, cache: new Map(), @@ -370,6 +430,8 @@ export function compile(root: Graph, options: CompileOptions = {}): const stack: AnyGraph[] = [] const resolveDefinition = (graph: AnyGraph, domain: ReturnType): readonly Resolved[] => { + // Host nodes keep their tag through any replacement, so the host's choice is already in its context. + if (host && graph instanceof NodeValue && graph.tag === host.tag) return [borrow(graph, host.context)] const replacement = replacements.get(graph) if (replacement && replacement !== graph) return resolve(replacement, domain) const definition = graph[GraphTypeId] @@ -421,10 +483,11 @@ export function compile(root: Graph, options: CompileOptions = {}): const roots = resolve(root) return Layer.fromBuild((memoMap, scope) => { - const local = shared === undefined ? memoMap : Layer.makeMemoMapUnsafe() + const local = shared === undefined && host === undefined ? memoMap : Layer.makeMemoMapUnsafe() const ambient = Layer.succeed(Layer.CurrentMemoMap, memoMap) const layers = new Map() const build = (node: Resolved): RuntimeLayer => { + if (node.borrowed) return node.implementation const cached = layers.get(node) if (cached) return cached const dependencies = node.dependencies.map(build) @@ -444,6 +507,22 @@ export function compile(root: Graph, options: CompileOptions = {}): }) as Layer.Layer } +function borrow(node: AnyNode, context: Context.Context): Resolved { + const service = node[GraphTypeId].service + const value = service && Context.getOrUndefined(context, service) + if (service && value === undefined) { + throw new Error(`Host context is missing ${node.name}; build it on the host before its children`) + } + return { + name: node.name, + // Side-effect-only host nodes (`service === undefined`) already ran on the host and expose no service output. + implementation: service ? Layer.succeedContext(Context.make(service, value)) : Layer.empty, + dependencies: [], + shared: false, + borrowed: true, + } +} + // The node's scope releases sequentially in reverse order, so a finalizer added before the build runs last and one // added after it runs first: together they bracket the release of everything this node acquired. The build must // not start before the first finalizer is added; Layer builds fork their scopes as soon as they are called.