Skip to content

The embedded YAML parser reads bytes, not one-character Strings - #370

Merged
284km merged 5 commits into
mainfrom
rails-ar-psych-bytes
Nov 26, 2026
Merged

284km merged 5 commits into
mainfrom
rails-ar-psych-bytes

Conversation

@284km

@284km 284km commented Nov 26, 2026

Copy link
Copy Markdown
Owner

Why

After #351 and #353, eager_test's citations fixture (65,536 rows) was still the peak. Loaded and collected, it left about 1.2 GB that was not live data: FixtureSet.reset_cache + GC.start moved nothing.

A plain YAML.load of the rows shows the same thing. At 16,384 rows, after keeping the result and collecting, ruby holds +30 MB and mere +232 MB. Most of mere's extra is String slots: the parse makes about 110 Strings a row and keeps about 6. A String's slot is never reused, and a page of 4,096 is freed only when none of its Strings lives. The survivors are spread over every page, so the dead slots stayed: 1.8M slots, 75 MB.

lib/psych_parser.rb's scanner made a new one-byte String for every position it looked at: __char, and __advance's return value. Around that it also built a Hash of punctuation per token and an Array per include? question.

What (4 commits; the rewrite and the regeneration are separate)

  1. Scanner reads bytes. __byte is getbyte on the same window, and comparisons are on Integers; YAML's syntax is ASCII.
    • __advance answers the byte and counts marks exactly as before: a line at \n, a column and an index per character.
    • A directive, an anchor's or alias's name, a tag and a scalar are cut from the source by byte position, as quoted and plain scalars already were. The source is UTF-8 by this point (UTF-16 is converted when parse begins), so a multibyte character is never split or re-encoded.
    • __skip needs no String on an ASCII-only source; a plain scalar is copied once instead of three times; the punctuation and indicator tables and the structure's lists are constants.
  2. Regenerate m_psych_lib.mere.
  3. Differences from ruby found while checking, aligned with libyaml.
    • An anchor's or alias's name is letters, digits, _ and -, ended by a blank or one of ? : , ] } % @ or the backquote. Anything else is an error at the & or *, with context "while scanning an anchor" / "an alias". A multibyte name used to be accepted, and an empty one was reported a column late.
    • A CRLF after a block scalar's header and at the end of its lines is one line break. a: |\r\n x\r\n used to be "did not find expected comment or line break".
    • A tab where a token starts, and %, @ or the backquote there, report context "while scanning for the next token".
    • Corpus 1072 covers:
      • multibyte (Japanese, emoji, combining) keys, values, comments, and quoted, block and flow scalars, plus anchors;
      • error marks after multibyte characters;
      • UTF-16LE/BE with and without a BOM, and a UTF-8 BOM;
      • CRLF, tabs and trailing blanks;
      • a handler's event marks.
  4. Regenerate m_psych_lib.mere.

The rewrite alone (commit 1) changes no output: main and commit 1 give identical results on all 40 cases of the check.

Still different from ruby (from before this PR, not the scanner)

These are structural checks libyaml makes and this parser does not; they are left out of the corpus:

input ruby (libyaml) mere
日本: 1\n 語: 2\n x\n SyntaxError 2:4 "mapping values are not allowed in this context" {"日本"=>{"1 語"=>2}}
鍵: 値: 二重\n SyntaxError 1:5 "mapping values are not allowed in this context" {"鍵"=>{"値"=>"二重"}}
a: &x, v / a: &ab}c v / a: &ab]c SyntaxError 1:1 "did not find expected key" {"a"=>nil}
a: *x? SyntaxError 1:6 "mapping keys are not allowed in this context" Psych::AnchorNotDefined
UTF-16LE given as a binary String, no BOM SyntaxError 1:1 "control characters are not allowed" SyntaxError 1:1 "invalid leading UTF-8 octet"

Checked (Mere 9dec2ff6)

YAML.load of the fixture's rows, default collector, result kept:

rows time main → this peak footprint kept after GC
16,384 75.2 → 63.4 s 544 → 436 MB 315 → 208 MB
65,536 298.6 → 259.3 s 1,632 → 1,203 MB 979 → 553 MB
  • At 16,384 rows, String slots drop from 1.8M to 166k, and the String store from 75 to 10 MB.
  • The time left is the interpreter's: the event stream is about 2.5 ms a row, roughly 1,600 builtin calls (Integer compares, [], getbyte) at about a microsecond each, on both engines.
  • test/psych (635): MATCH 635 on the evaluator and the VM, index on and off.
  • The 16 YAML programs already in the corpus match ruby.
  • Corpus: 994/994 on the evaluator and the VM, index on and off, MERE_RUBY_SHAPES_CHECK=1.

