Skip to content

YAML's loads take apart the tree they built, once its value is made - #374

Merged
284km merged 3 commits into
mainfrom
rails-ar-psych-load-tree
Nov 27, 2026
Merged

284km merged 3 commits into
mainfrom
rails-ar-psych-load-tree

Conversation

@284km

@284km 284km commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Why

After #370, a YAML.load dropped and collected still kept its whole node tree. At 16,384 rows that was 98.7k objects with instance variables and 16.5k appended children Arrays.

MERE_RUBY_GC_DBG=4 (leave out the conservative scan of the C stack) lets the tree go: a handle the parse left on the stack keeps the root alive. Ruby keeps the last tree for the same kind of reason, but a node there is about 80 bytes; here it is a kilobyte or more. In eager_test's fixture load (65,536 rows), 526k such objects were left after the load and a GC.

What

tools/gen_psych_lib.rb inserts one call into vendor psych's safe_load and unsafe_load; load and the *_file loads go through them. The value is kept in a local, the tree is taken apart, and the local is returned:

  • __value = result.to_ruby(...), __drop_tree(result), __value
  • __value = visitor.accept result, __drop_tree(result), result = __value

Nothing is sent to the loaded value. The first push used .tap { __drop_tree(result) }, which dispatched tap to whatever the document made: an object revived through init_with with its own tap changed the load's answer, and a raising tap failed the load (review). Corpus 1073 now covers both.

Each line must be found exactly once, or the generator aborts, so a psych that moves them fails loudly. The reason is written beside the substitution.

Psych.__drop_tree (private, in lib/psych_native_protocols.rb) clears the children along the spine: the stream's, the document's, and on down while a node has one child, to the mapping or sequence that holds the rows. A stale handle is on the root or near it, so afterwards it keeps one row at most.

The tree never leaves the load. A tree returned by Psych.parse or parse_stream belongs to the caller and is left alone.

The first version walked the whole tree and cost more than it saved: iterating an Array built by appends folds it into a list, so the walk copied every children Array once more. The fixture load's footprint reached 2.3 GB, against 1.5–1.9 GB for the spine.

Checked (Mere 9dec2ff6, main 391b560)

YAML.load, 16,384 rows, kept to the end main this
after GC 196 MB 146 MB
objects with instance variables 98.7k 449
appended Arrays 16.5k 81
peak footprint 522 MB 525 MB

In eager_test's fixture load, objects left after the load and a GC went from 526k to 133k.

  • Corpus 1073 (matches ruby on the evaluator and the VM, index on and off): load, unsafe_load, safe_load with aliases, load_stream, init_with, the *_file loads, and the trees from Psych.parse and parse_stream still whole after a load.
  • Full corpus: 1013/1013 on the evaluator and the VM, index on and off, MERE_RUBY_SHAPES_CHECK=1.
  • test/psych: MATCH 635 on the VM; 634 on the evaluator. The one RED is test_yaml.rb#test_y_method, an existing regression on main from Apply named visibility changes to class-method receivers #346: require "ostruct" fails with "undefined method 'block_given!'", on main itself as well.

🤖 Generated with Claude Code

The collector scans the C stack conservatively, and a handle the parse left
there -- a node's -- kept the whole node tree alive after a load had
returned (MERE_RUBY_GC_DBG=4, leaving that scan out, let it go).
activerecord's citations fixture, 65,536 rows, kept 393k nodes and their
children Arrays. ruby keeps the last tree as well, but a node there is about
80 bytes; here it is a kilobyte and more.

tools/gen_psych_lib.rb now puts one call into vendor psych's safe_load and
unsafe_load (load and the *_file loads go through them):
`.tap { __drop_tree(result) }` after the value is made. Psych.__drop_tree
(lib/psych_native_protocols.rb, private) clears the spine's children: the
stream's, the document's, and down while a node has one child -- to the
mapping or sequence that holds the rows. A stale handle is the root's or
near it, and then keeps one row at most. (Walking the whole tree cost more
than it saved: iterating an Array built by appends folds it into a list.) The tree never leaves the load; a tree
Psych.parse or parse_stream returns is the caller's and is left alone. Each
line has to be found exactly once, so a psych that moved them fails the
generator rather than silently losing this.

