Skip to content

Commit 6400201

Browse files
sahrizviclaude
andcommitted
release: v0.9.6 review round 2 — self-heal dispatcher after stale register()
Addresses second round of coderabbit + cubic findings on release/v0.9.6: - **cubic P2 (dispatcher.ts)** — the previous generation guard prevented a stale hook's `.then` handler from mutating shared state, but the old hook BODY itself could still `Dispatcher.register()` late and clobber fresh entries a newer hook had already written. Fix: on stale-generation success, clear `_registrationPromise` so the next `Dispatcher.call` re-runs the CURRENT hook — its `register()` calls then idempotently overwrite whatever the stale hook wrote. Successful current-generation attempts keep the resolved promise memoized so subsequent calls fast-path through an already-settled await. - **cubic P3 (test file)** — replaced every `setTimeout` sync point with Promise-gate synchronisation. Bun's `async` function bodies run sync until the first `await`, so `Dispatcher.call(...)` has already registered its cached promise and hit `await _registrationPromise` by the time control returns to us — no external delay needed. Tests are now scheduler-independent. - **cubic P3 (docs/usage/check.md)** — rewrote the dangling "and how the rule inventory is discovered in practice" clause. Now links to the Finding Object schema and calls out which check types always vs sometimes include `rule`. - New adversarial test covering the stale-register self-heal path; full dispatcher suite: 15/15 pass. Non-vacuous: verified the new test FAILS if the P2 fix is reverted. Co-Authored-By: Claude Opus 4.7 <[email protected]>
1 parent 3645a9d commit 6400201

3 files changed

Lines changed: 99 additions & 60 deletions

File tree

‎docs/docs/usage/check.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ altimate-code check --fail-on warning
5050
| `semantic` | Semantic validation (cartesian products, wrong JOINs) | Optional | No |
5151
| `grade` | SQL quality grading with recommendations | Optional | No |
5252

