Skip to content

Core: speed up WASM exports and cut core allocations - #7

Merged
Fellmonkey merged 5 commits into
mainfrom
perf/wasm-benchmarks
Nov 26, 2026
Merged

Fellmonkey merged 5 commits into
mainfrom
perf/wasm-benchmarks

Conversation

@Fellmonkey

@Fellmonkey Fellmonkey commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner

What this changes and why

No issue: this is the WASM performance and browser-generation task requested directly.

Performance. All six WASM exports have native benchmarks and a Node smoke harness. Export logic lives in a js-free api.go, so the browser path is what gets measured. A second pass cut allocations in the core itself — validator, parser, lexer, renderer and result JSON.

Browser generation. goGenerate(yaml, bridge, packagesJSON) builds the IR, resolves the extends chain from the embedded bridges/ tree and returns generated files as JSON. Disk rendering is unchanged: TestRenderMemoryMatchesDisk proves byte-identical output.

Changes:

  • memoize the last goValidate/goParseDomain result and the goSpecmeta JSON;
  • give SplitIdentifier, PascalCase, ToDatabaseColumnName and SplitRespectingQuotes a fast path for the common case;
  • create Validations only when a field actually has a validation modifier;
  • add renderer.NewFromFS + RenderMemory, with js/wasm stubs that keep the network-backed package resolver and bridge clone/update code out of the browser binary;
  • keep the JS argument type checks and the Unicode casing fix from main;
  • share a sorted-key helper and a flat cycle DFS in the validator;
  • parse strings without a []byte copy, cache feature-field order, read Node.Value for plain scalars;
  • cache regexp.Compile for the field definition the Studio reparses on every keystroke;
  • write goParseField JSON directly and stream result JSON into a strings.Builder;
  • grow template output builders from the previous render size;
  • fix BenchmarkValidate/BenchmarkParseDomain: they appended a digit after a trailing newline and measured the parse-error path instead of validation.

How you tested it

go test ./... -count=1                 # all packages pass
make lint                              # 0 issues
GOOS=js GOARCH=wasm go build -o bin/validate.wasm ./cmd/wasm-validator/
node cmd/wasm-validator/smoke.mjs bin/validate.wasm   # all 6 exports ok, 6 generated files

go test ./cmd/wasm-validator/ -run '^$' -bench . -benchmem -count=6 -benchtime=200ms
make bench                             # module benchmarks, same command as bench.yml

Benchstat, e3ef352 → 9a27589, Windows/amd64 Ryzen 7 5800X, Go 1.27.4, corrected benchmarks, n=6:

Benchmark Before After Delta
geomean, time 120.3 µs 76.2 µs −36.7%
geomean, bytes 63.77 KiB 45.55 KiB −28.6%
geomean, allocs 725.5 549.7 −24.2%
Validate/entities=2000 45.17 ms 32.69 ms −27.6%
Validate/entities=2000, allocs 230.3k 174.2k −24.3%
GenerateYAML 825.6 µs, 603.9 KiB 670.3 µs, 300.7 KiB −18.8% / −50.2%
ParseField/regex 4.40 µs, 3518 B, 40 alloc 1.01 µs, 904 B, 9 alloc −77% / −74% / −77%
ParseField/modifiers 2.77 µs 1.32 µs −52.4%
StudioValidationCycle/changing-yaml 2.541 ms 2.274 ms −10.5%

Generation was initially 2.01 ms / 1.44 MiB / 11.5k alloc. Compiling templates once per bridge chain cut it to 0.71 ms / 587 KiB / 2.49k alloc; the second pass (buffered output and streamed result JSON) brings it to 0.67 ms / 301 KiB / 2.42k alloc. The cached plan holds only bridge files, never the user's model.

Earlier measurements against base main@8927417 (the first three commits; Validate/ParseDomain rows predate the benchmark fix): Specmeta 22.7 µs → 3.4 ns, StudioValidationCycle/same-yaml 2.66 ms → 2.0 µs, ToDatabaseColumnName/simple 183 ns → 5.7 ns, Validate/entities=2000 18.4 ms → 13.8 ms.