YAML.load of 16,384 rows (main 391b560 -> this), kept to the end: after GC
196 -> 146 MB, objects with instance variables 98.7k -> 449, appended Arrays
16.5k -> 81; the peak is the same (522 / 525 MB). In eager_test's fixture
load (65,536 rows, with #351-#370), the objects left after the load and a GC
are 526k -> 133k.

corpus 1073: load, unsafe_load, safe_load with aliases, load_stream,
init_with, the *_file loads, and the trees Psych.parse and parse_stream
return, whole after a load.

@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 a8a03b2c9a3175a3ba83c8d75dc5c1e8948d4ed3 against current main b9ca06d6700c44ded301131930a5dbd9107202be.

The generator checks both substitution sites exactly once, and the added corpus usefully checks aliases, init_with, file loads and preservation of caller-owned parse trees. The generated embedded library independently regenerates byte-for-byte.

One Major: using .tap on the deserialized value invokes user-defined code and can change what all three load APIs return. Please keep the loaded value in a local, perform cleanup separately, and return that local. Details and a reproduced example are inline.

Independent Darwin arm64 validation: fresh ordinary O2 head build with pinned compiler 9dec2ff6 and mgz 661a01d8; 16 current-main/head executions across the added corpus and an overridden-tap regression probe, using evaluator/strict VM, hash index ON/OFF and tight GC against Ruby 4.0.10. Corpus 1073 matches in all four configurations on both trees; the tap probe matches on main and regresses on head in all four configurations. Main binary reused after verifying all 397 tracked runtime/build source inputs byte-identical to current main; no base rebuild claimed. GC roots and emitted-C bracket depth pass (155/1024). No independent full corpus, complete Psych suite, memory/resource measurement or Linux acceptance claimed.

No merge: the recorded all-merge hold and new-failure review remain active. Main run 45913249285 has an executed network contract failure (net/http/test_http.rb, reference exit 0 versus main exit 1), while latest main run 45916943242 is pending with no jobs. Hosted checks are incomplete and have not been counted as passes. COMMENT because the authenticated account owns the PR.

Comment thread tools/gen_psych_lib.rb Outdated
# tree is the caller's, are left alone. Each line has to be found
# exactly once -- a new psych that moved them fails here, not silently.
{ " result.to_ruby(symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer, parse_symbols: parse_symbols)\n" =>
" result.to_ruby(symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer, parse_symbols: parse_symbols).tap { __drop_tree(result) }\n",

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.

[Major] Run cleanup without calling tap on the loaded object. Both replacements dispatch tap on an arbitrary deserialized Ruby value. A supported custom class can override that method: define TapValue#init_with(coder) and def tap; :intercepted; end, then load "--- !ruby/object:TapValue\nvalue: 7\n". Current main and Ruby 4.0.10 return a TapValue from unsafe_load, safe_load(..., permitted_classes: [TapValue]) and load(..., permitted_classes: [TapValue]); this head returns :intercepted from all three on both engines. An override that raises will also turn a successful load into an exception. Store to_ruby/visitor.accept in a separate local, call __drop_tree on the original node, and return the saved value; add an object with an overridden tap to the regression corpus.

The drop of the load's tree was spliced in as .tap { __drop_tree(result) },
which sends tap to whatever the document made. An object revived through
init_with that defines its own tap changed what the load answered, and one
whose tap raised failed the load. The value now goes through a local, the
tree is taken apart, and the local is answered. Corpus 1073 gains both
cases.

@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.

Re-review at d2fee8db. The Major is fixed: the loaded value now goes through a local (__value), __drop_tree is called on the tree, and the local is returned, so nothing is sent to the deserialized object. Corpus 1073 adds a TapValue whose tap returns :intercepted and a TapRaises whose tap raises, loaded through unsafe_load, load(permitted_classes:) and safe_load, and they match in three modes. The generator still requires each insertion point exactly once, and Psych.parse / parse_stream trees are untouched. I will merge once the review bot has reviewed this head.

@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.

Re-reviewed d2fee8dbd7e85a3adf5707110582f1dfbd637903; compared the source with current main 9547d96b046c822598d0be35e1c47b3a2c41f9ca and read the existing discussion.

The previous Major is fixed: both generated load paths save the deserialized value in __value, clean up the original node separately, and return the saved value. The new TapValue/TapRaises cases exercise the problematic user overrides. I found no new actionable issue in this follow-up. The generator still checks both insertion points exactly once, and caller-owned parse trees remain untouched.

Independent Darwin arm64 validation: fresh ordinary O2 build of this exact PR head, pinned compiler 9dec2ff6, and mgz 661a01d8 (reused dependency sources verified against the pinned archive). Corpus 1073 and the prior overridden-tap reproduction both match Ruby 4.0.10 in all four evaluator/strict-VM and hash-index ON/OFF configurations, with tight GC and shape checks: 8/8 executions, exit 0 and empty stderr. The embedded library regenerates byte-for-byte; GC roots and C nesting checks pass (155/1024). Generated Ruby source also matches the reference corpus, and the prior reproduction matches with both current-main and head-generated libraries. These are focused checks, not a fresh full corpus, complete Psych suite, memory measurement, Linux acceptance, or a tested prospective merge.

No merge: the recorded hold_all_merges and new_failure_review_required remain active. Hosted checks still include queued and in-progress jobs; they are not counted as passes or covered by the queue exception. Latest main CI run 45938377621 is pending. COMMENT because the authenticated account owns the PR.

@284km
284km merged commit 795dc3e into main Nov 27, 2026
14 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