53-
Findings carry a machine-readable `rule` field (e.g. `unbalanced_quote`, `sql_injection`, `L003`) when the underlying engine attaches one — visible in `--format json` output, and how the rule inventory is discovered in practice. A minority of `lint` findings may arrive without `rule` (or `code`); switch on presence, not a hard assumption.
53+
Findings usually carry a machine-readable `rule` field (e.g. `unbalanced_quote`, `sql_injection`, `L003`) visible in `--format json` output — see the [Finding Object](#finding-object) schema below. `safety` and `policy` findings always include one; `lint` findings may omit both `rule` and `code` if the engine didn't attach them, so switch on presence rather than assuming.
5454

5555
By default, `lint` and `safety` are enabled. Override with `--checks`:
5656

‎packages/opencode/src/altimate/native/dispatcher.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,18 @@ export async function call<M extends BridgeMethod>(
6767
const generation = ++_registrationGeneration
6868
_registrationPromise = fn().then(
6969
() => {
70-
if (generation === _registrationGeneration) _ensureRegistered = null
70+
// Generation advanced while this attempt was in flight (concurrent
71+
// ``reset()``/``setRegistrationHook()`` + another call arrived).
72+
// The stale hook body may have written stale entries into
73+
// ``nativeHandlers`` via late ``register()`` calls, clobbering the
74+
// newer hook's. Clear ``_registrationPromise`` so the NEXT
75+
// ``Dispatcher.call`` re-runs the current hook — its ``register()``
76+
// calls then overwrite whatever the stale hook wrote. Hook bodies
77+
// must be idempotent (they are today — ``register`` is a plain
78+
// ``Map.set``). Successful current-generation attempts leave the
79+
// resolved promise memoized so subsequent calls fast-path through
80+
// an already-settled ``await``. (cubic round 2 on release/v0.9.6.)
81+
if (generation !== _registrationGeneration) _registrationPromise = null
7182
},
7283
(err) => {
7384
if (generation === _registrationGeneration) _registrationPromise = null

‎packages/opencode/test/skill/release-v0.9.6-adversarial.test.ts‎

Lines changed: 86 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,22 @@
33
*
44
* Focus: fixes that landed IN this release (not the whole PR history) —
55
* 1. Dispatcher retry-after-registration-failure (v0.9.6 review gremlin fix)
6-
* 2. Truncation cleanup: fail-safe on stat error, mtime-based aging
6+
* 2. Dispatcher generation guard (coderabbit round 1)
7+
* 3. Dispatcher stale-register self-heal (cubic round 2)
78
*
89
* Not covered here (existing test suites are authoritative):
910
* - altimate-core 0.7.0 shape corrections — see
10-
* packages/opencode/test/altimate/altimate-core-e2e.test.ts (26 files,
11-
* real-engine "consumer contract sync" blocks land there)
11+
* packages/opencode/test/altimate/altimate-core-e2e.test.ts
1212
* - Truncation ID-wrap regression — see
1313
* packages/opencode/test/tool/truncation.test.ts
14+
*
15+
* Scheduling discipline: these tests never use ``setTimeout``. Every
16+
* synchronisation point is a Promise gate that the test controls, so the
17+
* ordering is deterministic regardless of the underlying scheduler. Bun's
18+
* ``async`` function bodies run synchronously until the first ``await``, so
19+
* ``Dispatcher.call(...)`` has already registered its cached promise and
20+
* hit ``await _registrationPromise`` by the time control returns to us —
21+
* we can immediately act on shared state without racing the call's setup.
1422
*/
1523
import { afterEach, beforeAll, afterAll, beforeEach, describe, expect, test } from "bun:test"
1624

@@ -47,7 +55,6 @@ describe("v0.9.6 release: Dispatcher registration retry", () => {
4755
Dispatcher.register("ping", async () => ({ status: "recovered" }))
4856
})
4957

50-
// First call: registration fails, error propagates.
5158
await expect(Dispatcher.call("ping", {} as any)).rejects.toThrow(
5259
"simulated NAPI load failure",
5360
)
@@ -61,37 +68,36 @@ describe("v0.9.6 release: Dispatcher registration retry", () => {
6168
expect(attempts).toBe(2)
6269
})
6370

64-
test("concurrent calls share ONE registration attempt on both success and failure", async () => {
65-
// Guard the dedup property — the fix caches the in-flight promise so
66-
// 100 racing calls trigger the hook exactly once, not 100 times.
71+
test("concurrent calls share ONE registration attempt", async () => {
72+
// Fires 20 concurrent calls before the hook completes; asserts the
73+
// hook body ran exactly once. All 20 Dispatcher.call invocations run
74+
// sync-then-yield in a row, so by the time the array is populated
75+
// every caller is already awaiting the shared _registrationPromise —
76+
// no external synchronisation needed.
6777
let attempts = 0
6878
let resolveRegistration: () => void = () => {}
69-
const registrationGate = new Promise<void>((resolve) => {
70-
resolveRegistration = resolve
71-
})
79+
const registrationGate = new Promise<void>((r) => (resolveRegistration = r))
7280
Dispatcher.setRegistrationHook(async () => {
7381
attempts += 1
7482
await registrationGate
7583
Dispatcher.register("ping", async () => ({ status: "ok" }))
7684
})
7785

78-
// Fire 20 concurrent calls before registration completes.
7986
const calls = Array.from({ length: 20 }, () => Dispatcher.call("ping", {} as any))
80-
// Let the concurrent callers all enter the registration branch.
81-
await new Promise((r) => setTimeout(r, 10))
8287
resolveRegistration()
83-
8488
const results = await Promise.all(calls)
89+
8590
expect(results).toHaveLength(20)
8691
for (const r of results) expect(r).toEqual({ status: "ok" })
8792
// Critical: the hook fired exactly ONCE despite 20 concurrent callers.
8893
expect(attempts).toBe(1)
8994
})
9095

91-
test("successful registration clears the hook — a later call does NOT re-run it", async () => {
92-
// Guard against overcorrection: the fix must still short-circuit after
93-
// success, otherwise every subsequent call would eagerly re-import all
94-
// handler modules for no reason.
96+
test("successful registration is memoized — a later call does NOT re-run the hook", async () => {
97+
// Guard against overcorrection: once the current-generation hook has
98+
// completed, the resolved _registrationPromise memoizes success so
99+
// subsequent calls fast-path through an already-settled await instead
100+
// of re-importing all handler modules for no reason.
95101
let attempts = 0
96102
Dispatcher.setRegistrationHook(async () => {
97103
attempts += 1
@@ -100,68 +106,53 @@ describe("v0.9.6 release: Dispatcher registration retry", () => {
100106

101107
await Dispatcher.call("ping", {} as any)
102108
expect(attempts).toBe(1)
103-
104-
// Later call: hook must NOT re-run (it was cleared on success).
105109
await Dispatcher.call("ping", {} as any)
106110
expect(attempts).toBe(1)
107111
})
108112

109-
test("reset() while a hook is pending — stale success does NOT clobber the reset state (generation guard)", async () => {
110-
// coderabbit round 1 catch on release/v0.9.6: without a generation guard,
111-
// an old registration attempt's success handler nulls _ensureRegistered,
112-
// wiping out a replacement hook that reset() installed mid-flight. Later
113-
// calls then skip registration entirely and see stale (empty) state.
113+
test("reset() while a hook is pending — stale success does NOT clobber the replacement (generation guard)", async () => {
114+
// coderabbit round 1 on release/v0.9.6: without a generation guard,
115+
// an old attempt's success handler would null _ensureRegistered even
116+
// after reset() + setRegistrationHook() had installed a replacement,
117+
// wiping it out and causing later calls to skip registration.
114118
let resolvePending: () => void = () => {}
115119
const pending = new Promise<void>((r) => (resolvePending = r))
116120
Dispatcher.setRegistrationHook(async () => {
117121
await pending
118122
Dispatcher.register("ping", async () => ({ status: "old-hook-ran" }))
119123
})
120124

121-
// Start the first call — hook attempt is now in flight, awaiting `pending`.
125+
// Dispatcher.call runs sync until its first await, so by the time this
126+
// returns the call is already blocked on _registrationPromise and we
127+
// can safely mutate shared state without a race.
122128
const firstCall = Dispatcher.call("ping", {} as any)
123-
await new Promise((r) => setTimeout(r, 5))
124129

125-
// Concurrent reset + install a REPLACEMENT hook. Without generation guard,
126-
// when the pending attempt finally resolves, it will null _ensureRegistered
127-
// — clobbering the replacement.
128130
Dispatcher.reset()
129131
let replacementRan = false
130132
Dispatcher.setRegistrationHook(async () => {
131133
replacementRan = true
132134
Dispatcher.register("ping", async () => ({ status: "replacement" }))
133135
})
134136

135-
// Let the old attempt resolve. Its success handler must skip the mutation
136-
// because the generation has advanced twice (reset + setRegistrationHook).
137137
resolvePending()
138-
await firstCall.catch(() => {}) // may reject or resolve; doesn't matter here
138+
await firstCall.catch(() => {})
139139

140-
// A new call should invoke the REPLACEMENT hook, not skip registration.
141140
const result = await Dispatcher.call("ping", {} as any)
142141
expect(replacementRan).toBe(true)
143142
expect(result).toEqual({ status: "replacement" })
144143
})
145144

146145
test("setRegistrationHook() while a hook is pending — stale failure does NOT clobber the new in-flight promise", async () => {
147-
// Companion to the previous case: the failure handler also mutates
148-
// shared state (_registrationPromise = null), so it needs the same guard.
149-
// Scenario: old hook is failing, but during its await, setRegistrationHook
150-
// installs a new hook AND a new call kicks off a new registration
151-
// promise. Without the guard, the old attempt's failure handler nulls
152-
// the NEW _registrationPromise mid-flight, breaking dedup for anyone
153-
// else awaiting it.
146+
// Failure handler also mutates shared state (_registrationPromise = null),
147+
// so it needs the same generation guard. Otherwise a stale failure
148+
// clears a newer in-flight promise, breaking dedup for anyone awaiting it.
154149
let rejectOld: (err: Error) => void = () => {}
155150
const oldPending = new Promise<void>((_, rej) => (rejectOld = rej))
156151
Dispatcher.setRegistrationHook(async () => {
157152
await oldPending
158153
})
159-
160-
// Start first call — will fail once we reject.
161154
const firstCall = Dispatcher.call("ping", {} as any)
162-
await new Promise((r) => setTimeout(r, 5))
163155

164-
// Install new hook; kick off a second call which caches its own promise.
165156
let newHookAttempts = 0
166157
let resolveNew: () => void = () => {}
167158
const newPending = new Promise<void>((r) => (resolveNew = r))
@@ -171,32 +162,71 @@ describe("v0.9.6 release: Dispatcher registration retry", () => {
171162
Dispatcher.register("ping", async () => ({ status: "new-hook-ran" }))
172163
})
173164
const secondCall = Dispatcher.call("ping", {} as any)
174-
await new Promise((r) => setTimeout(r, 5))
175165

176-
// Reject the old attempt. Its failure handler must NOT null the second
177-
// call's cached promise.
178166
rejectOld(new Error("old attempt failed"))
179167
await firstCall.catch(() => {})
180168

181-
// Third caller arrives — should share the second call's still-cached
169+
// Third caller arrives — must share the second call's still-cached
182170
// promise (dedup works), not start a third registration attempt.
183171
const thirdCall = Dispatcher.call("ping", {} as any)
184172
resolveNew()
185173

186174
const [r2, r3] = await Promise.all([secondCall, thirdCall])
187175
expect(r2).toEqual({ status: "new-hook-ran" })
188176
expect(r3).toEqual({ status: "new-hook-ran" })
189-
// Critical: new hook fired ONCE despite second + third call both
190-
// dedup-sharing its promise, proving the stale failure handler didn't
191-
// null the cached promise and let a third attempt start.
177+
// Critical: new hook fired ONCE despite second + third both dedup-sharing
178+
// its promise — proving the stale failure handler didn't null the cache.
192179
expect(newHookAttempts).toBe(1)
193180
})
194181

182+
test("stale hook's LATE register() call is self-healed by a re-run on the next call", async () => {
183+
// cubic round 2 on release/v0.9.6: the generation guard prevented a
184+
// stale success handler from mutating _ensureRegistered / _registrationPromise,
185+
// but the old HOOK BODY itself could still write stale entries into
186+
// nativeHandlers via late register() calls after a new hook had already
187+
// filled them. Fix: on stale-generation success, clear _registrationPromise
188+
// so the next Dispatcher.call re-runs the CURRENT hook and its idempotent
189+
// register() calls overwrite whatever the stale hook wrote.
190+
let resolveOld: () => void = () => {}
191+
const oldPending = new Promise<void>((r) => (resolveOld = r))
192+
Dispatcher.setRegistrationHook(async () => {
193+
await oldPending
194+
Dispatcher.register("ping", async () => ({ status: "stale-old" }))
195+
})
196+
const firstCall = Dispatcher.call("ping", {} as any)
197+
198+
Dispatcher.reset()
199+
let newRunCount = 0
200+
Dispatcher.setRegistrationHook(async () => {
201+
newRunCount += 1
202+
Dispatcher.register("ping", async () => ({ status: "fresh-new" }))
203+
})
204+
205+
// Second call runs the new (fast) hook to completion — registers
206+
// "ping" -> fresh-new, memoized as the resolved promise.
207+
const r1 = await Dispatcher.call("ping", {} as any)
208+
expect(r1).toEqual({ status: "fresh-new" })
209+
expect(newRunCount).toBe(1)
210+
211+
// Now the old hook wakes up and belatedly overwrites "ping" with
212+
// stale-old via its own register() call. Without the self-heal, the
213+
// next Dispatcher.call would silently return the stale handler because
214+
// registration is memoized "done" and never re-runs.
215+
resolveOld()
216+
await firstCall.catch(() => {})
217+
218+
// Third call: the fix detects the stale-generation success, clears
219+
// the memoized promise so the CURRENT hook re-runs and overwrites
220+
// "ping" back to fresh-new.
221+
const r2 = await Dispatcher.call("ping", {} as any)
222+
expect(r2).toEqual({ status: "fresh-new" })
223+
expect(newRunCount).toBe(2) // re-ran to self-heal the stale register()
224+
})
225+
195226
test("reset() clears both the hook and the cached in-flight promise", async () => {
196-
// The reset added a new field (_registrationPromise) that also needs
197-
// to be cleared, otherwise test isolation regresses: a failed
198-
// registration in one test would leave the cached rejected promise
199-
// pinned for the next test.
227+
// reset() must wipe both _ensureRegistered AND _registrationPromise —
228+
// otherwise a failed registration in one test leaves the cached
229+
// rejected promise pinned for the next test.
200230
let attempts = 0
201231
Dispatcher.setRegistrationHook(async () => {
202232
attempts += 1
@@ -205,8 +235,6 @@ describe("v0.9.6 release: Dispatcher registration retry", () => {
205235
await expect(Dispatcher.call("ping", {} as any)).rejects.toThrow("boom")
206236
expect(attempts).toBe(1)
207237

208-
// Reset should wipe both hook and cached promise. Setting a new hook
209-
// must let call() invoke IT, not a stale rejected promise.
210238
Dispatcher.reset()
211239
Dispatcher.setRegistrationHook(async () => {
212240
Dispatcher.register("ping", async () => ({ status: "fresh" }))

0 commit comments

Comments
 (0)