Repository navigation
feat(ffi)!: failed run-time checks raise the language's error - #730
Conversation
Quest-Claim: ed1ecb7545259280
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # quest/m1/ffi-export/checks-raise.md
The empty async closure ran on another thread and could return before Rust's first poll, as a ready Rust future does, so the test failed about 4 runs in 10. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…thon Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… a hard-linked baseline Leave quest/m0/swift-gives-up.md as main has it: #730 finishes it. Test the lock's library-name guard and the hard-linked baseline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… an argument throw Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t of them needs no ? The moq export's record traits lifted a list of Version, a Copy object no export misuses, with a ? inside the item closure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rom the Rust-like close The Swift within(0) check also waits for the error's resumption, the second race swift-gives-up names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rs each binding A record or data enum holding a checked handle takes a status in _eq, _to_string, and _debug, which C++'s operators left out. Seat, holding a Ticket, runs both through every binding against Rust's transcript. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g calls Its C program missed the status each checked call now takes, and Swift's calls on checked handles now throw. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The status each call allocated from its arena cost a checked call about 4 ns in the bench's handle call and u64 getter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ee decision Measured on desktop against main: the getter and handle call gain in Kotlin and Go, while Go's object return and Go's and Kotlin's stamped write lose to the GC freeing each closed handle. object-ownership now requires checks-raise. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…a move free it at once Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… status allocation is a follow-up Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
ℹ️ No correctness issues found. The merges fit this branch's check ordering. One minor test gap is noted inline.
Reviewed changes
Since the review at b5b99ca2, the branch merged main three times (c033d8eb, 6cb60db6, c5104a4c, up to 2cf80c93). The merges matter mostly because of #808, which crosses a Copy type changed in place by value. I checked how each binding's write-back of a value's &mut self combines with this branch's status.
- Moved checked-Copy fixtures to a new
Mark: #808 turnedScoreinto an opaque value, so it is no longer checked.Mark(Copy, with anOption<u32>slot and&mut selfadd) now stands in for it inSeat,Choice,Parcel,heft,admit, andBooth, and in every binding's test. - Gave
abi::Handeda status:leadno longer counts the trailing status.Handed::callsplits the status off and passes it last to the real C function. The Dart serve glue routes a handed call through the stack-locals_, and Kotlin and Python append the status beforeHanded::callsplits it. - Wrote a value's
&mut selfback only on success: the glue'sthis.write(..)runs after the call insidewrap, so a refused call writes nothing back. Swift'sdefer { self = .. }and Go's*self = ..reassign an unchanged copy when the call is refused. - Adopted #807's Kotlin runtime names:
_Native.Refusedis now_Native.__Refused, andmovingand the fixture expectations (Native$__Refused) follow it. - Passed a status to main's new checked calls: the C, Swift, and Kotlin tests for main's new exports (
spareGet/spareSet,Codecs,failure,weigh_all,resolved) now pass a NULL status or usetry!.
I built and ran nothing.
claude-opus-5-5 | 𝕏
|
quest land watch: ended this pull request's pick, disarming its auto-merge, since its head c5104a4 is held by finding by pullfrog[bot]: (written by quest land watch) |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
✅ No new issues found. The only new commit adds the tests the earlier test-gap thread asked for.
Reviewed changes
Since the review at c5104a4c, the branch added one commit, 9fed5970, which answers the open Score::note test-gap thread.
- C covers a refused
&mut selfvalue method:api.ccallsapi_Score_notewith the dropped mark and expectsAPI_STATUS_MOVED, withapi_Score_countstill 2. - Go covers the same case:
api.gocallsNotewith a closed mark and expects an error, withCount()still 7. - Other bindings: the author explains why Swift can't reach a refused
note, and why Kotlin, Python, and Dart return a changed copy and never mutate the receiver. That matches how the glue writes back after the call.
I built and ran nothing. The author reports just ci passing on this head.
claude-sonnet-5-5 | 𝕏
# Conflicts: # ffi/moq/moq.c # ffi/tests/api.c # ffi/tests/api.swift
There was a problem hiding this comment.
✅ No new issues found. The only new commit merges main, and it resolves its three conflicts the same way earlier merges did.
Reviewed changes
Since the review at 9fed5970, the branch merged main once (78882d5a). The merge brings in #811, which crosses padded Copy types as handles, and #810's nightly moq exports. I read the conflict resolution with git show --remerge-diff and checked how #811's new copy objects fit this branch's abi::checked.
- Resolved three test conflicts:
moq.ckeeps main's pointer-returningmoq_tokio_Backoff_initial_get(..) == NULLand passes theNULLstatus.api.candapi.swiftkeep main'sMoment-based drive closure along with this branch'sapi_Waiter_waker(waiter, NULL)andtry! waiter.waker()(). - Left the new handle types unchecked:
InstantandGapare nowcopyobjects.abi::checkedignorescopyobjects passed by value, and nothing borrows them&mutor lends them, so main's calls such asapi_now,api_later,api_Gap_new, andapi_has_instanttake no status and the merged tests needed no change.
I ran the api_c, api_cpp, and api_go fixture tests on this head, and they all pass.
claude-opus-5-5 | 𝕏
|
quest land watch: the merge queue removed this pull request at 78882d5 because its The land fixer works on it in the background, and the watcher re-enqueues it at the back of the queue once it is fixed or judged flaky, or hands it back here with what it needs.
…c::<usize>::fetch_update`: renamed to `try_update` for consistency
--> /var/cache/github-runner-home/mbx-targets/v1/b55138f0663f5d26fcf7506227e1e07c51974a2ce2a773e02b51e22779ee9b97/moq/rs/moq-net/src/session.rs:1077:5
|
1077 | .fetch_update(Ordering::AcqRel, Ordering::Acquire, |live| {
| ^^^^^^^^^^^^
|
help: replace the use of the deprecated method
|
1077 - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |live| {
1077 + .try_update(Ordering::AcqRel, Ordering::Acquire, |live| {
|
warning: use of deprecated method `std::sync::atomic::Atomic::<u64>::fetch_update`: renamed to `try_update` for consistency
--> /var/cache/github-runner-home/mbx-targets/v1/b55138f0663f5d26fcf7506227e1e07c51974a2ce2a773e02b51e22779ee9b97/moq/rs/moq-net/src/transport/boxed.rs:78:5
|
78 | .fetch_update(Ordering::AcqRel, Ordering::Acquire, |paused| {
| ^^^^^^^^^^^^
|
help: replace the use of the deprecated method
|
78 - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |paused| {
78 + .try_update(Ordering::AcqRel, Ordering::Acquire, |paused| {
|
warning: use of deprecated method `std::sync::atomic::Atomic::<usize>::fetch_update`: renamed to `try_update` for consistency
--> /var/cache/github-runner-home/mbx-targets/v1/b55138f0663f5d26fcf7506227e1e07c51974a2ce2a773e02b51e22779ee9b97/moq/rs/moq-mux/src/container/ts/import.rs:2075:9
|
2075 | used.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
| ^^^^^^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
help: replace the use of the deprecated method
|
2075 - used.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
2075 + used.try_update(Ordering::Relaxed, Ordering::Relaxed, |used| {
|
note: link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms
note: native-static-libs: -lgcc_s -lutil -lrt -lpthread -lm -ldl -lc
mbx[savings]: 944.5 GiB logical of target/ had outlived its checkouts. it has been dealt with.
ok
cargo test --locked
Compiling rust2-ffi v0.0.0 (/var/cache/github-runner-work/rust2/rust2/ffi)
Finished `test` profile [unoptimized] target(s) in 5.47s
Running unittests src/main.rs (target/debug/build/rust2-ffi/6d5da8e5c23dfc65/out/rust2_ffi-6d5da8e5c23dfc65)
running 21 tests
test abi::tests::unique_keeps_names_their_own ... ok
test abi::tests::names_apart_from_order ... ok
test abi::tests::lengthens_only_where_instances_clash ... ok
test abi::tests::splits_only_names_that_join_alike ... ok
test cli::decode_tests::decodes_a_branch ... ok
test cli::tests::matches_partial_versions_as_cargo_does ... ok
test cli::tests::reads_what_picks_a_resolution ... ok
test cpp::tests::parameters_keep_apart_from_what_they_would_hide ... ok
test ir::tests::held_reads_an_earlier_baseline ... ok
test kotlin::tests::room_reserves_writeback ... ok
test merge::tests::names_a_cycle_across_targets ... ok
test merge::tests::refuses_a_facade_module_named_as_another_targets_reached_crate ... ok
test python::tests::member_keeps_clear_of_the_runtime_aliases ... ok
test merge::tests::names_a_variants_own_targets ... ok
test go::package_names_are_locked ... ok
test swift::tests::runtime_names_taken ... ok
test kotlin::tests::runtime_classes_prefixed ... ok
test lock::tests::go_error_owner_is_locked ... ok
test lock::tests::tuple_c_rename_is_reported_once ... ok
test glue::rewrite_keeps_unchanged_files ... ok
test glue::go_module_resolves_missing_parent ... ok
test result: ok. 21 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
Running tests/fixtures.rs (target/debug/build/rust2-ffi/2b6f39900ed6e05d/out/fixtures-2b6f39900ed6e05d)
running 56 tests
test api_android ... ignored, needs the Android SDK and NDK, cargo-ndk, and a device: just ffi android
test api_asan ... ignored, needs clang and the nightly's rust-src: just ffi sanitize
test api_miri ... ignored, needs the nightly's miri: just ffi sanitize
test api_tsan ... ignored, needs clang and the nightly's rust-src: just ffi sanitize
test locked ... ok
test feature_of_dependency ... ok
test configured_out ... ok
test argfile ... ok
test rust_version ... ok
test reject ... ok
test channel ... ok
test go_package_names ... ok
test shapes::ir_covered ... ok
test shapes::nightly::c ... ignored, the nightly's: every sampled shape, just ffi shapes
test shapes::nightly::cpp ... ignored, the nightly's: every sampled shape, just ffi shapes
test shapes::nightly::dart ... ignored, the nightly's: every sampled shape, just ffi shapes
test shapes::nightly::go ... ignored, the nightly's: every sampled shape, just ffi shapes
test shapes::nightly::kotlin ... ignored, the nightly's: every sampled shape, just ffi shapes
test shapes::nightly::python ... ignored, the nightly's: every sampled shape, just ffi shapes
test shapes::nightly::swift ... ignored, the nightly's: every sampled shape, just ffi shapes
test config_patched ... ok
test lookalike ... ok
test git_patched ... ok
test dev_feature ... ok
test step_reruns_on_change ... ok
test patched ... ok
test foreign_role_names ... ok
test relative_target ... ok
test reexport ... ok
test foreign_lib_name ... ok
test opaque_values ... ok
test profiled ... ok
test replaced ... ok
test symlinked ... ok
test plain ... ok
test go_module ... ok
test standard_names ... ok
test go_reserved_packages ... ok
test unreached_types ... ok
test target ... ok
test shapes::gate::python ... ok
test shapes::gate::dart ... FAILED
mbx[progress]: 15s elapsed; 5 hits, 2 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
test shapes::gate::c ... ok
test lock ... ok
test shapes::gate::swift ... ok
test api_dart ... FAILED
test api_py_types ... ok
test api_c ... ok
test api_python ... ok
test shapes::gate::cpp ... ok
test shapes::gate::kotlin ... ok
test shapes::gate::go ... ok
mbx[progress]: 30s elapsed; 5 hits, 4 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
test api_kotlin ... ok
mbx[progress]: 45s elapsed; 5 hits, 6 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
test api_swift ... ok
mbx[progress]: 1m elapsed; 5 hits, 6 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
test api_go ... ok
test api_cpp has been running for over 60 seconds
mbx[progress]: 1m 15s elapsed; 5 hits, 6 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
mbx[progress]: 1m 30s elapsed; 5 hits, 6 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
mbx[progress]: 1m 45s elapsed; 5 hits, 6 misses, 17 bypassed, 36 not looked up; ~155.5ms compiler work saved
test api_cpp ... ok
failures:
---- shapes::gate::dart stdout ----
thread 'shapes::gate::dart' (500552) panicked at tests/fixtures.rs:66:5:
"/nix/store/m3g2r3bs1cil4r1a9abnggs25plyhvvd-dart-3.13.0/bin/dartaotruntime" "/nix/store/m3g2r3bs1cil4r1a9abnggs25plyhvvd-dart-3.13.0/bin/snapshots/gen_kernel_aot.dart.snapshot" "--platform" "/nix/store/m3g2r3bs1cil4r1a9abnggs25plyhvvd-dart-3.13.0/lib/_internal/vm_platform_strong.dill" "--packages" "/var/cache/github-runner-work/rust2/rust2/ffi/target/tmp/shapes/drivers/dart/package_config.json" "--native-assets" "/var/cache/github-runner-work/rust2/rust2/ffi/target/tmp/shapes/drivers/dart/native_assets.yaml" "-o" "/var/cache/github-runner-work/rust2/rust2/ffi/target/tmp/shapes/drivers/dart/main.dill" "/var/cache/github-runner-work/rust2/rust2/ffi/target/tmp/shapes/drivers/dart/main.dart" failed:
target/tmp/shapes/out/dart/shapes.dart:427:31: Error: Can't declare a member that conflicts with an inherited one.
final ffi.Pointer<ffi.Void> _drop;
^^^^^
target/tmp/shapes/out/dart/shapes.dart:488:8: Context: This is the inherited member.
void _drop() {}
^^^^^
target/tmp/shapes/out/dart/shapes.dart:434:14: Error: Too few positional arguments: 3 required, 2 given.
super(raw.data, true) {
^
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- api_dart stdout ----
thread 'api_dart' (499786) panicked at tests/fixtures.rs:66:5:
"dart" "analyze" "--fatal-infos" "/var/cache/github-runner-work/rust2/rust2/ffi/target/tmp/api/out/dart" failed:
Analyzing dart...
error - api.dart:427:31 - Class 'Waker' can't define field '_drop' and have method '_Object._drop' with the same name. Try converting the getter to a method, or renaming the field to a name that doesn't conflict. - conflicting_field_and_method
error - api.dart:434:29 - 3 positional arguments expected by '_Object.new', but 2 found. Try adding the missing arguments. - not_enough_positional_arguments
2 issues found.
failures:
api_dart
shapes::gate::dart
test result: FAILED. 43 passed; 2 failed; 11 ignored; 0 measured; 0 filtered out; finished in 106.26s
error: test failed, to rerun pass `--test fixtures`
mbx[cache]: object cache: 5 hits, 6 misses, 36 not looked up, 17 bypassed; 0 B downloaded, 0 B uploaded, 27.3 MiB stored locally
mbx[cache]: 1m 52s session; 155.5ms estimated compiler time avoided (summed across compilations)
mbx[cache]: 36 compilations had no usable prior inputs or matching prediction for a lookup
mbx[cache]: bypass reasons: 13 unsupported-crate-type, 4 build-script-input-overlaps-outputs
mbx[cache]: Cargo artifact reuse and CI cache archive transfers are not included above
mbx[savings]: cleaned up 944.5 GiB logical after checkouts that left without saying goodbye.
error: recipe `test` failed on line 38 with exit code 101
error: recipe `ci` failed on line 28 with exit code 101
##[error]Process completed with exit code 101.
Post job cleanup.
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git version
git version 2.56.0
Temporarily overriding HOME='/var/cache/github-runner-work/_temp/8750479d-3a04-4093-a8dd-b7465e85d87a' before making global git config changes
Adding repository directory to the temporary git global config as a safe directory
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git config --global --add safe.directory /var/cache/github-runner-work/rust2/rust2
Removing SSH command configuration
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git config --local --name-only --get-regexp core\.sshCommand
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git submodule foreach --recursive sh -c "git config --local --name-only --get-regexp 'core\.sshCommand' && git config --local --unset-all 'core.sshCommand' || :"
Removing HTTP extra header
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git config --local --name-only --get-regexp http\.https\:\/\/github\.com\/\.extraheader
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git submodule foreach --recursive sh -c "git config --local --name-only --get-regexp 'http\.https\:\/\/github\.com\/\.extraheader' && git config --local --unset-all 'http.https://github.com/.extraheader' || :"
Removing includeIf entries pointing to credentials config files
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git config --local --name-only --get-regexp ^includeIf\.gitdir:
[command]/nix/store/i2m3w4ly2w6grrmk1j59rb7zp09bssia-git-2.56.0/bin/git submodule foreach --recursive git config --local --show-origin --name-only --get-regexp remote.origin.url
A job completed hook has been configured by the self-hosted runner administrator
##[group]Run '/nix/store/3wq9f25mz2ksqrx6zs5nq522386djzw1-ci-cache-gc.sh/bin/ci-cache-gc.sh'
shell: /nix/store/lfm00fnq66xfgbn099vqckabyl5jllz6-bash-interactive-5.3p20/bin/bash --noprofile --norc -e -o pipefail {0}
##[endgroup]
evicted 0 objects and 0 action results (120.8 KiB logical); 49.9 GiB logical remain
dropped 3 stale checkout records
dropped 2 session event streams
Cleaning up orphan processes
(written by quest land watch) |
|
codex, gpt-6.1-sol, medium effort land fixer note:
(written by codex, gpt-6.1-sol, medium effort) |
|
quest land watch: armed auto-merge on this pull request at 41d9a71, so it joins the back of the merge queue once its required checks pass, with the land fixer's fix ( (written by quest land watch) |
There was a problem hiding this comment.
✅ No new issues found. The merge of main applies cleanly, and the follow-up commit fits #818's Dart
Wakerto this branch's_Object.
Reviewed changes
Since the review at 78882d5a, the branch merged main once (880c2de3, through ac5aee0d) and added one fix (41d9a719). Apart from rt.dart, the merge's diff over 78882d5a matches main's diff over its previous base exactly, so #817 and #822 arrive unchanged.
- Fitted the returned
Wakerto the branch's_Object: the fix renames #818's_dropfield to_dropFn, because a field of that name would collide with this branch's_Object._drop()method. It also callssuper(raw.data, true, false). Since a waker is not a handle Rust checks,_countedstays true and Dart keeps the hold count itself:call()holds and releases, andclose()throws while a call holds the waker. That matches what #818 intended. - Kept refused calls away from the new lift: the Dart glue runs
_status(s_.value, ..)beforeWaker._(r_), so a refusedWaiter.waker()never wraps a zeroed_Wakeror attaches a finalizer to a NULLdrop.
I didn't run the Dart tests because this runner has no Dart SDK.
claude-opus-5-5 | 𝕏

Finishes quest/m1/ffi-export/checks-raise.md, deleted here.
Problem
A run-time check a rust2-ffi binding fails aborted the process from safe Kotlin, Python, Go, Dart, and Swift. These checks are a borrow Rust would refuse, a call on a moved-out handle, a lent handle used past its lend, and an item off the library's target. Kotlin, Go, Python, and Dart also kept a hold count of their own beside the runtime's, so every handle argument paid four atomic operations, and close freed the handle only once running calls finished rather than dropping the value as Rust would.
Approach
One accounting, in Rust.
rt::Object's checks returnResult<_, Status>instead of aborting. A C function whose handles can fail a check takes a trailing<prefix>_status *statusand writes the status there, returning a zeroed value. A NULL status aborts with the message, naming the function; C++ passes NULL, so C and C++ still abort. The header adds<prefix>_status,<PREFIX>_STATUS_{MOVED,EXCLUSIVE,BORROWED,THREAD,LENT,OUTLIVED}, and<prefix>_status_message.A failed call changes nothing. The glue runs checks before any Rust code runs, in a fixed order:
Takes, CAS 0→TAKEN) and roll back on drop unless committed. A checkedCopyobject in a moved argument, alone or held in a record or data enum, is borrowed into the sameTakes(Object::hold), copied out after the commit (Object::held,lift_<T>_taken), and released before the call runs, so no check fails once a move committed.deref_mutwas used, at drop.Checked types are chosen at export time (
abi::checked). A type is checked if it is notSync; or an export borrows it&mut, moves it (also inside anOption,Box, list, tuple, record, or data enum passed by value), or lends it to a closure or trait; or a call returns a borrow of it; or a trait method returns it. Every other type is only ever borrowed shared, soObject::peekborrows it with no atomic operation, and its calls take no status.Close is Rust-like. A checked type gets
<T>_drop(self, status):rt::Object::closeCASes the state 0→TAKEN and drops the value, leaving the handle to_free. A later call failsmoved, a second drop does nothing, and a drop while a call or future borrows the value failsborrowed, as Rust refuses that drop. Kotlin's, Go's, and Dart'sclosecall it. Dart's and Python's hold counts go for checked owned handles, so a call borrows through the runtime's two atomics alone, and the handle is freed once the GC collects the object; Python never hadclose(), and a move leaves the handle to Rust'sTAKEN, which refuses the next call. Go and Kotlin keep counting each handle's calls, so aClosethat dropped the value, or a call that moved it out once it passed its checks, gives up the owner's hold and frees the handle once no call holds it, stopping Go's cleanup and Kotlin's phantom reference, as on main.Each binding raises its own error:
IllegalStateException.ValueErrorfor moved or outlived (as for a closed object) andRuntimeErrorotherwise.StateError.CheckError { function, message }. A field read stays a property withget throws, except one of a noncopyable value, which Swift cannot let throw: that becomes a method.checkError_matchingrt.ErrClosed(moved or outlived), the newrt.ErrBorrowed(any other check), orerrors.ErrUnsupported(off target).Every caller raises. Swift's
description,debugDescription,==, andclone()of a checked type, or of a record or enum holding one, throw, so that type conforms to none ofCustomStringConvertible,CustomDebugStringConvertible, andEquatable. A closed Swift class nested in an argument throws instead of trapping (Arena.held). Go'sString()andGoString()return the failed check's text. A record's or data enum's_eq,_to_string, and_debugtake a status when it holds a checked handle, and each binding raises from it. What a closure or trait implementation returns still aborts on a failed check: Rust, its caller, has no error to take.Swift changes no argument on a refused call: a checked call's
&mutwrite-back and its closing of moved classes run only once its status passed (c_ran_).A record's or enum's method takes a status when its receiver holds a checked handle, and C claims each
<PREFIX>_STATUS_*name, so an exported enum namedStatusis renamed instead of clashing.The target check (kixel-ai/rust2#700) now throws in Swift and returns an error in Go instead of trapping or panicking.
A ready call's
_start(main's feat(ffi)!: a ready async call in one crossing #741) takes the status last, after its future pointer, and each binding reads it before the poll's result: Go and Swift before theswitch, Dart before itsswitch. Swift's eager call and its already-cancelled path make the future through the checked call, so a refused call throws its check, notCancellationError.A pending move is its own state.
Object::reservetakes a free value toRESERVED, whichTakes::committurns intoTAKENand a droppedTakesrolls back to 0, soTAKENonly ever means gone: a_dropracing a reservation failsborrowedinstead of reporting a drop the rollback undoes.Dart's status survives reentrancy.
Home::serveruns queued relay calls on the isolate thread, and each can start a checked call, so the serve glue gives the call a status of its own and copies it into the isolate's one cell only onceservereturned; a NULL status passes through.Swift lowers fallible arguments before gifts. When a call hands Rust a kept closure, callback, waker, or future, which only the C call takes, each argument whose lowering throws (a moved class in a list) is lowered into a
letfirst, so a throw leaks nothing.Target-limited trait members raise too. Swift's
default()and each trait body taking a status throwCheckErroroff target; only a non-throwingdescription,debugDescription, or==traps, as their protocols forbidthrows. Go's<T>DefaultandEqualof a target-limited type return anerror, andString()/GoString()return its text, instead of panicking.The API lock reports a type becoming checked, or no longer, since that gives or takes a status from each call taking it and makes it throw in Swift.
moq's bench programs and the Miri tests pass the status:
moq.cpasses NULL,moq.swiftaddstry, and the Miri calls pass a null status.The flaky Swift
within(0)check this branch had fixed was fixed on main the same way; the merge takes main's.Merging main's owned buffers and Kotlin returns (kixel-ai/rust2#744, kixel-ai/rust2#750, kixel-ai/rust2#733):
Errthrown from inside Kotlin's native call, so it closes moved arguments in atry/finally. A failed check now throws_Native.Refused, anIllegalStateExceptionthe generatedcatchtells apart, so a refused call still closes nothing. Each of perf(ffi): return Kotlin values without byte-array transport #750's new return paths checks the status before it builds the value.takeflows through the checked and reserved lifts. Python takes feat(ffi)!: Rust takes owned buffers, and bindings pass Rust's bytes back uncopied #744'stwithout themthis branch dropped, and Dart marks its buffers taken (a_.took()) before a refused call's check throws, since the glue took them first. Go keeps closing moved handles only once the status passed, rather than in feat(ffi)!: Rust takes owned buffers, and bindings pass Rust's bytes back uncopied #744'sdefer.A refused call frees what it was given. A call a check refuses frees every buffer the caller handed Rust, as one that ran does:
&T, holding a checked handle beside bytes or text. So every check runs before any buffer is taken.rt::Unliftedguard, made before any argument is lifted, frees the reserved arguments' buffers (release_<T>, leaving their handles to the caller) unless the call commits. Lifts that can fail no check, an unchecked handle's included, run first, so what they took drops on a refusal.a_.ran(...)), after which Rust frees or takes it. A top-level buffer'sNative.takeopens inside every open that throws, after the throwing lowerings are hoisted, so nothing throws between its take and the call.Merging main's Copy values,
_Native, and CodSpeed (kixel-ai/rust2#742, kixel-ai/rust2#777, kixel-ai/rust2#805):Ticket,Stamp,Instant, and moq'sTimestampare values now, taking no status. The fixture's checked-Copycases (Seat,Booth,admit,Choice) holdScore, theCopytype main keeps as a handle, whichScore::add(&mut self)makes checked, soObject::holdkeeps its coverage.<T>_copyis gone, as on main.holdruns main's reclassed-object check before the branch's owned-handle fast path._Native, so the refusal is_Native.Refused. It andcheck'sUnsupportedOperationExceptionare qualified withkotlin., so an exported type of either name can't shadow them (CodeRabbit).io.Closers.Decisions
✅ Fix the buffer leak on refused calls in this PR (rejected: land with the follow-up refused-bufs). The refused-bufs quest is implemented here and deleted. Settled by the maintainer 2026-11-14 (comment).
✅ Keep the kotlin-compile-heap follow-up (rejected: drop), recorded in its Plan. Settled by the maintainer 2026-11-14 (comment).
✅ Close in Kotlin, Go, Python, and Dart is Rust-like (rejected: close waits for running calls). Close takes the value through the runtime's
TAKEN, the bindings' own hold counts go, and a checked call costs two atomics instead of four. Later calls raisemoved, and when a close races a running call, whichever loses raises the language's error. Settled by the maintainer 2026-11-12.✅ Go and Kotlin each keep a count, for checked types only (unchecked ones already counted), so a close or a move frees the handle once no call holds it; close stays Rust-like (rejected: land with the handle freed only by the GC, and look for a cheaper deferred free under object-ownership). It gives back the getter's few ns to win back 300 to 500 ns per object returned or stamped, which moq pays per frame. Settled by the maintainer 2026-11-13.
✅ Keep the error types (rejected: one dedicated type per language): Kotlin
IllegalStateException, PythonValueError/RuntimeError, DartStateError, SwiftCheckError, Gort.ErrClosed/rt.ErrBorrowed. Settled by the maintainer 2026-11-12.Choices made while the maintainer was away, each undoable in review:
peek), so its handle keeps the binding's count, and itsclosefrees the handle, throwinga handle is already borrowedwhile a call holds it instead of waiting. Checking every type instead would cost C, C++, and Swift their atomic-free borrow.String()/GoString()return the error text, as they already did for a closed object.default()of a target-limited type throws, rather than documenting a trap, as a constructor off target does.<T>DefaultandEqualof a target-limited type gain anerror, the target check's, rather than panicking.Copyobject lifts throughpeek, uncounted, as it is borrowed; the moq export failed to compile with a?inside a list's item closure without it.<Type> is closed, the binding's own refusal, as on main and in Dart, rather than Rust'smovedtext. Both matchrt.ErrClosedin Go and areIllegalStateExceptionin Kotlin. A call that held the handle before a racing close still meets Rust'smoved.Option,Box, list, or tuple frees it at once. No export takes such a record today.Impact
Public API, breaking (hence the
!):<prefix>_status *status; pass NULL to keep aborting. A checked type gains<T>_drop. A record's or enum's_eq,_to_string, and_debugtake a status when it holds a checked handle.throws. A field getter of a checked object with a copyable value becomesget throws; one returning a noncopyable value becomes a method (registry.firstGet→try registry.firstGet()).description,debugDescription,clone(), and==of a checked type throw, and it losesEquatable,CustomStringConvertible, andCustomDebugStringConvertible.default()of a target-limited type throws.error.Close()returns anerror(anio.Closer). A target-limited call returns an error matchingerrors.ErrUnsupportedinstead of panicking, as do<T>DefaultandEqualof a target-limited type, which gain anerror.close()drops the value and throws while a call borrows it, instead of waiting; a failed check raises instead of aborting. Kotlin's is_Native.Refused, anIllegalStateException.New runtime error types: Swift
CheckError, Gort.ErrBorrowed.Performance, from bench/ffi/README.md, median wall ns main → this branch. C, Python, Swift, and Dart, on desktop at a load average of 2.4 to 4.1 (unchanged since):
Kotlin and Go with their counts back, on nixos at a load average of 28 to 47, 10 interleaved runs each (the quieter hosts were busy too):
Without the counts, Go's object return had measured 183 → 691 and Kotlin's stamped write 310 → 613 on desktop. Go still costs more than main: each checked call heap-allocates its status, as cgo moves a local whose address it passes C to the heap (6 ns in a bare cgo call), and its
Closecrosses into Rust's_drop. The allocation is the follow-up below.Alternatives
Follow-ups
moq.ktneeds 512 to 640 MB of kotlinc heap, past its 512 MB default; main's moq recipes now pass-Xmx2gtoo (feat(bench): the binding benchmark on CodSpeed's CPU simulation #805). ✅ Keep (rejected: drop), recorded in its Plan. Recommended: one Kotlin file per type, after measuring Gradle's default heap.Validation
just cipasses, with all fixture tests in C, C++ (11/14/17/20/23), Kotlin, Python, Swift, Go, and Dart. Android was not run: it needs a device.Races between close and a running call, in Kotlin, Go, and Dart: a close during a call throws
borrowedand leaves the value; after the call, close passes and a later call raisesmoved, or in Go and Kotlin<Type> is closedonce close gave up the owner's hold. Counted (unchecked) types throw<Type>: a handle is already borrowedfrom close under a call.C:
statuseschecks a clear during a recv writesBORROWEDand changes nothing, an outlived meter writesOUTLIVED, a lent counter moved out writesLENT, and now that_dropduring a recv writesBORROWED, then drops, a second drop does nothing, and a later clear writesMOVED.Swift: a class a move closed throws
CheckErrorfromdescriptionand from a call holding it nested in a list.New fixture record
Seat, holding a checkedCopyScore(aTicketbefore main made it a value), prints itsDebugand==through every binding against Rust's transcript. It caught C++ leaving out the record trait status.The moq export builds every bench program (C, C++, Kotlin, Python, Swift, Go, Dart); the C program and Swift program needed the new statuses and
try.Bench: built and run on desktop through
quest gateat a load average of 2.4 to 4.1, main at7b0958b3and this branch run alternately, 12 rounds of main and 6 of the branch with the Dart cell. Go and Kotlin with their counts back: main ate9cca797and this head built side by side on nixos, each program run 10 times alternating.Go and Kotlin with counts back: the generated Go closes a moved handle (
self.Handle_.Moved(), or each moved list item's) only afterif c_status_ != 0returns, and Kotlin's.also { x.handle.abandon() }runs only once the JNI call returned without throwing; the fixtures' moved and boxed-moved cases then raiseCounter is closedandNode is closed, and Go'sclosed()test covers each kind of call on a closed object.Review round 1's five findings, each with a fixture case every binding compiles:
admit((Counter, Ticket, Seat, Choice)), whereapi.cdrops the ticket in each position in turn and checks the call writesMOVEDand leaves the counter, then moves it once all are live;Seat::number, which writesMOVEDfor a dropped ticket;Choice { Empty, Picked(Ticket) };enum Status, exported asapi_Status_; andnudge_by(&mut Point, &Refusal), whereapi.swiftchecks a closed refusal writes nothing back andreasonsrefusing a closed refusal leaves a live one beside it open. With the Swift gate disabled, that test fails.Merging main (feat(ffi)!: a ready async call in one crossing #741's
_start, the shapes round trip, Kotlin's flat record return): the shapes drivers pass C's NULL status and Swift'strywhere the generated function throws, which caught Kotlin's flat record return skipping its status check (thelent movedcase returned null instead of throwing) and Go importingrtin a package with no checked call.just cipasses on the merge.go build -gcflags=-mover moq'snetpackage reportsmoved to heap: c_status_756 times; a two-function cgo program measured 29 to 31 ns plain against 36 to 38 with a status pointer.Review threads of head
0d798f90, ten from pullfrog and CodeRabbit plus one CodeRabbit posted later, each reproduced before fixing:close_while_reservedreserves a move, checks_dropfailsborrowedand leaves the value, then rolls back and reads it; underTAKENalone, the drop reported success.relay(log: Box<dyn Log>, refusals: Vec<Refusal>), called from Swift with a movedRefusaland a log counting its deinit, leaked the log before the hoist and drops it after.Page(Default,Debug,PartialEq) andBooth(holding a checkedTicket) check, in every binding but C and C++, that each trait member off target raises the language's error. Swift'stargets()catchesCheckErrorand asserts itsfunctionandmessage, replacing the death test.Home::servewith a queued relay call, not reproduced by a deterministic test. The Dart bench against this head's own library before the change: getter 26.6 → 27.2 ns, handle call 39.2 → 40.5 ns, at a load average of 3.8 to 11.Gauge, whichnextgives a&mut selfmethod, passed the API lock before the fix and now fails it.&mut selfmethod returning a borrow is refused by collection (lendable); a fixture withfn renew(&mut self) -> &Meterfailed to export.On the merge of main at
0d258940:just ci,just ffi sanitize(asan, tsan, Miri), andjust ffi moq, whose C, C++, Kotlin, Python, Swift, Go, and Dart programs each printok.just ffi shapespassed in all seven languages before that merge.Merging main at
bb049072anda7db2666(feat(ffi): export a type the root does not reach by its public path in its crate #721's unreached types, quest: expected FFI aborts leave no core dump #767's abort cores, perf(ffi): distinguish wake, task, and executor costs #755's bench programs, fix(ffi): the nightly passes again: moq.swift's throwing tasks, and Kotlin GC checks independent of R8's inlining #732's nightly fixes, chore(ffi): the exporter pins moq on its own #736's moq pin):api.c's newBoard::bestcalls pass a NULL status,unreached_typesmatches the reserved move this branch emits for main'stake, Swift's new lines gaintry!, and ffi-abort-cores drops its link to the deleted checks-raise quest. On the head:just ci,just ffi sanitize,just ffi moq(each programok, pyright clean, as fix(ffi): the nightly passes again: moq.swift's throwing tasks, and Kotlin GC checks independent of R8's inlining #732 fixed it), andjust ffi bench-build.Merging main at
c4341b99,e5b3fa4f, andeeabf32f: on the last head,just ci,just ffi moq(all seven programs printok), andjust ffi sanitize(ASan, TSan, Miri).api.ktpasses a lent counter toreturnMoved, a moving call with a direct return, insideRegistry.edit. Rust refuses it withLENT, and the counter must still read afterwards. With_Native.Refusedexcluded from thecatchtaken out, the test fails withCounter is closed, both with the first inline helper and with the finaltry/catchform.moq.kt. So did perf(ffi): return Kotlin values without byte-array transport #750's owntry/finallyform on this branch's file, while main's file compiles in 1.3 GB RSS at the default-Xmx512M. 640 MB is enough, so the moq recipes passJAVA_OPTS=-Xmx2g(follow-up above).CodeRabbit's
api.c:1920thread is fixed: the counter handleapi_Registry_newlost is now freed.Refused calls' buffers, on the merge of main at
639d8bf2:heft(scored: (Score, Bytes), lent: &Parcel, moved: (Counter, Bytes)):api.c'sstatusesrefuses it with a dropped score in the tuple, then in the lent record, then a dropped counter beside the move, each handed threeapi_token_bytes. Each case writesMOVED,api_dropped()rises by exactly 3, and the live counter still reads. A call with all live returns 14 and drops 3. With the guard disabled, each refused case frees 0 of its 3.excuse(note: Bytes, entry: (Bytes, Refusal)):api.swiftpasses twotokenBytesbeside aRefusala move closed; the call throwsCheckErrorand both buffers drop once Swift's own go. With the arena's free and the take ordering disabled, that check fails.heftis in the transcript, so every binding passes a checked handle beside bytes and matches native Rust'sheft 16.just ffi sanitize: ASan (leak checking on) and TSan pass over the C and C++ scripts; Miri did not run, as this host's nightly has nocargo miri.just cipasses on the merge (all fixture tests in C, C++, Kotlin, Python, Swift, Go, and Dart, plus the lock and shapes gate).just ffi moq-cpasses.just ffi bench-buildbuilds every language's bench program, andjust ffi codspeedruns Rust, C, C++, moq-C, and Python.Codex's round on
85261792found Kotlin's move cleanup boundein itscatchanditin.also, shadowing a moved parameter of either name. Fixed inb5b99ca2: a fresh exception name and.also { _ -> ... }. The api fixture's newspend(e: Counter, it: Counter)fails kotlinc with the old cleanup (unresolved reference 'handle') and passes now;just cipasses on the head.Merging main at
039280eb(feat(ffi)!: Copy types changed in place cross by value #808, feat(ffi): Kotlin runtime helpers take underscore-prefixed names #807, feat(ffi): a future whose foreign error borrows its arguments exports #801, perf(ffi): a Dart call's serve compiles no panic catch or vtable of its own #793) and6356b42d(feat(ffi): export what moq's excludes hide at main #802):Scorean opaque value, so the refusal fixtures (Seat,admit,Choice,heft,Booth) hold a new checkedCopyhandle,Mark, whose&mut selfaddmakes it checked.&mut selfcall, which Kotlin, Python, and Dart make, now passes a status last when the method takes a checked handle.Score::note(&Mark)is in the transcript, so every binding calls it and matches native Rust'snoted 2 7.__names now cover this branch's runtime helpers too, as_Native.__Refusedand__Close.&[u8]lift takes the reserve slot the other lifts do, and its new tests pass a status in C andtry!in Swift where they reach checked handles.c5104a4c:just ci,just ffi moq(all seven programs printok; Swift's moq program drops thetrys that feat(ffi)!: Copy types changed in place cross by value #808's values made unneeded), andjust ffi bench-buildin the bench shell.Pullfrog's
Score::notethread onc5104a4c:api.cnow callsapi_Score_notewith the dropped mark, which writesMOVEDand leaves the score at 2, andapi.gocallsNotewith a closed mark, which errors and leaves the score at 7. Swift cannot reach a refusednote(Markhas no close, isCopyso no call moves it, and no callback lends one), and Kotlin, Python, and Dart return the changed copy, leaving the receiver unchanged by construction.just cipasses on the head.Merging main at
1c9b9d72(feat(ffi)!: cross padded Copy types as handles #811's paddedCopytypes as handles, feat(ffi): nightly exports moq for every target it ships #810):api.c's drive poll andapi.swift's drive closure take main'sMomentand keep this branch's NULL status andtry!onWaiter::waker;moq.c'sBackoffchecks take main's pointer option and keep the NULL status. On head78882d5a:just ciandjust ffi moq-cpass.Review: OpenCode Go is out of credit, so pullfrog's online review stands in for deepseek (decided by the maintainer 2026-11-13), and Codex ran with
--harness codex. Its round on the merge found the lock missing a type becoming checked, fixed in78a500c2; the session's saved state then needed--new, whose rounds found nothing. Codex's round 2 found nothing after the Kotlin fix, and rounds 3 and 4 found nothing on the merges.Models
Size: L
Implementer: Claude Code, claude-opus-5-5, unknown effort (iterate, L)
Implementer: Claude Code, claude-opus-5-5, unknown effort (iterate, M)
Implementer: Claude Code, claude-opus-5-5, unknown effort (iterate, M)
Implementer: Claude Code, claude-opus-5-5, unknown effort (iterate, M)
Implementer: Claude Code, claude-opus-5-5, unknown effort (iterate, XS)
(Written by Claude Opus 5.5)
🤖 Generated with Claude Code
Review
mechanical fix by codex, gpt-6.1-sol, medium effort:
Merged base; renamed the private Dart Waker drop pointer and supplied the unchecked constructor flag to preserve counted ownership; passed nix develop --command just ci base and git diff --check.(head 41d9a71)Rewritten by
quest reviewafter each round.Head: 78882d5
Base: origin/main at 563da9f
Risk: medium,
the base has no RISK.md to name what is always high or customer-facing, so every change is mediumClassified: medium by default
Reviewer: Codex, gpt-6.1-sol, xhigh effort
Session:
01a1db92-bfe5-7593-b94f-13ce00a57d5b, round 6Score: 10/10,
Code inspection found no new branch-specific defects in the merge adaptations for padded types and checked-call fixtures.Rounds: 6; first round 1 (medium 1); findings 1 (medium 1): fixed 1, refuted 0, open 0
Findings: none
Reviewer: Codex, gpt-6.1-sol, high effort, shadow
Session:
01a1dcac-b5fa-7262-aa08-faac5ad72b8fRounds: 2; first round 1 (high 1); findings 1 (high 1): fixed 0, refuted 1, open 0
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Bug Fixes