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,opencode,tui): audit-v9 wave F — tombstone bounds, removal l… · anomalyco/opencode@887b912

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • core
      • src
        • event.ts
      • test
        • event.test.ts
    • opencode
      • src
        • project
          • instance-store.ts
        • share
          • share-next.ts
      • test
        • project
          • instance.test.ts
        • share
          • share-next.test.ts
    • tui
      • src/context
        • sync.tsx
      • test/cli/cmd/tui
        • sync.test.tsx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/event.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/event.ts
+23-4Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,26 @@ export interface LayerOptions {
283283
readonly beforeAggregateRead?: (aggregateID: string) => Effect.Effect<void>
284284
}
285285

286+
// Aggregates removed by `remove()` are tombstoned so a durable stream created afterwards
287+
// ends immediately instead of parking on a wake that will never receive a null (v8 NEW-07).
288+
// The tombstone is bounded: a workload that removes many aggregates without ever re-creating
289+
// them would otherwise grow it for the process lifetime (v9 NEW-V9-05). Oldest removals are
290+
// evicted first, so the newest removes stay terminal. Residual: a `durable()` created after
291+
// more than MAX_REMOVED_AGGREGATES later removes on that same aggregate can park again, which
292+
// is preferable to unbounded growth; re-creating the aggregate clears the tombstone either way.
293+
export const MAX_REMOVED_AGGREGATES = 4_096
294+
295+
export function rememberRemoved(removed: Set<string>, aggregateID: string, max = MAX_REMOVED_AGGREGATES) {
296+
// Re-insert so eviction order tracks the latest removal, then drop the oldest tombstones.
297+
removed.delete(aggregateID)
298+
removed.add(aggregateID)
299+
while (removed.size > max) {
300+
const oldest = removed.values().next()
301+
if (oldest.done) break
302+
removed.delete(oldest.value)
303+
}
304+
}
305+
286306
// A durable wake coalesces payloads through a sliding(1) pubsub, so a terminal removal
287307
// can be evicted by a later signal. The Deferred carries termination independently.
288308
type DurableWake = {
@@ -300,9 +320,8 @@ export const layerWith = (options?: LayerOptions) =>
300320
typed: new Map<string, PubSub.PubSub<Payload>>(),
301321
}
302322
const projectors = new Map<string, Subscriber[]>()
303-
// Aggregates removed by `remove()`: a durable stream created afterwards must end
304-
// immediately instead of parking on a wake that will never receive a null. Cleared
305-
// when the aggregate is re-created by a later commit (v8 NEW-07).
323+
// Tombstones for `remove()`d aggregates; bounded by `rememberRemoved`. Cleared when
324+
// the aggregate is re-created by a later commit.
306325
const removedAggregates = new Set<string>()
307326
// TODO: Bind durable projectors to exact type+version before supporting incompatible historical payloads.
308327
const listeners = new Array<Subscriber>()
@@ -691,7 +710,7 @@ export const layerWith = (options?: LayerOptions) =>
691710
.pipe(retryDurableWrite("event.remove"), Effect.orDie)
692711
// Terminal null marker ends durable streams against a deleted log; the Deferred
693712
// guarantees termination even when the sliding(1) wake evicts the null.
694-
removedAggregates.add(aggregateID)
713+
rememberRemoved(removedAggregates, aggregateID)
695714
const wakes = pubsub.durable.get(aggregateID)
696715
if (wakes)
697716
yield* Effect.forEach(
Collapse file

‎packages/core/test/event.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/event.test.ts
+37-1Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect } from "bun:test"
1+
import { describe, expect, test } from "bun:test"
22
import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Option, Schema, Stream } from "effect"
33
import { EventV2 } from "@opencode-ai/core/event"
44
import { Event } from "@opencode-ai/schema/event"
@@ -1196,6 +1196,24 @@ describe("EventV2", () => {
11961196
}),
11971197
)
11981198

1199+
it.effect("ends a durable stream for the most recent of many removals", () =>
1200+
Effect.gen(function* () {
1201+
const events = yield* EventV2.Service
1202+
const removed = Array.from({ length: 4 }, () => Session.ID.create())
1203+
for (const aggregateID of removed) {
1204+
yield* events.publish(DurableMessage, durableData(aggregateID, "seed"))
1205+
yield* events.remove(aggregateID)
1206+
}
1207+
1208+
const result = yield* events
1209+
.durable({ aggregateID: removed.at(-1)! })
1210+
.pipe(Stream.runCollect, Effect.timeoutOption("1 second"))
1211+
1212+
expect(Option.isSome(result)).toBe(true)
1213+
if (Option.isSome(result)) expect(Array.from(result.value)).toEqual([])
1214+
}),
1215+
)
1216+
11991217
it.effect("runs every live-only listener and the pubsub fan-out before re-raising the defect", () =>
12001218
Effect.gen(function* () {
12011219
const events = yield* EventV2.Service
@@ -1318,3 +1336,21 @@ describe("EventV2", () => {
13181336
}),
13191337
)
13201338
})
1339+
1340+
describe("EventV2.rememberRemoved", () => {
1341+
test("bounds the tombstone, evicting the oldest removals first", () => {
1342+
const removed = new Set<string>()
1343+
for (let index = 0; index < 5; index++) EventV2.rememberRemoved(removed, `ses_${index}`, 3)
1344+
1345+
expect([...removed]).toEqual(["ses_2", "ses_3", "ses_4"])
1346+
})
1347+
1348+
test("moves a re-removed aggregate to the newest position", () => {
1349+
const removed = new Set<string>()
1350+
EventV2.rememberRemoved(removed, "ses_a", 2)
1351+
EventV2.rememberRemoved(removed, "ses_b", 2)
1352+
EventV2.rememberRemoved(removed, "ses_a", 2)
1353+
1354+
expect([...removed]).toEqual(["ses_b", "ses_a"])
1355+
})
1356+
})
Collapse file

‎packages/opencode/src/project/instance-store.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/project/instance-store.ts
+53-14Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,19 @@ interface Entry {
3434
readonly deferred: Deferred.Deferred<InstanceContext>
3535
/** Outstanding `provide` leases; a leased entry is never evicted (D-P1-05). */
3636
uses: number
37+
/** Set synchronously once a teardown claims the entry; a `provide` that observes it reloads. */
38+
disposed: boolean
39+
/** Resolves when a claimed teardown finished and the entry left the cache. */
40+
readonly closed: Deferred.Deferred<void>
3741
}
3842