Real WASM in Node 24 was smoke-tested after every pass: all six exports return the expected values and goGenerate produces six files. Cold goValidate/goParseDomain timings oscillate by 20–70% between identical runs on this machine, so they are not used as evidence. goParseField and goGenerate improved consistently (generation of the kitchen-sink model: ~130 ms → ~99 ms in the last interleaved run).

Binary size. The naive renderer wiring grew the WASM file from 5.90 MB to 19.38 MB. WASM-only stubs for package resolution, bridge resolution and crypto/rand bring it to 10.14 MB raw / 2.61 MB gzip (base: 5.90 MB raw / 1.61 MB gzip). net/http, crypto/tls and os/exec are absent from the js/wasm dependency graph. NuGet versions are not resolved in the browser; callers pass them via packagesJSON. Disk writes, --prune and --migrate stay outside the browser.

Byte identity and regressions. SHA256 over all six exports for four models and eight field definitions is aa57102b… for both the previous and the final commit. TestMarshalFieldDefinitionMatchesEncodingJSON guards the hand-written writer against encoding/json; it caught a real mismatch where a nil Validations map was written as {} instead of null. TestGenerateYAMLRejectsInvalidModel keeps the validator gate in front of browser generation. Both are named in compliance-suite/regressions.tsv.

DRY. The bridge contract gate lives in internal/bridgecontract and is reused by the CLI, disk renderer and WASM renderer; specmeta.EffectiveContractVersion handles absent/zero declarations. targetFramework and compileSpec are single implementations shared by both render paths. goGenerate calls the same validator as goValidate — an invalid model is not rendered.

Tested on: local Windows, Go 1.27.4, Node 24.18.1; CI-equivalent make lint and go test ./....

Keeping the gains

Allocation budgets run inside go test ./..., so CI rejects a systematic
regression without trusting a noisy timer. Measured on Go 1.27.4:

Check Measured Budget
ParseYAMLString/entities=100 6552 alloc/op 8200
Validate/entities=100 209 alloc/op 270
Parse simple / modifiers / regex 2 / 8 / 8 alloc/op 3 / 9 / 9
ValidateYAML (cold, alternating inputs) 233 alloc/op 300
ParseFieldDefinition 7 alloc/op 10
GenerateYAML 2420 alloc/op 3500
RenderMemory/admin 3595 alloc/op (3718 under -race) 4700

Budgets leave ~25% slack for patch releases (tighter where absolute counts are
small) and were verified under -race and -shuffle=on. A deliberately added
allocation in lexer.Parse failed the gate; the injection was removed. The
checks are named in compliance-suite/regressions.tsv.

make bench and bench.yml now cover internal/parser, internal/validator,
internal/lexer, cmd/wasm-validator and pkg/textutil in addition to the
existing renderer/IR/snapshot targets. bench.yml triggers on the two new
paths. On the base checkout it clears BENCH_WASM_PACKAGE: at that commit
cmd/wasm-validator contains only a js && wasm main.go and cannot build on
linux/amd64, which made the first bench run fail. Timing remains a report:
benchstat compares base and PR on the same runner, while behavior and
allocations are gated by tests.

How you found it

  • I use DomainCraft and ran into this myself
  • I found it by reading the code or comparing with other compilers

AI tools used to write this change: yes. OpenCode (hy4-flash-free) wrote the native benchmark harness, the js-free API extraction, the Node smoke harness, the in-memory renderer path and the core allocation fixes. For the second pass it orchestrated four parallel agents in isolated worktrees, each profiling one area with pprof and benchstat; ideas without a measured win were reverted. The human author reviewed every file and the final numbers before opening and updating this PR.

Checklist

  • Commits are signed and verified
  • The author of this PR is a person; an AI agent is not the contributor
  • make fmt, make lint and make test pass
  • Deterministic output: generated files are sorted by path; no map iteration was added
  • Regression checks are named in compliance-suite/regressions.tsv

