Skip to content

Stop to_json and Dynamic serialization at shared reference loops - #1222

Merged
schungx merged 1 commit into
rhaiscript:mainfrom
Rockyrok77:json-shared-loop
Nov 21, 2026
Merged

schungx merged 1 commit into
rhaiscript:mainfrom
Rockyrok77:json-shared-loop

Conversation

@Rockyrok77

Copy link
Copy Markdown
Contributor

A closure stored in the object map it captures makes a reference loop, and to_json follows it with no check:

let m = #{};
let f = || m;
m.f = f;

m.to_json();        // panics: called `Option::unwrap()` on a `None` value (src/api/json.rs)
#{a: m}.to_json();  // thread has overflowed its stack, process aborts

m holds f, and f carries m as a curried shared value. In the first call to_json holds the write borrow of m, so locked_read(v).unwrap() in format_dynamic_as_json hits None. The second takes only read borrows, so the formatter recurses until the stack runs out, and neither an engine limit nor catch_unwind can stop that. Under metadata, to_json goes through impl Serialize for Dynamic, which fails the same two ways (cell.borrow() panics with "RefCell already mutably borrowed", or the same unbounded recursion). That also covers hosts calling serde_json::to_string on a value returned by a script.

Both serializers now pass down the chain of shared values currently being formatted, the same idea as the visited set the Display/Debug impls of Dynamic already use for loops. A shared value that is already on the chain, or that cannot be read-locked, is written as null by the built-in formatter, and serde gets an error, which to_json already turns into "ERROR". The chain follows the current path rather than recording every value seen, so a shared value that appears several times without a loop (#{a: m, b: [m]}) still serializes in full. On the serde side &Dynamic is wrapped in a small private DynamicSer, because Serialize::serialize has no room for extra state; the public API is unchanged. Under sync the shared arm now uses locked_read like the rest of the engine instead of a blocking read().unwrap().

Added test_map_json_shared_loop to tests/maps.rs and test_serde_ser_shared_loop to tests/serde.rs. Without the fix the first panics and the second overflows the stack; with it both pass. cargo test --tests passes with default features and with the decimal, sync, unchecked, no_closure, no_index, no_object, no_function and compact_str rows of the CI matrix (each with serde,metadata,internals,debugging,grain), plus the combined sync,...,no_closure,...,unchecked row. cargo fmt --check and the CI clippy invocation are clean, and both the no_std sample and --no-default-features --features no_std,serde,sync build. CHANGELOG line under 1.27.1's bug fixes.

Found by building nested and self-referencing values in scripts and passing them to the standard-library functions.

@schungx

schungx commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Would arrays be subject to the same issue?

@schungx schungx added the bug label Nov 19, 2026
@Rockyrok77

Copy link
Copy Markdown
Contributor Author

Yes, an array closes the loop the same way. On main, let a = [()]; let f = || a; a[0] = f; #{x: a}.to_json() overflows the stack, both in format_dynamic_as_json and in the serde path under metadata. A map holding [f] where f captures the map hits the same unwrap in json.rs, or the RefCell panic in serialize.rs, as the plain map case.

There's no to_json for arrays in the stdlib, so arrays only get there as a value inside a map or through serde. The check in this PR sits on the Shared arm, not on Map, so it already covers them. I ran those array cases against this branch: the built-in formatter writes null where the loop closes, and serde returns the reference loop error (ERROR from to_json under metadata). Happy to add an array case to the tests too.

@schungx

schungx commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

There are some unused warnings and also merge conflicts. See if you can fix them, and I"ll merge!

@Rockyrok77

Copy link
Copy Markdown
Contributor Author

Rebased on main and fixed the CHANGELOG conflict. The entry now links #1222, same as the other lines there. The two codegen failures were the ui_tests stderr outputs, which your 0dc3795 already fixes, so they should go green after the rebase.

On the warnings, I couldn't find any from this change. cargo check on the lib is clean for default, serde/metadata, sync, no_closure, no_index, no_object, no_function and a few combinations of those. The test builds don't warn in maps.rs or the new test in serde.rs either. The unused warnings in the CI logs for this PR are in tests/closures.rs, tests/stack.rs, tests/var_scope.rs and tests/grain/limits.rs (plus the serde.rs imports on no_index/no_object), and main has all of them too. If you had a different warning in mind, tell me which feature set and I'll fix it.

@schungx
schungx merged commit e458dca into rhaiscript:main Nov 21, 2026
56 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants