GeezerVison is showing github.com — fix(core,opencode,tui): audit-v9 wave F — tombstone bounds, removal l… · anomalyco/opencode@887b912
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/core/src/event.ts +23-4Lines changed: 23 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -283,6 +283,26 @@ export interface LayerOptions { | 283 | 283 | readonly beforeAggregateRead?: (aggregateID: string) => Effect.Effect<void> | 284 | 284 | } | 285 | 285 |
| | 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 | + | 286 | 306 | // A durable wake coalesces payloads through a sliding(1) pubsub, so a terminal removal | 287 | 307 | // can be evicted by a later signal. The Deferred carries termination independently. | 288 | 308 | type DurableWake = { | @@ -300,9 +320,8 @@ export const layerWith = (options?: LayerOptions) => | 300 | 320 | typed: new Map<string, PubSub.PubSub<Payload>>(), | 301 | 321 | } | 302 | 322 | 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. | 306 | 325 | const removedAggregates = new Set<string>() | 307 | 326 | // TODO: Bind durable projectors to exact type+version before supporting incompatible historical payloads. | 308 | 327 | const listeners = new Array<Subscriber>() | @@ -691,7 +710,7 @@ export const layerWith = (options?: LayerOptions) => | 691 | 710 | .pipe(retryDurableWrite("event.remove"), Effect.orDie) | 692 | 711 | // Terminal null marker ends durable streams against a deleted log; the Deferred | 693 | 712 | // guarantees termination even when the sliding(1) wake evicts the null. | 694 | | - removedAggregates.add(aggregateID) | | 713 | + rememberRemoved(removedAggregates, aggregateID) | 695 | 714 | const wakes = pubsub.durable.get(aggregateID) | 696 | 715 | if (wakes) | 697 | 716 | yield* Effect.forEach( | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/test/event.test.ts +37-1Lines changed: 37 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 1 | | -import { describe, expect } from "bun:test" | | 1 | +import { describe, expect, test } from "bun:test" | 2 | 2 | import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Option, Schema, Stream } from "effect" | 3 | 3 | import { EventV2 } from "@opencode-ai/core/event" | 4 | 4 | import { Event } from "@opencode-ai/schema/event" | @@ -1196,6 +1196,24 @@ describe("EventV2", () => { | 1196 | 1196 | }), | 1197 | 1197 | ) | 1198 | 1198 |
| | 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 | + | 1199 | 1217 | it.effect("runs every live-only listener and the pubsub fan-out before re-raising the defect", () => | 1200 | 1218 | Effect.gen(function* () { | 1201 | 1219 | const events = yield* EventV2.Service | @@ -1318,3 +1336,21 @@ describe("EventV2", () => { | 1318 | 1336 | }), | 1319 | 1337 | ) | 1320 | 1338 | }) | | 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 Copy file name to clipboardExpand all lines: packages/opencode/src/project/instance-store.ts +53-14Lines changed: 53 additions & 14 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -34,8 +34,19 @@ interface Entry { | 34 | 34 | readonly deferred: Deferred.Deferred<InstanceContext> | 35 | 35 | /** Outstanding `provide` leases; a leased entry is never evicted (D-P1-05). */ | 36 | 36 | 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> | 37 | 41 | } | 38 | 42 |
| | 43 | +const makeEntry = (): Entry => ({ | | 44 | + deferred: Deferred.makeUnsafe<InstanceContext>(), | | 45 | + uses: 0, | | 46 | + disposed: false, | | 47 | + closed: Deferred.makeUnsafe<void>(), | | 48 | +}) | | 49 | + | 39 | 50 | const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Service> = Layer.effect( | 40 | 51 | Service, | 41 | 52 | Effect.gen(function* () { | @@ -116,10 +127,26 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 116 | 127 | const disposeEntry = Effect.fnUntraced(function* (directory: string, entry: Entry, ctx: InstanceContext) { | 117 | 128 | if (cache.get(directory) !== entry) return false | 118 | 129 | 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 | + ) | 123 | 150 | return true | 124 | 151 | }) | 125 | 152 |
| @@ -148,7 +175,7 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 148 | 175 | } | 149 | 176 |
| 150 | 177 | yield* evictStale() | 151 | | - const entry: Entry = { deferred: Deferred.makeUnsafe<InstanceContext>(), uses: 0 } | | 178 | + const entry = makeEntry() | 152 | 179 | cache.set(directory, entry) | 153 | 180 | yield* Effect.gen(function* () { | 154 | 181 | yield* Effect.logInfo("creating instance", { directory: directory }) | @@ -170,16 +197,17 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 170 | 197 | return Effect.uninterruptibleMask((restore) => | 171 | 198 | Effect.gen(function* () { | 172 | 199 | const previous = cache.get(directory) | | 200 | + const reusable = previous && !previous.disposed ? previous : undefined | 173 | 201 | // A reload for a directory not already cached adds an entry like `load`, so it | 174 | 202 | // 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() | 177 | 205 | cache.set(directory, entry) | 178 | 206 | yield* Effect.gen(function* () { | 179 | 207 | 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) | 183 | 211 | yield* Effect.promise(() => runDisposers(directory)) | 184 | 212 | yield* emitDisposed({ directory, project: input.project?.id }) | 185 | 213 | } | @@ -209,6 +237,10 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 209 | 237 | yield* disposeEntry(directory, entry, exit.value).pipe(Effect.asVoid) | 210 | 238 | }) | 211 | 239 |
| | 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). | 212 | 244 | const disposeAllOnce = Effect.fnUntraced(function* () { | 213 | 245 | yield* Effect.logInfo("disposing all instances") | 214 | 246 | yield* Effect.forEach( | @@ -234,15 +266,22 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser | 234 | 266 |
| 235 | 267 | const provide = <A, E, R>(input: LoadInput, effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => | 236 | 268 | 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 | + } | 238 | 277 | // Hold the lease on the exact entry the effect is using, not whatever the cache | 239 | 278 | // holds now, so a concurrent reload cannot make the lease land on the wrong entry. | 240 | | - entry.uses += 1 | | 279 | + loaded.entry.uses += 1 | 241 | 280 | return yield* effect.pipe( | 242 | | - Effect.provideService(InstanceRef, ctx), | | 281 | + Effect.provideService(InstanceRef, loaded.ctx), | 243 | 282 | Effect.ensuring( | 244 | 283 | Effect.sync(() => { | 245 | | - entry.uses = Math.max(0, entry.uses - 1) | | 284 | + loaded.entry.uses = Math.max(0, loaded.entry.uses - 1) | 246 | 285 | }), | 247 | 286 | ), | 248 | 287 | ) | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/src/share/share-next.ts +28-7Lines changed: 28 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -151,14 +151,35 @@ function sweepMaps(s: State) { | 151 | 151 | boundQueueMaps(s.queue, s.shared, s) | 152 | 152 | } | 153 | 153 |
| 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() | 159 | 170 | if (oldest.done) break | 160 | | - s.removals.delete(oldest.value) | | 171 | + removals.delete(oldest.value) | | 172 | + evicted.push(oldest.value) | 161 | 173 | } | | 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 | + }) | 162 | 183 | } | 163 | 184 |
| 164 | 185 | type Data = | @@ -698,7 +719,7 @@ const layer = Layer.effect( | 698 | 719 | ) | 699 | 720 |
| 700 | 721 | if (Exit.isFailure(result)) { | 701 | | - rememberRemoval(s, sessionID, share) | | 722 | + yield* reportRemovalEviction(rememberRemoval(s.removals, sessionID, share)) | 702 | 723 | yield* Effect.logWarning("failed to remove share", { sessionID: sessionID, cause: result.cause }) | 703 | 724 | } else { | 704 | 725 | s.removals.delete(sessionID) | |
Collapse file Copy file name to clipboardExpand all lines: packages/opencode/test/project/instance.test.ts +44Lines changed: 44 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -106,6 +106,10 @@ describe("InstanceStore", () => { | 106 | 106 | yield* Deferred.succeed(release, undefined) | 107 | 107 | yield* Fiber.join(fiber) | 108 | 108 | }), | | 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 }, | 109 | 113 | ) | 110 | 114 |
| 111 | 115 | it.live("runs bootstrap with InstanceRef provided", () => | @@ -402,4 +406,44 @@ describe("InstanceStore", () => { | 402 | 406 | expect(disposed).toEqual([dir]) | 403 | 407 | }), | 404 | 408 | ) | | 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 | + ) | 405 | 449 | }) |
|