- move WASM export logic into a js-free API so it is testable natively
- memoize goValidate/goParseDomain results and goSpecmeta JSON
- cut identifier and modifier-split allocations in the hot parse path
- add native benchmarks, a Node WASM smoke harness and measured results

Benchstat, Windows/amd64 Ryzen 7 5800X, Go 1.27.4, -count=6+8,
base main@8927417 vs PR after re-sync:

Specmeta                          22.7us  ->  3.4ns    -100%
StudioValidationCycle/same-yaml    2.66ms ->  2.0us    -99.9%
StudioValidationCycle/changing     2.59ms ->  2.27ms   -12.5%
SplitIdentifier/simple             192ns  ->  16ns     -92%
ToDatabaseColumnName/simple        183ns  ->  5.7ns    -97%
Validate/entities=2000            18.4ms  -> 13.8ms    -25%

Node, 200 calls, median of 4 interleaved runs, ms/call:
goValidate (same)       0.26 -> 0.055
goParseDomain (same)    0.19 -> 0.021
goSpecmeta              0.14 -> 0.016
studio cycle            0.39 -> 0.042

Cold per-call paths are unchanged within noise.
- expose goGenerate(yaml, bridge, packagesJSON) returning generated files
- load the embedded bridges tree through a new fs.FS renderer path
- keep CLI rendering byte-identical (TestRenderMemoryMatchesDisk)
- stub package resolution and bridge clone/update code for js/wasm

The naive build grew from 5.9 MB to 19.4 MB; the WASM-only stubs bring it
back to 10.2 MB raw (2.6 MB gzip). RenderMemory adds no disk or symlink
machinery, so browser generation stays bounded by the returned JSON.

go test ./... -count=1 and make lint pass; Node smoke generates 6 files
for admin-alpine in ~9 ms.
- cache compiled templates and the bridge chain across generate calls
- compile specs once for both disk and in-memory renderers
- validate the model in goGenerate before rendering it
- move the contract gate into internal/bridgecontract and reuse specmeta
- keep crypto/rand out of the WASM build

BenchmarkGenerateYAML before -> after:
  2.01ms -> 0.71ms (-65%)
  1477KiB -> 587KiB (-60%)
  11.5k -> 2.49k allocs/op (-78%)

WASM binary: 10.07 MB raw / 2.59 MB gzip. Other exports unchanged in Node.
- share a sorted-key helper and a flat cycle DFS in the validator
- parse strings without a []byte copy and cache feature-field order
- cache regexp compilation for field definitions
- write goParseField JSON directly and stream result JSON into a builder
- grow template output buffers from the previous render size
- fix benchmarks that appended a digit to YAML and measured the error path

benchstat on corrected benchmarks, base -> this commit:
  geomean time -36.7%, bytes -28.6%, allocs -24.2%
  Validate/entities=2000 -28% time
  GenerateYAML -19% time, -50% bytes
  ParseField/regex -77% time
  StudioValidationCycle/changing-yaml -10% time

All six exports stay byte-identical: SHA256 matches the previous commit for
four models and eight field definitions. WASM binary: 10.14 MB raw.
@Fellmonkey Fellmonkey changed the title Core: speed up WASM validation exports and add benchmarks Core: speed up WASM exports and cut core allocations Nov 26, 2026
- add parser, validator, lexer and in-memory renderer benchmarks with budgets
- budget WASM export allocations with alternating inputs to exercise the cold path
- extend make bench and bench.yml to cover the new modules
- clear cmd/wasm-validator on the base side: it only has a js/wasm main.go there
- name the new checks in compliance-suite/regressions.tsv

Budgets were measured on Go 1.27.4 with ~25% slack and verified under -race.
A deliberate extra allocation in lexer.Parse failed the gate; the injection
was removed afterwards. Timing stays a report, not a gate.
@Fellmonkey
Fellmonkey merged commit fe068e7 into main Nov 26, 2026
11 checks passed
@Fellmonkey
Fellmonkey deleted the perf/wasm-benchmarks branch November 26, 2026 21:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant