Skip to content

Commit 3645a9d

Browse files
sahrizviclaude
andcommitted
release: v0.9.6 review — dispatcher race guard + qualify rule wording
Addresses coderabbit findings on the release PR: - **Major** — dispatcher.ts: without generation tracking, a stale registration attempt's `.then` handler could clobber replacement state installed mid-flight by a concurrent `reset()` or `setRegistrationHook()`. Success path nulled `_ensureRegistered` (wiping a replacement hook); failure path nulled `_registrationPromise` (breaking dedup for a newer in-flight promise). Fix: bump a generation counter on every mutation entry point; the settle handlers only mutate cached state if their captured generation is still current. 2 new adversarial tests cover both races. - **Minor** — CHANGELOG.md and docs/docs/usage/check.md: the "every finding carries a `rule` field" claim isn't quite true — `lint` findings may omit `rule` if the engine didn't attach one (matches the documented Finding Object where `rule` is optional). Qualified the wording in both files to "when set" / "when the underlying engine attaches one" so users know to check for presence before switching on it. Local verification: `bun test test/skill/release-v0.9.6-adversarial.test.ts test/altimate/dispatcher.test.ts` → 14/14 pass (2 new race tests). `bun turbo typecheck` clean. Co-Authored-By: Claude Opus 4.7 <[email protected]>
1 parent 2a27682 commit 3645a9d

4 files changed

