Repository navigation
perf(replica): add benches and speed up diff apply - #185
Conversation
Survey every package for CPU-bound hot paths that warranted benchmarks,
add suites where they were missing, and fix the slow code the new numbers
exposed.
Benchmarks added (@lunora/replica, sql-store, db, advisor, errors), each
wired the same way as the existing suites: `vitest.bench.config.ts` off
the shared `getBenchConfig`, a `test:bench` script, `__bench__` in the
tsconfig include, and the eslint test-file relaxations extended to
benches.
@lunora/replica — applyDiff is the client replication hot path:
- applyDiffs copied the row map once per diff (N+1 copies for N diffs)
while documenting the opposite. Fold the backlog through one in-place
applier instead: 53x faster on a 64-diff catch-up replay.
- deriveInsertId ran 64-bit FNV-1a over BigInt, allocating a heap object
per character. Same digest over four 16-bit number limbs, pinned
bit-for-bit against the BigInt reference in the new test.
- Canonicalization built a fully canonicalized copy of the value tree
and re-walked it with JSON.stringify; it now streams into the hash
input in one pass. Combined: 3x faster on id-less inserts.
@lunora/replica also fixes a determinism bug found on the way: the
canonicalizer sorted object keys with localeCompare, which resolves
against the runtime locale and ICU version. Two clients in different
locales derived DIFFERENT ids for the SAME row and diverged — exactly
the failure deriveInsertId exists to prevent. Keys now sort by UTF-16
code unit, as canonical-JSON schemes specify. This changes derived ids
for id-less inserts whose keys sorted differently under the two
orderings; those ids were already environment-dependent.
@lunora/values — v.array built its result with Array.from({ length }),
which has no V8 fast path and measured ~27x slower than the
alternatives. Its own bench had been reporting the naive baseline as
6.46x FASTER than the "optimized" parser; it now reports 1.05x slower.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The streaming canonical encoder behind deriveInsertId is a hand-rolled re-implementation of JSON.stringify's encoding rules, and derived row ids are persisted and replayed — a divergence forks replicas instead of throwing. Add a differential suite that pins it against the obvious build-a-copy-then-stringify implementation over 3000 randomly generated values plus the cases JSON.stringify treats specially (undefined in objects vs arrays, NaN/Infinity, -0, escaping, empty and prototype-named keys, Date, RegExp). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Addresses the thermo review of this branch. The headline change: splitting the hotpath bench into independently attributable pairs — which the review asked for, because one number was covering two optimizations — showed that the streaming canonical-JSON encoder was NOT an optimization. Measured on its own it is ~2x SLOWER than the canonicalized-copy + native JSON.stringify form it replaced; JSON.stringify is a native fast path that JS-side string building cannot beat. The end-to-end 3x was the limb hash carrying a slower encoder. So the encoder is reverted. What survives is what actually measured: the single-copy applyDiffs fold (50x on a 64-diff backlog), the limb FNV-1a (7.5x on the hash alone), and the code-unit key sort. The rejected one-pass encoder stays in the bench as a labelled baseline so the decision is re-checkable and nobody "optimizes" it back. Reverting it also deletes the whole JSON.stringify-parity risk surface — no hand-rolled escaping, no re-implemented undefined/toJSON rules — and with it a latent collision bug the review caught: pushing raw parts into an array meant a non-string `table`/`id` arriving from untyped wire JSON contributed NOTHING to the digest, so two distinct diffs derived the same row key. Interpolation coerces; a test now pins it. Other review fixes: - applyDiffInto: revert to changes.entries(), dropping a cast that defeated noUncheckedIndexedAccess for an unmeasured gain. - Document the key-order migration accurately — it is broader than mixed-case keys (punctuation, non-ASCII), and integer-like keys were never locale-dependent at all. - Extract __bench__/apply-diff.shared.ts. The two replica bench files had drifted into measuring different inputs under near-identical titles. - advisor: throw on a missing lint instead of `?.`, which turned a renamed lint into a no-op bench reporting as a dramatic speedup. - db: hoist the toMap fixture out of the timed body (it was ~5.7x of the measurement) and give every bench identical setup cost. - errors/sql-store: drop the O(1) accessor benches — property reads that CodSpeed's instrumentation dwarfs — and hoist remaining fixtures. - sql-store: type the shape fixture and cast once. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
✅ Deploy Preview for lunorash ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Thank you for following the naming conventions! 🙏 |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
WalkthroughAdds Vitest benchmark coverage and package benchmark wiring across multiple packages, optimizes replica diff processing, fingerprint hashing, event-log canonicalization, and value-array parsing, and adds CodSpeed support. ChangesBenchmark infrastructure
Runtime optimizations
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant applyDiff as applyDiff/applyDiffs
participant applyDiffInto
participant deriveInsertId
participant RowMap
applyDiff->>applyDiffInto: Apply changes to the evolving map
applyDiffInto->>deriveInsertId: Derive IDs for id-less inserts
deriveInsertId->>RowMap: Produce deterministic row IDs
applyDiffInto->>RowMap: Mutate rows in place
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Thank you for confirming the Contributor License Agreement! 🙏 |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
packages/fingerprint/__bench__/fingerprint-stack.bench.ts (1)
10-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExercise the bare stack-frame parser branch.
DEEP_STACKis described as covering both frame shapes, but every entry is function-wrapped (at fn (...)). Add a bare frame such asat apps/worker/src/handlers.ts:7:11so the benchmark matches its stated coverage.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/fingerprint/__bench__/fingerprint-stack.bench.ts` around lines 10 - 23, Update the DEEP_STACK fixture to include at least one bare stack-frame entry without a function name, such as a path with line and column coordinates. Keep the existing function-wrapped, node_modules, and node:internal frames unchanged so both parser shapes remain covered.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/advisor/__bench__/run-advisor.bench.ts`:
- Around line 107-109: Align the benchmark fixture labels in the small, medium,
and large definitions with the actual table counts produced by buildSchema: 10,
30, and 105 respectively. Either rename the labels to those total counts or pass
values that make the existing labels represent complete schema sizes, keeping
dashboard comparisons accurate.
- Around line 49-50: Replace the untyped table-map cast in the benchmark fixture
with a typed accumulator or helper that preserves each table as a
TableDefinition. Update the surrounding defineSchema call to receive
Record<string, TableDefinition> directly, retaining compile-time validation of
relation and index targets and removing the never cast.
In `@packages/replica/__bench__/apply-diff-hotpath.bench.ts`:
- Around line 46-73: Update the “current” benchmark case around the affected
benchmark entries to call the real canonicalizer, canonicalizeForHash from
apply-diff.ts, instead of canonicalizeLocaleSortedPreReplica05. Keep the
pre-REPLICA-05 localeCompare implementation only for the explicitly labeled
historical comparison, so the reported benchmark compares the current code-unit
ordering against the alternative as documented.
- Line 184: Replace the hardcoded “500” in the benchmark title within the
applyDiffs describe block with the existing ROW_COUNT constant, matching the
equivalent title’s dynamic interpolation in apply-diff.bench.ts.
In `@packages/sql-store/__bench__/value-codec.bench.ts`:
- Around line 111-117: Move the object fixture and Uint8Array fixture
construction outside their respective bench callbacks, then reuse those prebuilt
values in the sqliteEncode calls within the “object (JSON.stringify)” and “bytes
(Uint8Array passthrough)” benchmarks so timing measures encoding only.
In `@packages/values/__bench__/parse-hotpath.bench.ts`:
- Around line 16-19: Update arrayBaseline to reproduce the former Array.from({
length }) result allocation with indexed assignment, matching the benchmark
description and isolating the result-construction optimization; alternatively,
revise the description to accurately state the [] plus push strategy currently
measured.
---
Nitpick comments:
In `@packages/fingerprint/__bench__/fingerprint-stack.bench.ts`:
- Around line 10-23: Update the DEEP_STACK fixture to include at least one bare
stack-frame entry without a function name, such as a path with line and column
coordinates. Keep the existing function-wrapped, node_modules, and node:internal
frames unchanged so both parser shapes remain covered.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: e2b74456-2de0-4f1f-bc4a-85477083e89c
⛔ Files ignored due to path filters (3)
packages/replica/__tests__/apply-diff-canonical.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**packages/replica/__tests__/apply-diff.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (37)
packages/advisor/__bench__/run-advisor.bench.tspackages/advisor/eslint.config.jspackages/advisor/package.jsonpackages/advisor/tsconfig.jsonpackages/advisor/vitest.bench.config.tspackages/db/__bench__/diff-emit.bench.tspackages/db/eslint.config.jspackages/db/package.jsonpackages/db/tsconfig.jsonpackages/db/vitest.bench.config.tspackages/errors/__bench__/to-error-body.bench.tspackages/errors/package.jsonpackages/errors/tsconfig.jsonpackages/errors/vitest.bench.config.tspackages/fingerprint/__bench__/fingerprint-error.bench.tspackages/fingerprint/__bench__/fingerprint-stack.bench.tspackages/fingerprint/__bench__/message-bucket.bench.tspackages/fingerprint/__bench__/sha256.bench.tspackages/fingerprint/package.jsonpackages/fingerprint/src/sha256.tspackages/fingerprint/tsconfig.jsonpackages/fingerprint/vitest.bench.config.tspackages/replica/__bench__/apply-diff-hotpath.bench.tspackages/replica/__bench__/apply-diff.bench.tspackages/replica/__bench__/apply-diff.shared.tspackages/replica/eslint.config.jspackages/replica/package.jsonpackages/replica/src/apply-diff.tspackages/replica/tsconfig.jsonpackages/replica/vitest.bench.config.tspackages/sql-store/__bench__/value-codec.bench.tspackages/sql-store/eslint.config.jspackages/sql-store/package.jsonpackages/sql-store/tsconfig.jsonpackages/sql-store/vitest.bench.config.tspackages/values/__bench__/parse-hotpath.bench.tspackages/values/src/v.ts
Addresses the second thermo review plus CodeRabbit on PR #185. The bug reviewer cleared every shipped source change — it fuzzed the limb FNV-1a against the BigInt reference over 276k inputs (exhaustive BMP, sampled astral, lone surrogates) with zero mismatches, and confirmed the copy-on-write contract, the sha256 module-state argument, and v.array's push-vs-preallocate equivalence. Everything below is guard quality. Benches were measuring hand-copied duplicates of the code they guard: - `fnv1a64Hex` and `canonicalizeForHash` are now exported (for benches and tests only; `src/index.ts` does not re-export them) and imported by both. The copy had ALREADY drifted — it built its hex with map/join where production concatenates — so the "optimized" arm was measuring a fossil on day one. Correcting it moved the hash number from a claimed ~8x to a measured ~5x, and the docstring now says ~5x. - The canonicalization pair labelled its "current" arm with the pre-REPLICA-05 localeCompare canonicalizer. It now calls the shipped one. - values: both arms of the v.array pair had converged on `push`, so nothing exercised `Array.from({ length })` any more — the regression the file exists to catch would have sailed through. Added an explicit third arm. `event-log-do.ts` carried the same localeCompare determinism bug this branch fixed in `apply-diff.ts`, 200 lines away in the same package — and on a worse path: it feeds `fingerprintBatch`, the idempotency fingerprint, so two DO instances on different ICU builds would fingerprint one batch differently and report a legitimate retry as a conflict. Fixed. Also fixes the Benchmarks CI job, which was already red on alpha (since the notify bench landed). Top-level `await` makes the module async, and CodSpeed's instrumented runner collects benches before that settles, so every body arrived as `undefined` — `TypeError: fn is not a function`. It only reproduces under instrumentation, which is why local runs stayed green. Moved the seeding into `beforeAll`. Smaller: advisor labels said 5/25/100 tables for schemas that hold 10/30/105 (now derived from the schema); the ALL_LINTS vs STATIC_LINTS pair differed in a `source` filter as well as the lint set; sql-store timed fixture allocation inside two bench bodies and kept an O(1) bench the errors suite argues against; a hard-coded 500 survived in the very file the shared-fixture extraction was about; fingerprint's DEEP_STACK claimed bare-frame coverage it did not have; the db setup-parity comment described a parity the code cannot provide. Documented why shared/stable-key.ts is not reusable here (fail-loud on Date/bigint, and this hashes untrusted wire data) and softened the digest comment, which overstated: `::`-joining is still value-ambiguous. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/replica/src/apply-diff.ts (1)
54-61: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winUse null-prototype accumulators in both canonicalizers.
Both canonicalizers can drop an own
__proto__key when assigning into{}, causing distinct payloads to serialize identically.
packages/replica/src/apply-diff.ts#L54-L61: useObject.create(null)for the hash canonicalization result.packages/replica/src/event-log-do.ts#L70-L73: useObject.create(null)for the fingerprint canonicalization result and test idempotency with a__proto__payload.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/replica/src/apply-diff.ts` around lines 54 - 61, Update the hash canonicalization result near sortedKeys in packages/replica/src/apply-diff.ts:54-61 to use a null-prototype accumulator created with Object.create(null), preserving deterministic key sorting. Apply the same accumulator change in the fingerprint canonicalization path in packages/replica/src/event-log-do.ts:70-73, and add an idempotency test using a payload containing an own __proto__ key.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/values/__bench__/parse-hotpath.bench.ts`:
- Around line 102-109: Update arrayFromPreallocationRegression to create one
reusable parser context and mutable path array before the loop, then push each
index, call inner._parse with that context, and pop it afterward. Remove the
per-element { path: [index] } allocation while preserving the existing output
population and index-path behavior.
---
Outside diff comments:
In `@packages/replica/src/apply-diff.ts`:
- Around line 54-61: Update the hash canonicalization result near sortedKeys in
packages/replica/src/apply-diff.ts:54-61 to use a null-prototype accumulator
created with Object.create(null), preserving deterministic key sorting. Apply
the same accumulator change in the fingerprint canonicalization path in
packages/replica/src/event-log-do.ts:70-73, and add an idempotency test using a
payload containing an own __proto__ key.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 5d2b784a-d559-4e0b-83ed-752085f7baf5
⛔ Files ignored due to path filters (1)
packages/replica/__tests__/apply-diff.test.tsis excluded by!**/__tests__/**,!**/*.test.tsand included bypackages/**
📒 Files selected for processing (9)
packages/advisor/__bench__/run-advisor.bench.tspackages/db/__bench__/diff-emit.bench.tspackages/fingerprint/__bench__/fingerprint-stack.bench.tspackages/notify/__bench__/broadcast-observability.bench.tspackages/replica/__bench__/apply-diff-hotpath.bench.tspackages/replica/src/apply-diff.tspackages/replica/src/event-log-do.tspackages/sql-store/__bench__/value-codec.bench.tspackages/values/__bench__/parse-hotpath.bench.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/sql-store/bench/value-codec.bench.ts
- packages/fingerprint/bench/fingerprint-stack.bench.ts
- packages/advisor/bench/run-advisor.bench.ts
- packages/db/bench/diff-emit.bench.ts
- packages/replica/bench/apply-diff-hotpath.bench.ts
The Benchmarks CI job has been red since this bench landed, failing with `TypeError: fn is not a function` inside CodSpeed's analysis runner. `@lunora/notify` is the only bench-enabled package that never declared `@codspeed/vitest-plugin`, even though its `vitest.bench.config.ts` goes through `getBenchConfig`, which imports it. pnpm therefore resolved the plugin from the root — bound to a different vitest peer set than the one notify itself resolves. Two vitest instances means two distinct module scopes, and `getBenchFn` finds a bench body by a `Symbol()` created in its own scope: against a task registered by the other instance the lookup misses, returns `undefined`, and the runner calls a non-function. Declaring the dependency collapses both onto the same instance (`vitest@4.1.10_…_d00180842d`), which is what every passing bench package already resolves. Only reproduces under instrumentation — outside CI the plugin is a transparent pass-through and never calls `getBenchFn` — which is why local `test:bench` stayed green throughout. Reverts the `beforeAll` refactor from the previous commit: top-level await was a plausible-looking suspect but not the cause, and the runner calls `beforeAll` before iterating tasks anyway. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Merging this PR will regress 1 benchmark
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing Footnotes
|
Two remaining CodeRabbit comments on #185. The `Array.from` regression guard allocated a fresh `{ path: [index] }` per element while the shipped `v.array` reuses one context and pushes/pops a single path stack. So the arm conflated two changes and did not isolate the result-construction difference it exists to measure. It now mirrors the parser in every other respect — reused context, hoisted `length`, indexed loop — leaving array construction as the only variable. That sharpens the reading to 6.7x (6.1M vs 912K hz), which reproduces the ~6.46x the bench originally reported for the pessimization. The advisor fixture's `Record<string, unknown>` + `defineSchema(tables as never)` is replaced with a plain `Record<string, TableDefinition>`, which typechecks. My earlier comment claimed a heterogeneous builder map could not be annotated without erasing its types; that was simply wrong — `defineSchema` is generic over `Record<string, TableDefinition>` and the builders satisfy it. Cast and apologia both deleted. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
All review comments addressed as of
Verification: 1,165 tests across the touched packages, types clean, zero eslint errors. |
`.lunora-schema.json` is a COMMITTED file whose whole purpose is to be byte-stable so drift detection is meaningful. It sorted table names and migration ids with `localeCompare`, which resolves against the runtime's default locale and ICU version — so two developers, or a developer and CI, or one machine either side of a Node upgrade, could regenerate the same schema and produce different bytes. That surfaces as a spurious diff and a false drift signal, which is exactly what the sort was there to prevent. Sorts by UTF-16 code unit instead, which is locale-independent. No committed snapshot changes: all 9 in-repo `.lunora-schema.json` files were checked object-by-object (191 objects) and no key ordering differs between the two comparators — their names are all lowercase ASCII, where ICU collation and code-unit order agree. So no fixture regeneration. Field / index / relation keys are deliberately left in declaration order and are now documented as such; they were never locale-sorted. Found while auditing `@lunora/replica`, which had the same bug in two places (see #185). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Surveys every package for CPU-bound hot paths that warranted benchmarks, adds suites where they were missing, and fixes the slow code the new numbers exposed.
Benchmarks added
Five packages that had none:
@lunora/replica,@lunora/sql-store,@lunora/db,@lunora/advisor,@lunora/errors. Each is wired exactly like the existing suites —vitest.bench.config.tsoff the sharedgetBenchConfig, atest:benchscript,__bench__in the tsconfig include, and the eslint test-file relaxations extended to benches.vis run test:benchnow resolves 20 targets, so the CodSpeed workflow picks them up with no change to CI.Packages deliberately left without benches: thin IO wrappers (
bindings,browser,hyperdrive,ai,mcp,x402,notify,queue,container), build-time-only tooling (config,vite), andstudio(UI). Benching those would measure the network or the harness, not our code.Performance fixes
applyDiffscopied the row map once per diff — N+1 copies for N diffs — while its docstring claimed the oppositederiveInsertIdran 64-bit FNV-1a overBigInt, allocating a heap object per character; now four 16-bit limbs in plain numbersv.arraybuilt its result withArray.from({ length }), which has no V8 fast pathThe
v.arraycase is worth calling out:parse-hotpath.bench.tshad been reporting the "optimized" parser as ~6x slower than the baseline it replaced. The number was sitting in the repo, correct, and unread.A correctness bug, found on the way
@lunora/replica's canonicalizer sorted object keys withlocaleCompare, which resolves against the runtime's default locale and ICU version. Two clients in different locales derived different ids for the same row and diverged — precisely the failurederiveInsertIdexists to prevent (REPLICA-05). Keys now sort by UTF-16 code unit, as canonical-JSON schemes specify.This changes derived ids for id-less inserts whose keys sorted differently under the two orderings — broader than "mixed-case keys": punctuation and separators (
a-b/a_b), and non-ASCII ("é"now sorts after"z"). Those ids were already environment-dependent, nothing in the repo persists them, and all three exports are@experimental— so this is a release note, not a migration.What the review changed
/thermosran over the branch. Its most useful finding was structural: the hotpath bench measured two optimizations with one number. Splitting them apart showed that the streaming canonical-JSON encoder I had written was not an optimization at all — on its own it is ~2x slower than the canonicalized-copy + nativeJSON.stringifyform it replaced, becauseJSON.stringifyis a native fast path JS string building cannot beat. The end-to-end 3x was the limb hash carrying a slower encoder.So the encoder is reverted. The rejected version stays in the bench as a labelled baseline, so the decision is re-checkable rather than folklore. Reverting it also deleted the entire
JSON.stringify-parity risk surface (no hand-rolled escaping, no re-implementedundefined/toJSONrules) and with it a latent collision bug the review caught independently: pushing raw parts into an array meant a non-stringtable/idarriving from untyped wire JSON contributed nothing to the digest, so two distinct diffs derived the same row key. Interpolation coerces; a test pins it.A second review round caught the same class of problem one level down: the benches were measuring hand-copied duplicates of the functions they guard, and the copy had already drifted. Exporting the real
fnv1a64Hex/canonicalizeForHashand repointing benches and tests at them moved the hash claim from ~8x to a measured ~5x. That round also found the identicallocaleComparedeterminism bug 200 lines away inevent-log-do.ts, on the idempotency-fingerprint path — where two DO instances on different ICU builds would fingerprint one batch differently and reject a legitimate retry as a conflict. Fixed.Also fixed from the review: a cast that defeated
noUncheckedIndexedAccessfor an unmeasured gain; two replica bench files that had drifted into measuring different inputs under near-identical titles (now a sharedapply-diff.shared.ts); an advisor bench where a renamed lint would silently become a no-op reporting as a dramatic speedup; adbbench where ~5.7x of thetoMapmeasurement was fixture construction; and several O(1) accessor benches that would only have produced noise-driven CodSpeed alerts.One "optimization" was declined:
advisor'scircular_fklooked like it dominated the suite, but only because the first fixture was a pathological 100-table FK ring. Johnson's algorithm is already the right choice there, so the fixture was fixed to be realistic and the ring kept as an explicitly-labelled worst case.Verification
1,167 tests pass across the touched packages, types clean, zero new eslint errors. The monorepo-wide affected run is green: 1,210 tests across 49 projects.
(
cli'sinit-smoketests failed on an earlier run and passed on re-run — they fetch templates over the network and the vite template alone eats 6.4s of a 10s timeout. Worth a longer budget at some point; not touched here.)Measured under CodSpeed instrumentation
The
v.arrayfix lands harder than the local numbers suggested — these are instrumented, not wall-clock:server— 4-field mutation dispatch (optional + union)values—v.array(v.string()), 32 itemsvalues—v.object(), 7 fields with optional + arrayvalues— nested object (user + message + record)The dispatch win is the one that matters most: every mutation validates its args through
v.array, so this is on the request path, not just in a microbenchmark.Also: 79 new benchmarks registered, 155 untouched.
The one reported regression is not in shipped code
CodSpeed flags
parse-hotpath.bench.ts :: v.record — 16 entries :: baseline (proto-key skip + double path spread)at −10.65%.That is the baseline arm of a bench pair — an inline re-implementation living in the bench file, deliberately unoptimized, never shipped. It is byte-identical to
alpha(git diff origin/alpha...HEADtouches neitherrecordBaselinenorv.record), and the only change topackages/values/src/v.tsin this branch is the three-linev.arrayedit.The most likely cause is V8 code-layout: this branch adds
arrayFromPreallocationRegressionto that module, which can shift inlining and IC decisions for neighbouring functions. CodSpeed independently flagged the run with "different runtime environments detected", which points the same way. Productionv.recordis untouched and shows no change.Needs an acknowledgement on CodSpeed rather than a code change — contorting a deliberately-naive baseline to satisfy a noise signal would defeat the point of having it.
🤖 Generated with Claude Code
Summary by CodeRabbit