43+
const makeEntry = (): Entry => ({
44+
deferred: Deferred.makeUnsafe<InstanceContext>(),
45+
uses: 0,
46+
disposed: false,
47+
closed: Deferred.makeUnsafe<void>(),
48+
})
49+
3950
const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Service> = Layer.effect(
4051
Service,
4152
Effect.gen(function* () {
@@ -116,10 +127,26 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
116127
const disposeEntry = Effect.fnUntraced(function* (directory: string, entry: Entry, ctx: InstanceContext) {
117128
if (cache.get(directory) !== entry) return false
118129
yield* awaitLease(entry)
119-
if (cache.get(directory) !== entry) return false
120-
yield* disposeContext(ctx)
121-
if (cache.get(directory) !== entry) return false
122-
cache.delete(directory)
130+
// Claim the entry in one synchronous step. A `provide` may have leased it after
131+
// `awaitLease` observed `uses === 0`; both this claim and `provide`'s check-and-increment
132+
// are synchronous critical sections, so whichever runs first is observed by the other.
133+
// If a lease landed, leave the entry alive rather than tearing down under it (W5).
134+
const claimed = yield* Effect.sync(() => {
135+
if (cache.get(directory) !== entry) return false
136+
if (entry.disposed) return false
137+
if (entry.uses > 0) return false
138+
entry.disposed = true
139+
return true
140+
})
141+
if (!claimed) return false
142+
yield* disposeContext(ctx).pipe(
143+
Effect.ensuring(
144+
Effect.gen(function* () {
145+
if (cache.get(directory) === entry) cache.delete(directory)
146+
yield* Deferred.succeed(entry.closed, undefined)
147+
}),
148+
),
149+
)
123150
return true
124151
})
125152

@@ -148,7 +175,7 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
148175
}
149176

150177
yield* evictStale()
151-
const entry: Entry = { deferred: Deferred.makeUnsafe<InstanceContext>(), uses: 0 }
178+
const entry = makeEntry()
152179
cache.set(directory, entry)
153180
yield* Effect.gen(function* () {
154181
yield* Effect.logInfo("creating instance", { directory: directory })
@@ -170,16 +197,17 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
170197
return Effect.uninterruptibleMask((restore) =>
171198
Effect.gen(function* () {
172199
const previous = cache.get(directory)
200+
const reusable = previous && !previous.disposed ? previous : undefined
173201
// A reload for a directory not already cached adds an entry like `load`, so it
174202
// must enforce the bound too; a replacement keeps the size unchanged.
175-
if (!previous) yield* evictStale()
176-
const entry: Entry = { deferred: Deferred.makeUnsafe<InstanceContext>(), uses: 0 }
203+
if (!reusable) yield* evictStale()
204+
const entry = makeEntry()
177205
cache.set(directory, entry)
178206
yield* Effect.gen(function* () {
179207
yield* Effect.logInfo("reloading instance", { directory: directory })
180-
if (previous) {
181-
yield* Deferred.await(previous.deferred).pipe(Effect.ignore)
182-
yield* awaitLease(previous)
208+
if (reusable) {
209+
yield* Deferred.await(reusable.deferred).pipe(Effect.ignore)
210+
yield* awaitLease(reusable)
183211
yield* Effect.promise(() => runDisposers(directory))
184212
yield* emitDisposed({ directory, project: input.project?.id })
185213
}
@@ -209,6 +237,10 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
209237
yield* disposeEntry(directory, entry, exit.value).pipe(Effect.asVoid)
210238
})
211239

240+
// Runs entries sequentially: each `disposeEntry` may wait up to LEASE_DRAIN_TIMEOUT_MS for a
241+
// lease to drain, so the worst case is MAX_CACHED_INSTANCES * 2 s (~32 s) during explicit
242+
// shutdown. Parallelising would shorten it but changes teardown ordering, so the bound is
243+
// documented rather than changed here (W5/F4c).
212244
const disposeAllOnce = Effect.fnUntraced(function* () {
213245
yield* Effect.logInfo("disposing all instances")
214246
yield* Effect.forEach(
@@ -234,15 +266,22 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
234266

235267
const provide = <A, E, R>(input: LoadInput, effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
236268
Effect.gen(function* () {
237-
const { ctx, entry } = yield* loadEntry(input)
269+
const loaded = yield* loadEntry(input)
270+
// A teardown may have claimed this entry between `loadEntry` returning it and the
271+
// lease increment; wait for that teardown to finish, then load a fresh entry rather
272+
// than run against a disposed context (W5).
273+
if (loaded.entry.disposed) {
274+
yield* Deferred.await(loaded.entry.closed)
275+
return yield* provide(input, effect)
276+
}
238277
// Hold the lease on the exact entry the effect is using, not whatever the cache
239278
// holds now, so a concurrent reload cannot make the lease land on the wrong entry.
240-
entry.uses += 1
279+
loaded.entry.uses += 1
241280
return yield* effect.pipe(
242-
Effect.provideService(InstanceRef, ctx),
281+
Effect.provideService(InstanceRef, loaded.ctx),
243282
Effect.ensuring(
244283
Effect.sync(() => {
245-
entry.uses = Math.max(0, entry.uses - 1)
284+
loaded.entry.uses = Math.max(0, loaded.entry.uses - 1)
246285
}),
247286
),
248287
)
Collapse file

‎packages/opencode/src/share/share-next.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/share/share-next.ts
+28-7Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -151,14 +151,35 @@ function sweepMaps(s: State) {
151151
boundQueueMaps(s.queue, s.shared, s)
152152
}
153153

154-
function rememberRemoval(s: State, sessionID: SessionID, share: Share) {
155-
s.removals.delete(sessionID)
156-
s.removals.set(sessionID, share)
157-
while (s.removals.size > MAX_REMOVALS) {
158-
const oldest = s.removals.keys().next()
154+
// Every entry here is a DELETE that is still pending, so the cap can only drop pending
155+
// work; it drops the oldest first, keeping the most recent failures (the ones a live client
156+
// is most likely waiting on). Residual: a dropped tombstone is no longer retried in this
157+
// process, so if its share is still readable it stays that way until a reconnect or restart.
158+
// The alternative is unbounded growth, which the bound exists to prevent (v9 NEW-V9-06).
159+
export function rememberRemoval(
160+
removals: Map<SessionID, Share>,
161+
sessionID: SessionID,
162+
share: Share,
163+
max = MAX_REMOVALS,
164+
) {
165+
removals.delete(sessionID)
166+
removals.set(sessionID, share)
167+
const evicted: SessionID[] = []
168+
while (removals.size > max) {
169+
const oldest = removals.keys().next()
159170
if (oldest.done) break
160-
s.removals.delete(oldest.value)
171+
removals.delete(oldest.value)
172+
evicted.push(oldest.value)
161173
}
174+
return evicted
175+
}
176+
177+
export function reportRemovalEviction(evicted: ReadonlyArray<SessionID>) {
178+
if (evicted.length === 0) return Effect.void
179+
return Effect.logWarning("share removal tombstones capped; oldest pending remote deletes dropped", {
180+
dropped: evicted.length,
181+
sessionIDs: evicted,
182+
})
162183
}
163184

164185
type Data =
@@ -698,7 +719,7 @@ const layer = Layer.effect(
698719
)
699720

700721
if (Exit.isFailure(result)) {
701-
rememberRemoval(s, sessionID, share)
722+
yield* reportRemovalEviction(rememberRemoval(s.removals, sessionID, share))
702723
yield* Effect.logWarning("failed to remove share", { sessionID: sessionID, cause: result.cause })
703724
} else {
704725
s.removals.delete(sessionID)
Collapse file

‎packages/opencode/test/project/instance.test.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/test/project/instance.test.ts
+44Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ describe("InstanceStore", () => {
106106
yield* Deferred.succeed(release, undefined)
107107
yield* Fiber.join(fiber)
108108
}),
109+
// 17 real git worktrees; under concurrent load the default 5 s budget is too tight, so
110+
// give the setup an explicit budget instead of flaking (v9 F4b). The ordering itself is
111+
// deterministic: `held` guards the lease and `store.load` awaits the eviction.
112+
{ timeout: 15_000 },
109113
)
110114

111115
it.live("runs bootstrap with InstanceRef provided", () =>
@@ -402,4 +406,44 @@ describe("InstanceStore", () => {
402406
expect(disposed).toEqual([dir])
403407
}),
404408
)
409+
410+
it.live("reloads instead of leasing an instance that is already being disposed", () =>
411+
Effect.gen(function* () {
412+
const dir = yield* tmpdirScoped({ git: true })
413+
const store = yield* InstanceStore.Service
414+
const disposed: string[] = []
415+
const disposing = yield* Deferred.make<void>()
416+
const releaseDispose = yield* Deferred.make<() => void>()
417+
yield* registerDisposerScoped((directory) => {
418+
disposed.push(directory)
419+
Deferred.doneUnsafe(disposing, Effect.void)
420+
return new Promise<void>((resolve) => {
421+
Deferred.doneUnsafe(releaseDispose, Effect.succeed(resolve))
422+
})
423+
})
424+
425+
const ctx = yield* store.load({ directory: dir })
426+
const disposingFiber = yield* store.dispose(ctx).pipe(Effect.forkScoped)
427+
yield* Deferred.await(disposing)
428+
429+
let captured: unknown
430+
const provided = yield* store
431+
.provide(
432+
{ directory: dir },
433+
Effect.gen(function* () {
434+
captured = yield* InstanceRef
435+
}),
436+
)
437+
.pipe(Effect.forkScoped)
438+
439+
const release = yield* Deferred.await(releaseDispose)
440+
yield* Effect.sync(release)
441+
yield* Fiber.join(disposingFiber)
442+
yield* Fiber.join(provided)
443+
444+
expect(disposed).toEqual([dir])
445+
expect(captured).toBeDefined()
446+
expect(captured).not.toBe(ctx)
447+
}),
448+
)
405449
})

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.