Lines changed: 105 additions & 5 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Correctness release: `check --checks {validate,semantic,grade,pii,migration,safe
1111

1212
### Changed
1313

14-
- **`check --checks *` now surfaces the findings it was missing — expect newly-failing CI runs.** `altimate-core` upgrade `0.5.1 → 0.7.0` plus a consumer-contract sync catches a class of latent shape-mismatch bugs where the CLI was reading fields the engine no longer emits and rendering false-clean output as a result. Concretely: (a) `check --checks validate` gated on the wrong field and passed every file, now maps `ValidationError.location` and fails closed on engine failure; (b) `check --checks semantic` treated `valid:true` as clean, but `valid` means "plannable" — cartesian products came back "OK" for months, now reads `findings` and never gates on `valid`; (c) `check --checks grade` read fields `evaluate()` doesn't return, so no grade or finding ever surfaced, now reads `overall_grade`/`scores.overall`/`lint.findings` (with nested findings from `validation.errors` + `safety.threats`); (d) `check --checks pii` mapped the column name to the numeric column-position field and printed `[object Object]` for `{ Custom: string }` classifications, now reports the exposing alias and stringifies properly; (e) `check --checks migration` rendered "SAFE" for every migration including `DROP COLUMN`, now reads `findings`/`safe`/`overall_risk`; (f) `check --checks compare` rendered "IDENTICAL" for different queries, now reads `differences`; (g) `check --checks policy` titled on `pass` (engine returns `allowed`), so clean SQL always rendered "VIOLATIONS FOUND", now inverted; (h) `check --checks safety` maps engine `high → error` and `medium → warning` (previously both degraded to `info`), so `--fail-on error|warning` no longer silently passes high-risk SQL injection threats; a new `unbalanced_quote` safety rule ships from the engine. Every finding's `rule` field is machine-readable in `--format json` output — that's where rule catalog lives. (#1090)
14+
- **`check --checks *` now surfaces the findings it was missing — expect newly-failing CI runs.** `altimate-core` upgrade `0.5.1 → 0.7.0` plus a consumer-contract sync catches a class of latent shape-mismatch bugs where the CLI was reading fields the engine no longer emits and rendering false-clean output as a result. Concretely: (a) `check --checks validate` gated on the wrong field and passed every file, now maps `ValidationError.location` and fails closed on engine failure; (b) `check --checks semantic` treated `valid:true` as clean, but `valid` means "plannable" — cartesian products came back "OK" for months, now reads `findings` and never gates on `valid`; (c) `check --checks grade` read fields `evaluate()` doesn't return, so no grade or finding ever surfaced, now reads `overall_grade`/`scores.overall`/`lint.findings` (with nested findings from `validation.errors` + `safety.threats`); (d) `check --checks pii` mapped the column name to the numeric column-position field and printed `[object Object]` for `{ Custom: string }` classifications, now reports the exposing alias and stringifies properly; (e) `check --checks migration` rendered "SAFE" for every migration including `DROP COLUMN`, now reads `findings`/`safe`/`overall_risk`; (f) `check --checks compare` rendered "IDENTICAL" for different queries, now reads `differences`; (g) `check --checks policy` titled on `pass` (engine returns `allowed`), so clean SQL always rendered "VIOLATIONS FOUND", now inverted; (h) `check --checks safety` maps engine `high → error` and `medium → warning` (previously both degraded to `info`), so `--fail-on error|warning` no longer silently passes high-risk SQL injection threats; a new `unbalanced_quote` safety rule ships from the engine. Findings' `rule` field (when set — `lint` findings may omit it if the engine didn't attach one) names the rule in `--format json` output — that's how the safety and policy catalog is discovered in practice. (#1090)
1515
- **`altimate-core-track-lineage` no longer returns "0 edges" for everything.** The tool read `edges` off the top-level result; the engine has always emitted them at `queries[].edges`, so lineage tracking silently produced nothing. Now collects correctly, renders `impact_map`, formats `{table, column}` refs, and renders ERROR instead of "0 edges" when the engine call itself fails. (#1090)
1616
- **`schema.detect_pii` returned zero findings for every scan.** Same shape-mismatch class: the detector read `piiData.findings`, but the engine's `PiiReport` is `{ columns, pii_count, … }`. Both cache and live paths now filter `classification !== "None"` through the shared `piiColumnsFromReport` helper. Malformed `PiiReport` shapes now throw rather than silently yield zero findings. Failed per-column classifications flip `success` to `false` — the schema-detect-pii tool renders "PII Scan: ERROR" with any partial findings attached, instead of a clean "no findings" verdict. (#1090)
1717
- **`altimate-core-{compare,column-lineage,extract-metadata,import-ddl}` no longer crash on the default invocation.** Empty-string dialects now coerce to `undefined` before hitting `Schema.fromDdl`, centralized as `dialectHint()` in `native/engine-coerce.ts` and applied across all 7 dialect-forwarding handlers. (#1090)

‎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-
Every finding carries a machine-readable `rule` field (e.g. `unbalanced_quote`, `sql_injection`, `L003`) — visible in `--format json` output, and how the safety, lint, and policy rule inventory is discovered in practice.
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.
5454

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

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

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,28 @@ let _ensureRegistered: (() => Promise<void>) | null = null
2323
/** In-flight registration promise (deduped across concurrent callers). */
2424
let _registrationPromise: Promise<void> | null = null
2525

26+
/** Generation counter — bumped whenever the hook or in-flight promise is
27+
* replaced. An in-flight attempt captures its generation at start; if the
28+
* counter advanced by the time its settle handler fires, another caller
29+
* (reset / setRegistrationHook / a distinct new attempt after failure)
30+
* has already installed replacement state, and the stale attempt must NOT
31+
* mutate it. Prevents a stale success from clobbering a replacement hook,
32+
* and a stale failure from clobbering a newer in-flight promise. */
33+
let _registrationGeneration = 0
34+
2635
/** Clear all registered handlers and lazy registration hook (for test isolation). */
2736
export function reset(): void {
2837
nativeHandlers.clear()
2938
_ensureRegistered = null
3039
_registrationPromise = null
40+
_registrationGeneration++
3141
}
3242

3343
/** Called by native/index.ts to set the lazy registration function. */
3444
export function setRegistrationHook(fn: () => Promise<void>): void {
3545
_ensureRegistered = fn
3646
_registrationPromise = null
47+
_registrationGeneration++
3748
}
3849

3950
/** Dispatch a method call to the registered native handler. */
@@ -47,16 +58,19 @@ export async function call<M extends BridgeMethod>(
4758
// ``_ensureRegistered`` was nulled BEFORE the await, so a transient NAPI
4859
// load failure poisoned the bridge for the process lifetime — every
4960
// subsequent ``call`` threw ``No native handler for X`` with no way to
50-
// recover without restarting the CLI.
61+
// recover without restarting the CLI. Generation guard prevents a stale
62+
// attempt from mutating state a concurrent ``reset()``/``setRegistrationHook()``
63+
// has since replaced. (coderabbit round 1 — release/v0.9.6 review.)
5164
if (_ensureRegistered) {
5265
if (!_registrationPromise) {
5366
const fn = _ensureRegistered
67+
const generation = ++_registrationGeneration
5468
_registrationPromise = fn().then(
5569
() => {
56-
_ensureRegistered = null
70+
if (generation === _registrationGeneration) _ensureRegistered = null
5771
},
5872
(err) => {
59-
_registrationPromise = null
73+
if (generation === _registrationGeneration) _registrationPromise = null
6074
throw err
6175
},
6276
)

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

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,92 @@ describe("v0.9.6 release: Dispatcher registration retry", () => {
106106
expect(attempts).toBe(1)
107107
})
108108

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.
114+
let resolvePending: () => void = () => {}
115+
const pending = new Promise<void>((r) => (resolvePending = r))
116+
Dispatcher.setRegistrationHook(async () => {
117+
await pending
118+
Dispatcher.register("ping", async () => ({ status: "old-hook-ran" }))
119+
})
120+
121+
// Start the first call — hook attempt is now in flight, awaiting `pending`.
122+
const firstCall = Dispatcher.call("ping", {} as any)
123+
await new Promise((r) => setTimeout(r, 5))
124+
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.
128+
Dispatcher.reset()
129+
let replacementRan = false
130+
Dispatcher.setRegistrationHook(async () => {
131+
replacementRan = true
132+
Dispatcher.register("ping", async () => ({ status: "replacement" }))
133+
})
134+
135+
// Let the old attempt resolve. Its success handler must skip the mutation
136+
// because the generation has advanced twice (reset + setRegistrationHook).
137+
resolvePending()
138+
await firstCall.catch(() => {}) // may reject or resolve; doesn't matter here
139+
140+
// A new call should invoke the REPLACEMENT hook, not skip registration.
141+
const result = await Dispatcher.call("ping", {} as any)
142+
expect(replacementRan).toBe(true)
143+
expect(result).toEqual({ status: "replacement" })
144+
})
145+
146+
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.
154+
let rejectOld: (err: Error) => void = () => {}
155+
const oldPending = new Promise<void>((_, rej) => (rejectOld = rej))
156+
Dispatcher.setRegistrationHook(async () => {
157+
await oldPending
158+
})
159+
160+
// Start first call — will fail once we reject.
161+
const firstCall = Dispatcher.call("ping", {} as any)
162+
await new Promise((r) => setTimeout(r, 5))
163+
164+
// Install new hook; kick off a second call which caches its own promise.
165+
let newHookAttempts = 0
166+
let resolveNew: () => void = () => {}
167+
const newPending = new Promise<void>((r) => (resolveNew = r))
168+
Dispatcher.setRegistrationHook(async () => {
169+
newHookAttempts += 1
170+
await newPending
171+
Dispatcher.register("ping", async () => ({ status: "new-hook-ran" }))
172+
})
173+
const secondCall = Dispatcher.call("ping", {} as any)
174+
await new Promise((r) => setTimeout(r, 5))
175+
176+
// Reject the old attempt. Its failure handler must NOT null the second
177+
// call's cached promise.
178+
rejectOld(new Error("old attempt failed"))
179+
await firstCall.catch(() => {})
180+
181+
// Third caller arrives — should share the second call's still-cached
182+
// promise (dedup works), not start a third registration attempt.
183+
const thirdCall = Dispatcher.call("ping", {} as any)
184+
resolveNew()
185+
186+
const [r2, r3] = await Promise.all([secondCall, thirdCall])
187+
expect(r2).toEqual({ status: "new-hook-ran" })
188+
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.
192+
expect(newHookAttempts).toBe(1)
193+
})
194+
109195
test("reset() clears both the hook and the cached in-flight promise", async () => {
110196
// The reset added a new field (_registrationPromise) that also needs
111197
// to be cleared, otherwise test isolation regresses: a failed

0 commit comments

Comments
 (0)