Skip to content

magna-gqlmin: lightweight GraphQL parser (v0.1.0) - #1

Merged
srmcguirt merged 57 commits into
mainfrom
claude/graphql-parser-lightweight-b6Vi8
May 4, 2026
Merged

srmcguirt merged 57 commits into
mainfrom
claude/graphql-parser-lightweight-b6Vi8

Conversation

@srmcguirt

Copy link
Copy Markdown
Member

Summary

New magna-gqlmin crate: a lightweight GraphQL parser with three distribution modes from a single Rust source — native (build-time tooling), wasm32 (browser/edge), and napi-rs (Node/Bun). Operations parser, SDL parser, 10 validation rules, pretty errors, AST serde derives, custom inline bump allocator for wasm.

11 of 12 build-order steps shipped. Step 11 (SFC compiler integration) deferred — that compiler doesn't exist in the workspace yet.

What's in the crate

  • Lexer — DFA, full GraphQL Oct-2021 spec § 2.1 token coverage
  • Operations parser — LL(1) recursive-descent over a span-indexed Node arena (Document<'src>), 20-case acceptance corpus
  • SDL parser (feature sdl) — Oct-2021 spec § 3 type system definitions
  • Validation (feature validate) — 5 ops-only rules + 5 schema-aware rules (full set under sdl,validate)
  • Pretty errors (feature pretty) — caret-rendered diagnostics
  • AST serde derives (feature serde)
  • napi-rs binding (feature napi) — parseExecutableDocument returning a stable JSON envelope
  • Wasm shim (feature wasm) — custom 256 KiB inline bump allocator, four extern "C" exports, zero runtime crate deps

Wasm size

Original architect estimate ~4.5 KB; nine rounds of empirical work landed at 6,155 bytes gz (60% reduction from a 15,375-byte naive baseline). The CI gate is set at 6,500 to provide ~345 byte regression headroom. The 5,120 budget proved unreachable on stable Rust without breaking changes; full reduction journey documented in crates/magna-gqlmin/SIZE.md.

The wasm build path uses nightly with -Z build-std=core,alloc + -Cpanic=immediate-abort (workspace rust-toolchain.toml stays on stable; nightly is invoked only for the wasm size-gate target).

Stability

experimental per GOVERNANCE.md. AST shape and public API may change in 0.x minor versions.

Test plan

  • cargo check --workspace — ok
  • cargo test -p magna-gqlmin — 18 lex + 20 corpus = 38/38 pass
  • cargo test -p magna-gqlmin --features pretty --test pretty — 5/5
  • cargo test -p magna-gqlmin --features "ops,validate" --test validation — 12/12 (verified pre-R11)
  • cargo test -p magna-gqlmin --features "ops,sdl,validate" --test validation — 22 expected (10 new R11 cases not yet run end-to-end on this branch; CI will verify)
  • cargo test -p magna-gqlmin --features sdl --test sdl — 8 expected (R11)
  • cargo test -p magna-gqlmin --features serde --test serde_smoke — updated to actually serialize a Document; not yet run end-to-end on this branch
  • cargo check -p magna-gqlmin --features napi — ok
  • cargo check -p magna-gqlmin --features serde — ok
  • Wasm build + Node smoke test — gqlmin_alloc/free/parse/result_free ABI durable across all rounds; simple_query.graphql → tag=0, empty_selection_error.graphql → tag=1 kind=34

The two unchecked feature combos are gated only because the R11 builder was salvaged before its full feature-test pass completed; CI will run them.

Reference docs in the repo

  • docs/topic-summaries/gqlmin-summary.md — full plan-of-record + R1–R11 history
  • crates/magna-gqlmin/SIZE.md — wasm size measurement journey
  • crates/magna-gqlmin/CHANGELOG.md — v0.1.0 unreleased notes
  • crates/magna-gqlmin/docs/director-r*.md — substance decisions per round

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu


Generated by Claude Code

claude added 30 commits May 2, 2026 17:23
Establishes the single-pointer state for the magna-gqlmin track and the
living plan-of-record that Synthesizer updates after each round.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
New experimental workspace crate that will host the lightweight GraphQL
parser. This commit lands the scaffolding only: Cargo manifest with the
locked feature-flag matrix, a crate-root lib with `ops` entry point, the
allocation-free `ParseError` types, AST type definitions for the
operations parser, and stubs for the lexer and recursive-descent parser
(filled in by steps 3 and 4).

Stability label: experimental, per GOVERNANCE.md.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Add a check-features.sh that exercises the meaningful feature combos so
the matrix doesn't silently rot. Four combos run today (default;
ops+sdl; ops+sdl+validate; ops+serde). Two are deferred until the wasm
shim arrives in R2 (no_std builds need an allocator + panic_handler the
shim will provide).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Hand-written, allocation-free GraphQL lexer covering Oct-2021 spec
section 2.1.6: punctuators, names, integer / float values, regular and
block string literals (with \""" escape), comments, insignificant commas,
BOM skip, and EOF. ASCII-only identifiers per spec — no Unicode tables.
Errors carry static `&'static str` messages and a span. 18 lexer tests
exercise every token kind plus edge cases (empty input, unterminated
string, block-string escape, negative int, float with `.` and exponent,
comment skipping, comma insignificance, BOM skip, leading-zero rejection,
unexpected character).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Hand-rolled LL(1) recursive-descent parser over the lexer (one-token
lookahead, no backtracking). Implements the executable-document subset
of GraphQL Oct-2021 spec sections 2.2-2.12: shorthand and named
query/mutation/subscription operations, fragment definitions, fragment
spreads, typed and untyped inline fragments, field aliases, arguments,
directives, variable definitions with default values, full type
references (named/list/non-null), and all eight value kinds (variable,
int, float, string, block-string, boolean, null, enum, list, object).
Numeric values keep their unparsed lexeme; string values keep the raw
slice including quotes. AST is `&'src str`-based and zero-copy.

20-case integration corpus drives acceptance: 18 expected-to-parse cases
and 2 expected-error cases (`empty_selection_error`,
`unterminated_string_error`). Each parsing case asserts >=2 specific
structural properties; error cases assert the `ParseErrorKind`
discriminant and a non-empty span.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
…play fix

Steps 5A/5B/5C in progress. Iron Law triggered at gz=15783 (3× over budget).
Investigation identifies core::fmt::Display pulling in unicode tables as primary
cause. Fix: gate Display impl behind cfg(feature = "std"). Re-measurement pending.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Iron Law triggered: gz=15375 bytes (3x over 5120-byte budget).
Primary cause: 7 distinct Vec<T> types in the parser generate ~10 KB of
monomorphized grow/drop/realloc code — far exceeding the architect's 1.5 KB
estimate which assumed a bump-allocated AST design.

Risk ladder fully tried (rungs 0-6): wee_alloc saves ~1.8 KB gz (→ 13978
bytes) but still 2.7x over budget. Structural fix (bumpalo arena or
span-indexed arrays) needed in R3.

Wasm binary is functionally correct: smoke test passes (tag=0 for valid
docs, tag=1/kind=34 for empty selection set).

docs/investigation-r2-wasm-size.md: complete root-cause analysis with
fix paths A/B/C ranked by impact. SIZE.md: honest measurements for all
pipeline stages and risk-ladder rungs tried.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
error.rs:
- Gate core::fmt::Display impl behind #[cfg(feature = "std")] to
  keep wasm build clean of fmt machinery. (Had no size impact since
  Debug derives were already cfg_attr-gated in R1.)
- Add wire-format contract comment above ParseErrorKind: lex errors
  occupy discriminants 1..=5, parse errors 32..=43, gap intentional
  so JS decoders can branch on kind < 32.

lex.rs / parse/mod.rs:
- Gate all Debug derives behind #[cfg_attr(any(feature = "std", test), derive(Debug))]
  to prevent fmt machinery from leaking into the no_std/wasm build.

scripts/check-features.sh:
- Re-enable the 2 previously-deferred combos:
  * ops,wasm (wasm32 target — now that the shim ships)
  * Note: bare ops-only wasm32 is invalid without the allocator from
    the wasm feature; removed from the active combos with a comment.
- Add 3 new combos flagged by Verifier R1:
  * ops,pretty
  * ops,wasm-bindgen (wasm32 target)
  All 7 active combos now pass.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
.github/workflows/gqlmin-size.yml:
- Triggers on push/PR when magna-gqlmin crate files or workspace
  root Cargo.toml/Cargo.lock change.
- Downloads binaryen version_119 for wasm-opt.
- Builds with release-wasm profile (opt-level=z, lto=fat, panic=abort).
- Optimizes with wasm-opt -Oz --strip-debug --vacuum
  --enable-bulk-memory --enable-sign-ext.
- Fails the PR if gzipped wasm exceeds 5120 bytes.
- Currently expected to FAIL (gz=15375; see SIZE.md for root-cause
  and docs/investigation-r2-wasm-size.md for fix paths).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
scripts/wasm-smoke.mjs: Node ESM script that exercises the actual
.wasm artifact (not the Rust-native parse path):
  Test 1: simple_query.graphql → tag=0 (success)
  Test 2: empty_selection_error.graphql → tag=1, kind=34
          (EmptySelectionSet discriminant)

Smoke test result on this environment (Node v22.22.2):
  PASS test 1: valid document parsed successfully (tag=0)
  PASS test 2: empty selection error detected (tag=1, kind=34, span=8..11)
  smoke: ok

Usage: node scripts/wasm-smoke.mjs [/path/to/gqlmin.opt.wasm]
Default path: /tmp/gqlmin.opt.wasm (produced by build pipeline).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Wire up the `serde` feature so downstream code can opt in:

- `serde = ["dep:serde"]` in Cargo.toml
- New `serde` optional dep (default-features = false, derive + alloc),
  no_std-compatible — does not pull std into the wasm build path
- `tests/serde_smoke.rs` confirms the feature compiles and that public
  AST imports resolve under it

Real `#[derive(Serialize, Deserialize)]` on the AST types in
`parse/mod.rs` is DEFERRED to a post-R3 round. R3 owns the AST shape
this round (bumpalo migration); concurrent derives would conflict.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Replace the seven distinct Vec<T> types in the operations parser with
bumpalo::collections::Vec<'bump, T> so all list collections share a
single monomorphized grow/drop/realloc machinery. This collapses the
~10 KB gz of per-type Vec code identified in R2's investigation into
roughly one copy.

Public API change (allowed under 0.x experimental policy):
  Document<'src> -> Document<'src, 'bump>
  parse_executable_document(src) -> parse_executable_document(arena, src)

The caller owns the bumpalo::Bump arena and drops it after extracting
what they need from the AST. The wasm shim allocates a fresh Bump per
gqlmin_parse call and drops it before returning — the wasm-visible ABI
is unchanged.

Also:
- Added bumpalo as an optional runtime dep gated on the always-on `ops`
  feature; default-features = false + features = ["collections"] so
  bumpalo stays no_std-compatible for the wasm build.
- Box<Type> in List/NonNull replaced with &'bump Type so the AST has
  zero owned boxes.
- corpus tests now construct a Bump per test; all 20 R1 corpus cases
  ported.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Wire up the `napi` feature so a future round can add real AST-to-JSON
serialization without touching feature plumbing again:

- Cargo.toml: `napi = ["std", "ops", "serde", "dep:napi", "dep:napi-derive", "dep:serde_json"]`
- New optional deps: napi v2 (napi9 features), napi-derive v2, serde_json v1
- `mod napi;` declared in lib.rs under `cfg(feature = "napi")`

The `src/napi.rs` module itself was added in c27b0af. Per the briefing,
the function body is a placeholder that returns a stable JSON envelope
without the parsed AST — real AST encoding requires `serde::Serialize`
derives on the parser's AST types, which are deferred until R3's
bumpalo migration lands.

Acceptance: `cargo check -p magna-gqlmin --features napi` succeeds.
The actual `.node` artifact build (napi-rs build script) is not
attempted in R4 — that's a later round once the binding is fleshed out.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Completes the bumpalo arena migration started in c27b0af. The previous
commit captured parse/mod.rs but the dependency wiring, public API
re-export, wasm shim allocation, and corpus test ergonomics were left
on the floor. This commit lands them as a single atomic change so the
crate compiles end-to-end.

- Cargo.toml: add `bumpalo` (optional, gated on the always-on `ops`
  feature). default-features = false + features = ["collections"]
  keeps it no_std-compatible for the wasm build.
- lib.rs: re-export `bumpalo::Bump`; update `parse_executable_document`
  signature to take `(arena, src)` and return `Document<'src, 'bump>`;
  add `#[allow(unused_extern_crates)]` to `extern crate alloc` so the
  rust_2018_idioms lint passes across all feature combinations.
- wasm.rs: allocate `bumpalo::Bump::new()` per `gqlmin_parse` call,
  parse into it, encode the binary result, drop the arena. The
  wasm-visible ABI is unchanged.
- tests/corpus.rs: every test allocates a `Bump` arena before parsing.
  Type::List/NonNull pattern matches updated from `inner.as_ref()` to
  `*inner` since the variants now hold `&'bump Type<...>` instead of
  `Box<Type<...>>`.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
The bumpalo migration introduced a borrow-checker issue in
gqlmin_parse: the match expression's implicit temporary borrows from
the Bump arena, but the arena drops at the end of the function, which
the compiler reports as E0597 ("bump dropped while still borrowed").
Bind the encoded result pointer to a local so the temporary
Result<Document, ParseError> is dropped before the arena.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
…ial)

Implements operations-only static validation that does not require a
schema. Five rules ship in this round:

  1. NoUndefinedVariables  (5.8.3) — used vars must be declared
  2. NoUnusedVariables     (5.8.4) — declared vars must be used
  3. NoUnusedFragments     (5.5.1.4) — defined fragments must be spread
  4. KnownFragmentNames    (5.5.2.1) — spreads must reference a definition
  5. UniqueOperationNames  (5.2.1.1) — names unique; anonymous-only-if-sole

The schema-aware rule set (FieldsOnCorrectType, KnownTypeNames,
ScalarLeafs, ArgumentsOfCorrectType, etc.) is deferred to R6 once the
SDL parser lands.

Public API:

```rust
pub struct ValidationError { pub rule: &'static str, pub span: Span, pub message: &'static str }
pub fn validate_operations<'src, 'bump>(doc: &Document<'src, 'bump>) -> Vec<ValidationError>
```

Re-exported from the crate root under `cfg(feature = "validate")`.

12 tests cover passing + failing case for each rule plus the
anonymous-with-others edge case and the solitary-anonymous pass case.

R3-aftermath: this round's validate code consumes the bumpalo-arena AST
(`Document<'src, 'bump>`) directly. The validator only borrows shared
references, so the second lifetime is threaded through opaquely.

Cargo.toml: `validate = ["std"]` (was `["sdl", "std"]`). Schema-aware
rules will re-add the `sdl` dep when implemented in R6.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Bumpalo arena migration successfully collapsed Vec monomorphization
(150 → 90 functions, the seven distinct RawVec impls became one), but
bumpalo's panic-format paths transitively pulled in core::str Debug
formatting and the Unicode printable.rs tables, plus ~1 KB of bumpalo
library code itself. Net: gz=17490 bytes — 2115 bytes WORSE than the
R2 baseline (15375), 2.5x over the 7000-byte Iron Law ceiling, 3.4x
over the 5120-byte budget.

R3 is BLOCKED. Investigation document ranks four candidate next moves:

1. Fix B (span-indexed flat arrays) — RECOMMENDED.
2. Hand-rolled bump arena — uncertain, doesn't address full bloat.
3. Option C (revise budget to 8 KB) — fastest escape hatch.
4. build-std on nightly — may reach 5 KB without rewrite.

Smoke test still passes (tag=0 / tag=1+kind=34); the wasm ABI is
unchanged. All 38 native tests pass. The functional contract is
preserved — only the size budget has regressed.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Removes the bumpalo crate dep and reverts the AST to the R2 single-lifetime
shape. R3 measured the bumpalo migration at gz=17,490 (worse than R2),
because bumpalo's panic paths pull in core::str Debug formatting and
Unicode `printable.rs` tables. Iron Law fired; user chose Option B
(span-indexed flat arrays). Phase 1 lands a clean baseline so phase 3 can
implement the structural rewrite from a known-good starting point.

Changes:
- Cargo.toml: drop the `bumpalo` optional dep and the `dep:bumpalo`
  entry under `ops`.
- src/parse/mod.rs: revert AST types to `Document<'src>` (single
  lifetime). Lists store `alloc::vec::Vec<T>` again. `Type::List` /
  `Type::NonNull` use `Box<Type>` (R2 shape, not R3's `&'bump Type`).
  `parse_executable_document` takes only `src: &str`.
- src/lib.rs: drop the `pub use bumpalo::Bump` re-export and revert
  the public entry point signature.
- src/wasm.rs: drop the `Bump::new()` per-call alloc and the let-bind
  borrow-checker workaround.
- src/validate.rs: drop the `'bump` lifetime parameter from every
  signature; update the module doc comment.
- tests/corpus.rs: drop the per-test `Bump::new()` and the unused
  `Bump` import; switch `*inner` matches over `Type::NonNull`/`List`
  to `inner.as_ref()` (Box → reference instead of arena reference).
- tests/validation.rs: drop the `Bump` setup in the `rules()` helper.

Verification:
- cargo check --workspace ok
- cargo test -p magna-gqlmin → 38/38 (18 lex + 20 corpus)
- cargo test --features pretty --test pretty → 5/5
- cargo test --features "ops,validate" --test validation → 12/12
- cargo check --features napi / --features serde ok
- wasm build + opt + smoke: raw=37254 opt=32221 gz=15298 (vs R2=15375),
  smoke test passes (tag=0 / tag=1+kind=34, ABI unchanged).

Phase 1 leaves the project at "R2-shape with R4 add-ons" — gz=15298, no
bumpalo, single-lifetime AST. Phase 2 (design note) and phase 3 (implement
span-indexed AST) follow in subsequent commits.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Documents the chosen approach for Option B's structural rewrite (phase 3).
Picks Approach 2B (single typed Node arena: one Vec<Node> with a tagged
enum for every list-element type) per the Director brief's recommendation
— simpler than 2A (no offset/decode dance), lower-risk than 2C (no new
unsafe code, no new way to silently re-introduce core::fmt panic paths).

Layout: every list field becomes a slice of a unified Vec<Node>; the
Node enum carries every per-list element shape (Definition,
VariableDefinition, Directive, Argument, Selection, ObjectField, Value).
Parent structs expose typed iterator/index accessors that project the
correct variant. Phase 3 will keep Box<Type> for the tiny recursive
Type::List/Type::NonNull case (only two Box instantiations exist).

Risk assessment includes: (1) the bumpalo-shaped trap of bounds-check
panic paths is mitigated by using `get(i)` over `[i]` in accessors;
(2) enum-tag match cost is irrelevant for wasm size; (3) corpus-test
breakage is mitigated by preserving the `&[T]`-shaped API via wrappers.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Collapses the seven previously-distinct Vec<T> AST collections into ONE
shared Vec<Node<'src>> arena per Document. Each list field on every AST
node is a NodeRange { start, len } slice into Document::nodes; the Node
enum carries every shape that can appear inside a list (Definition,
VariableDefinition, Directive, Argument, Selection, ObjectField, Value).
Public API stays single-lifetime: Document<'src>.

Why a scratch stack: parser recursion would otherwise interleave
outer-list elements with inner-list contents in the final arena. The
parser carries a single Vec<Node> scratch buffer where in-flight list
children accumulate; on closing a list, scratch[start..] drains en bloc
into the final nodes arena. This keeps every NodeRange contiguous while
sharing one Vec<Node> instantiation across the entire parser. Same Node
element type for both the scratch and the final arena, so still ONE Vec
monomorphization total.

Type::List / Type::NonNull keep Box<Type> — only two Box<Type>
instantiations exist, and the wrapping cost is small.

Public API:
- New types: NodeRange { start: u32, len: u32 } and the Node enum.
- New typed accessor methods on Document: definitions(), directives(r),
  arguments(r), variable_definitions(r), selections(r), object_fields(r),
  list_values(r). Each returns a NodeSlice<'doc, 'src, T> that supports
  .len(), .is_empty(), .get(i), [i] (Index), and iter()/IntoIterator —
  preserving the call-site shape of the previous &[T] slice access.
- SelectionSet drops its 'src lifetime parameter (carries no &'src str).
- The Document::definitions field is renamed `definitions_range` to free
  up the `definitions()` method name.

Validate.rs and the corpus tests are updated to thread &Document and
use the typed accessor methods. Behavior is unchanged.

Wasm-size measurement (next commit will land SIZE.md update):
- raw=36017 opt=31273 gz=14895
- vs R5 phase 1 baseline: 15298 → 14895 (Δ = -403 bytes gz)
- vs R2 baseline: 15375 → 14895 (Δ = -480 bytes gz)
- vs R3 (bumpalo, refuted): 17490 → 14895 (Δ = -2595 bytes gz)
- vs 5120 budget: still 9775 bytes over.
- Function count: 150 (R2) → 90 (R3) → 77 (R5). Further collapse beyond
  R3 confirms the structural reorganization worked on the code-size
  axis.

The remaining gz overhead is dominated by the data section: panic
strings ("byte index … is not a char boundary", "slice index …",
"index out of bounds: the len is …", "out of range for slice of
length …") plus the Unicode printable.rs property tables (~4 KB of
binary data) plus the dlmalloc allocator (~1 KB). These are reachable
because the parser body uses safe slice indexing (self.src[s..e],
self.nodes.get(start..end), Vec::extend) which retains bounds-check
panic call sites that transitively reference core::str Debug formatting.
This is the SAME family of bloat that killed R3's bumpalo migration —
not a regression introduced by the span-indexed design, but a baseline
cost that comes with using safe slice/Vec operations on stable Rust.

R6+ tuning candidates (not in this round's scope):
- swap dlmalloc → wee_alloc (R2 measured ~1.4 KB gz savings)
- replace panic-formatting indexers with `get(...).unwrap_or(default)`
  in the parser hot path so panic strings become unreachable
- audit lex.rs for remaining `[..]` slice operations
- ultimately Option F (build-std nightly) if stable-toolchain ceiling
  proves to be in the 8–10 KB range

Verification:
- cargo check --workspace ok
- cargo test -p magna-gqlmin → 38/38 (18 lex + 20 corpus)
- cargo test --features pretty --test pretty → 5/5
- cargo test --features "ops,validate" --test validation → 12/12
- cargo check --features napi / --features serde ok
- wasm build + smoke: PASS test 1 (tag=0) + PASS test 2 (tag=1, kind=34).
  ABI durable.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Records the R5 measurement after the span-indexed AST landed. Verdict:
PARTIAL.

Pipeline:
- raw=36017 opt=31273 gz=14895
- vs 5120-byte budget: 9775 bytes over.
- vs 7000-byte Iron Law ceiling: 7895 bytes over.
- vs R2 baseline (15375): -480 bytes (improvement).
- vs R3 bumpalo (17490): -2595 bytes (improvement).
- Function count: 150 (R2) → 90 (R3) → 77 (R5).

Iron Law check: R5 did NOT regress vs R2 or R3. The structural fix
landed cleanly; the absolute gz figure is still above budget but the
Vec-collapse insight from R2 is empirically validated by the
77-function final count. Structural-fix attempt counter advances to
2/5 (R3 was 1/5; three attempts remain).

Next-largest bloat (per `wasm-dis` of /tmp/gqlmin.opt.wasm):
1. Unicode `printable.rs` property tables (~3-4 KB gz). Reachable from
   `core::str` Debug-formatting via the parser's safe slice-indexing
   (self.src[s..e], etc.). Mitigation candidate: replace with
   .get(...).unwrap_or("") in the wasm parser body.
2. dlmalloc → wee_alloc swap (~1.4 KB gz, R2 measured).
3. Custom panic-handler / fmt::Write shim (medium-confidence, partial).
4. Option F (build-std nightly) — requires user approval for toolchain
   split; estimated to land near the 5120 budget.

Acceptance evidence (Phase 4 verification):
- cargo check --workspace ok
- cargo test -p magna-gqlmin → 18 lex + 20 corpus = 38/38
- cargo check --features pretty / --features serde / --features napi ok
- cargo test --features pretty --test pretty → 5/5
- cargo test --features "ops,validate" --test validation → 12/12
- node scripts/wasm-smoke.mjs: tag=0 (success) + tag=1+kind=34
  (EmptySelectionSet) — ABI durable.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
R5 PARTIAL — span-indexed AST landed (gz=14,895; Δ=−480 vs R2;
function count 150→77) but still over budget and over Iron Law
ceiling. Recommendation: R6 = rung 1 (Unicode/slice-panic elimination,
est. −3 to −4 KB). Surface deferred one round to land empirical data
before forcing budget-vs-Option-F decision. Counter advances to 2/5
entering R6; three rounds remain.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
claude added 27 commits May 3, 2026 21:40
Catalogues every &str slice and &[u8] index access on the parser hot
path that pulls in core::str / core::slice panic-format machinery (and
transitively the Unicode printable.rs property tables). 1 &str slice +
19 byte indexes in lex.rs, 1 &str slice + 1 &Node index in parse/mod.rs.
Phase 2 replaces each with an Option-returning equivalent.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
…d.rs

Replaces every panic-on-bounds &str slice and &[u8] index in the
parser/lexer hot path with the Option-returning equivalent, breaking
the reachability path from the parser body to core::str::Debug and
the Unicode printable.rs property tables (~3-4 KB gz).

- lex.rs: 17 byte-index reads converted to .get(i).copied()/match
  Some(&b)=>… patterns; 1 &str slice converted to .get(s..e).unwrap_or("").
  peek_byte() collapses to a one-line bytes.get().copied().
- parse/mod.rs: parser slice() helper switched to .get(s..e).unwrap_or("");
  NodeSlice::Index funnels out-of-bounds through the existing format-free
  panic_invariant() instead of through core::slice::index_fail.

No new unsafe (forbid(unsafe_code) preserved outside wasm.rs). No API
changes. No new dependencies. Fallback sentinels (0 byte, "" string)
are defensively unreachable: the bound was already checked by the
caller; the sentinel just removes the redundant panic edge LLVM
couldn't prove dead.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
R6 result: gz=10006 bytes (Δ=−4889 vs R5's 14895), well above the
R5-estimated 3-4 KB savings from the slice-panic-elimination rung.

wasm-dis confirms the Unicode printable.rs property tables, the
core::str char-boundary panic message, the lex.rs filename literal,
and the slice "range end index … out of range" message are all
absent from the R6 binary — empirically validating R5's bloat
hypothesis.

Status: PARTIAL — partial-over-ceiling band per R6 brief (7,001 ≤
gz ≤ 11,000). Gap to budget remains 4,886 bytes; gap to Iron Law
ceiling remains 3,006 bytes. ABI smoke unchanged (tag=0 / tag=1+
kind=34). All 38 + 5 + 12 tests pass. Iron Law does NOT fire.

Next-rung targets remaining (per wasm-dis): Vec capacity-overflow
panic strings + raw_vec/vec/alloc filename literals (≈ rung 3 ‘panic-
handler / fmt::Write shim’), dlmalloc internal asserts (≈ rung 2
‘wee_alloc swap’), and one residual ‘slice index starts at … but
ends at’ message whose site is not yet identified.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Switch wasm size-gate to nightly + `-Z build-std=core,alloc` with
`-Cpanic=immediate-abort` (RUSTFLAGS form — the older `-Z
build-std-features=panic_immediate_abort` form now emits a
compile_error on recent nightlies). Workspace `rust-toolchain.toml`
stays on stable; nightly is invoked only for the size-gate target.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Try the production wasm path (nightly + build-std + immediate-abort)
when nightly + rust-src are installed; fall back to a stable cargo check
(compile-only, no size-gate) otherwise with a clear message about the
prereq command. Keeps the script portable to contributor machines that
haven't installed nightly yet, while validating the production path
when available.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Path β landed: gz=8605 bytes (R6 was 10006; saved 1401 bytes).
Hypothesis confirmed at the data-section level — the R6 binary's
filename literals, alloc panic strings, dlmalloc assertions, and
ASCII pair table are all physically absent from R7. Remaining 8.6 KB
is essentially pure code (64 functions of parser + dlmalloc) plus a
~55-byte keyword pool.

The 1.4 KB saving falls 3.5 KB short of Director R6's projection
because (1) R6 already captured the largest data win (Unicode
printable.rs ~3-4 KB) so R7 stripped the smaller residual, (2) code
size dominates after data is stripped, (3) dlmalloc remains (rung 2
target).

R7 measures 8605 — 105 bytes above the brief's 8500 Iron-Law cutoff.
Investigation in `investigation-r7-buildstd-shortfall.md` reconciles
the "literal trigger fires" vs "hypothesis empirically confirmed"
contradiction and ranks next-step options for the user.

ABI durable: smoke tag=0 / tag=1+kind=34 unchanged across R2/R3/R5/R6/R7.
Tests: 38/38 ops + 5/5 pretty + 12/12 validation. napi + serde compile.

Used new nightly flag form: `RUSTFLAGS="-Zunstable-options
-Cpanic=immediate-abort"` plus `-Z build-std=core,alloc`. The older
`-Z build-std-features=panic_immediate_abort` from the brief now emits
a compile_error pointing to the new flag form.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Replace dlmalloc::GlobalDlmalloc with an inline BumpAllocator over a
static mut [u8; 256 KiB] arena. The wasm shim's parse-once-then-drop
lifecycle does not need a real free path; dealloc is a no-op.

Reset strategy: fill-then-rollover (no in-call reset). Resetting at
gqlmin_parse entry would clobber the source bytes that gqlmin_alloc
just wrote at offset 0. 256 KiB is sufficient for many calls of typical
query sizes; production hosts that need more capacity can recycle the
wasm instance.

Uses core::ptr::addr_of_mut! to avoid the static_mut_refs lint without
introducing UB. Returns null on overflow (no panic strings).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
The wasm build's only runtime dep is now gone — the inline bump
allocator (previous commit) replaces dlmalloc::GlobalDlmalloc. The
wasm feature dep list shrinks by one (dep:dlmalloc removed); no new
deps added. Cargo.lock updated to drop dlmalloc 0.2.13.

scripts/check-features.sh comment lines updated to reference the new
allocator (no functional change).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
R8 wasm size pipeline:
  raw  = 16,734 bytes  (R7: 23,448; Δ=−6,714)
  opt  = 14,560 bytes  (R7: 19,940; Δ=−5,380)
  gz   =  6,254 bytes  (R7:  8,605; Δ=−2,351, ~27% reduction)
  fns  =     33        (R7:     64; −31, dlmalloc family removed)

Lands in the "5,121 ≤ gz ≤ 6,500" PARTIAL-close band per Director R7's
R8 brief. Beats the projected ~6,800 R8 ceiling by ~550 bytes. Budget
gap remains 1,134 bytes; one more focused rung (parser code reduction
or block-string drop) may close it.

Smoke test: tag=0 success / tag=1 kind=34 EmptySelectionSet — ABI
durable across R2/R3/R5/R6/R7/R8.
Native tests: 38/38 ops + 5/5 pretty + 12/12 validation pass; napi +
serde features compile; workspace cargo check clean.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Catalog parser and lexer helper functions in src/parse/mod.rs and
src/lex.rs by line count, call-site count, and existing attribute.
Identify 11 candidates for `#[inline(always)]` (7 in parser, 4 in
lexer). No merge candidates retained — single-call-site helpers will
gain `#[inline(always)]` rather than be textually deleted, preserving
readability per brief.

Bans honored: no API change, no state-table rewrite, block-string
parsing preserved.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Promote 11 small parser/lexer helpers to `#[inline(always)]`:

src/parse/mod.rs:
- Document::slice (7 call sites; was #[inline])
- Parser::new (1 site; merge-equivalent without textual deletion)
- Parser::peek (~12 sites; hot path)
- Parser::bump_tok (~14 sites; hot path)
- Parser::slice (5 sites; identical body each site)
- Parser::expect (7 sites; lets LLVM specialise per (kind, err) pair)
- Parser::open_list (was #[inline]; trivial body)
- Parser::close_list (was #[inline]; small + multi-call)

src/lex.rs:
- Span::new (many sites; one-liner constructor)
- Lexer::single (13 punctuator sites; lets LLVM see kind constant)
- Lexer::lex_spread (1 site; merge-equivalent)
- Lexer::lex_name (1 site; merge-equivalent)
- Lexer::peek_byte (~12 sites in lex_number; one-liner)

Deliberately NOT inlined: lex_number, lex_string, skip_insignificant
(too large; would balloon next_token). Projection helpers
(project_definition et al.) untouched — addressed as fn pointers.
panic_invariant untouched — single-emission abort point.

No API change; block-string parsing path unmodified.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
R9 measurement: gz=6155 (Δ=−99 vs R8 6254). Lands in the brief's
"6,051 ≤ gz < 6,254" band — PARTIAL but underwhelming. Iron Law
does NOT fire on the committed conservative variant.

Phase-3 aggressive variant (all 11 audit candidates `inline(always)`)
measured gz=6847 (+593 vs R8) and tripped Iron Law. Bisection per
brief investigation guidance identified the regressors:
- Parser::peek (+433 vs minimal): 5-line body × 12 sites
- Parser::bump_tok (+204): 5-line body × 14 sites
- Parser::slice (+68): 4-line body × 5 sites

Final committed inline-always set is the two true one-liners:
- Span::new
- Lexer::peek_byte

Other audit candidates reverted to plain `#[inline]` (or no attribute).

Investigation note: docs/investigation-r9-inline-regression.md.

Verification: 38 ops + 5 pretty + 12 validation tests pass; napi +
serde compile; wasm smoke ABI durable (tag=0/tag=1+kind=34); the
`case_block_string_arg` corpus test passes (block-string parsing
preserved).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Post-R9 Option A acceptance. Topic retired on size axis at gz=6,155.
CI gate raised from 5,120 to 6,500 to provide ~345 byte regression
headroom. SIZE.md final-disposition section documents the R2->R9
60% reduction journey. README adds a Size section.

Recovered work (Builder R10 hung in cargo verification loops; file
edits committed by Team Lead).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
…mpletion)

Adds #[cfg_attr(feature = "serde", derive(...))] to the public AST
types in src/parse/mod.rs and src/lex.rs (Span). Updates
tests/serde_smoke.rs to actually serialize a parsed Document via
serde_json::to_string and assert non-empty output.

cargo check -p magna-gqlmin passes (exit 0); cargo test corpus
38/38 still pass.

Recovered work (Builder R10 hung in cargo verification loops; file
edits committed by Team Lead).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Replaces the R4 placeholder body with the real implementation:
parses the input, builds a stable JSON envelope with serde_json
({"ok":true,"document":...} on success, {"ok":false,"error":{
"kind":...,"span":[s,e]}} on parse error). Consumes the AST serde
derives added in the previous commit.

Recovered work (Builder R10 hung in cargo verification loops; file
edits committed by Team Lead).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Initial CHANGELOG.md for magna-gqlmin (v0.1.0 unreleased) cataloguing
the lexer, parser, validation rules, pretty errors, AST serde derives,
napi binding, custom bump allocator, and the achieved 6.0 KB gz wasm
size. GOVERNANCE.md gains the magna-gqlmin row as experimental.

Recovered work (Builder R10 hung in cargo verification loops; file
edits committed by Team Lead).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
885-line SDL parser covering Oct-2021 spec § 3 type-system definitions:
SchemaDefinition, Scalar/Object/Interface/Union/Enum/InputObject type
defs, DirectiveDefinition, field defs with arg lists, input field defs,
description strings (regular and block). Reuses the existing lexer.

Public API under `#[cfg(feature = "sdl")]`: parse_schema, SchemaDocument,
TypeSystemDefinition, and per-kind type-def structs.

Tests in tests/sdl.rs cover 8 named cases.

cargo check -p magna-gqlmin → ok (1m 09s).

Recovered work (Builder R11 was running verification with 540s timeouts;
Team Lead salvaged at user's request to unblock fellwork/api umbrella).

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
Adds KnownTypeNames, FieldsOnCorrectType, ScalarLeafs, KnownArgumentNames,
ArgumentsOfCorrectType under `#[cfg(all(feature = "sdl", feature = "validate"))]`.

Public API: validate(doc, schema) -> Vec<ValidationError> runs all 10
rules (5 ops-only from R4 + 5 schema-aware here).

tests/validation.rs extended with 10 more cases (2 per new rule).

Recovered work.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
README documents the full feature matrix (ops/sdl/validate/pretty/serde/napi).
CHANGELOG notes SDL parser and 5 additional schema-aware validation rules.

Recovered work — final feature round of session.

https://claude.ai/code/session_01R5CSNvnAEYc7FCiPPgZspu
@changeset-bot

changeset-bot Bot commented May 4, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: b5b0762

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@srmcguirt
srmcguirt merged commit 03b8073 into main May 4, 2026
4 of 6 checks passed
@srmcguirt
srmcguirt deleted the claude/graphql-parser-lightweight-b6Vi8 branch May 4, 2026 17:29
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.

2 participants