eager_test with this, #353 and #355 together is still MEMORY_LIMIT (2.10 GB at 371 s); the peak has moved from the fixture to the preload. That is the next step.

Loop record: loop/2026-11-27-rails-ar-psych-bytes.md.

🤖 Generated with Claude Code

The scanner's __char answered a new one-byte String for every character it
looked at, and __advance returned it; a YAML.load of activerecord's
citations fixture made about 110 Strings a row and kept about 6. A String's
slot is never reused and a page of them goes back only when none lives, so
the dead ones stayed: 16,384 rows left 1.8M slots, 75 MB.

The syntax of YAML is ASCII, so the scanner now reads bytes (__byte,
getbyte on the window) and compares Integers; __advance answers the byte.
What a token holds -- a directive, an anchor's or alias's name, a tag, a
scalar -- is cut from the source by byte position, as quoted and plain
scalars already were, so a multibyte character is never split. The marks
(index, line, column) are counted exactly as before.

Also: a run's character count needs no String when the source is ASCII
only (__skip), a plain scalar is copied once instead of three times, and
the punctuation tables and the structure's include? lists are constants
rather than a Hash or Array made per token.
Found while checking the byte scanner against ruby (corpus 1072):

- An anchor's or alias's name is letters, digits, '_' and '-', ended by a
  blank or one of ? : , ] } % @ ` -- anything else is an error at the & or
  *, "while scanning an anchor" / "an alias". A multibyte name was taken,
  and an empty one was reported one column late with the wrong context.
- A CRLF after a block scalar's header, and at the end of its lines, is one
  line break: `a: |\r\n  x\r\n` was "did not find expected comment or line
  break".
- A tab where a token starts, and a reserved character (% @ `), report
  "while scanning for the next token".

Corpus 1072: multibyte keys, values, comments, quoted, block and flow
scalars, anchors; error marks after multibyte characters; UTF-16 with and
without a BOM, a UTF-8 BOM; CRLF, tabs and trailing blanks; and a
handler's event marks.

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 59996f5c9d0cb60310ad8290d7bd7264383be809 against fetched current main 29016cb8b45142e7e57af80fbb49ae03d4916fb3. No new actionable findings established. The scanner consistently keeps byte positions for slicing while counting UTF-8 leading bytes for character marks, and the CRLF handling is applied to both the block header and its content.

Independent focused validation on Ruby 4.0.10: generated the full embedded Psych Ruby implementation with tools/gen_psych_lib.rb --ruby and exercised it in a separate process, alongside the main parser and native reference Psych. Corpus 1072 matches reference stdout/stderr/exit status exactly with the head implementation; main aborts at its existing multibyte anchor/alias divergence. A separate 43-case matrix covers multibyte/combining/emoji scalars, strings crossing the 65,536-byte window, CRLF blocks, anchor delimiters and document directives. Matching rows improve from 27/43 on main to 38/43 on head, with no previously matching row lost. Remaining structural/error differences were not counted as passes. Regenerating m_psych_lib.mere is byte-identical. No AGENTS.md/CLAUDE.md files are present in the fetched repository trees.

These are Ruby-source checks of the actual embedded implementation, not executions of a rebuilt Mere binary. I did not independently rerun the full Mere corpus, original Psych whole-file suites, large fixture/RSS measurements or Linux acceptance. The author's measurements remain attributed to the PR record. Hosted CI is incomplete and queues are not passes. No merge: recorded hold_all_merges/new_failure_review_required remains active.

@284km 284km left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of 59996f5c. No Critical/Major/Minor findings. The embedded YAML scanner reads bytes with getbyte and compares Integers instead of building a one-character String per byte. Tokens are cut from the source by byte position, and columns are counted per character, skipping UTF-8 continuation bytes, as libyaml does. test/psych 635 passes in four modes, and the PR lists the remaining pre-existing differences from Ruby. YAML.load at 65,536 rows goes from 299 to 259 s, and its peak from 1,632 to 1,203 MB. The review bot reviewed this head with no findings, the author posted corpus --both and the VM corpus, and the test merge with current main is clean.

@284km
284km merged commit 2afb41f into main Nov 26, 2026
11 of 19 checks passed
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