Skip to content

Modeled C stage 9: callbacks and threads (ruling §44-§51) - #1606

Merged
ehartford merged 2 commits into
mainfrom
modeled-c-stage9
Sep 24, 2026
Merged

ehartford merged 2 commits into
mainfrom
modeled-c-stage9

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Stage 9 of docs/modeled-c-implementation-plan.md (ruling §44-§51; spec §16.2b.9-10), on top of stage 8 (main d783366). Two commits: Box.into_raw (std.box), then the stage.

What lands

A callback contract — an fn item that retains a callback or its userdata (retains … by param 0), consumes userdata with a destroy callback (consumes … destroyed_by), types a callback's userdata (callback param N userdata param M), or says callback_thread any — is rendered as a method of the resource its first parameter receives (compiler/FacadeRender.w facade_render_callback_methods), generic in the userdata type U:

  • the callback is extern "C" fn(&U, …): captureless (§12.4, D63 — C receives the code pointer alone); a bare fn or a captureless closure, checked against the callback type with U bound from the userdata argument whatever order C declares them (SemaCheck.w method-call path, SemaFacade.w facade_callback_expected_type);
  • callback scope (§44): the userdata is &U, borrowed for the call; an ephemeral view is accepted;
  • retained (§45): mut fn … (app: U); the resource owns the userdata — boxed, handed to C as the cell's pointer — and its Drop releases every retained cell after the destroyer ran (the retaining origin never outlives what it retains, §25); a retained callback is a code pointer, nothing is kept for it;
  • consumed with destroy callback (§24): fn … (owned: U); the value moves into C in a Box cell and the compiler supplies the destroy fn for U (a captureless closure over the type parameter) in the withheld destroyed_by parameter; With destroys it through no other path;
  • reentrancy (§47) is by construction: the callback holds no captures and reaches the userdata as a read view (&U), so a callback may read the resource through a view it was handed and can mutate nothing the exclusivity rules protect (behav_c_facade_callback_scope re-enters db_total through &Database in the userdata);
  • thread capabilities (§48-§50): a facade resource is Send/Sync exactly as its thread clause says (SemaCheck.w type_satisfies_thread_trait → facade_thread_caps_for): thread-bound by default, send (which requires drop_any_thread, stage 2's check) makes it Send, share makes it Sync, never inferred from the representation; a spawn_os capture of a thread-bound resource names the facade's clause and the one to state;
  • callback_thread any (§51): at each call the userdata type must be Send and Sync (facade_check_callback_arg).

§61 verification added: callback param N userdata param M (callable; void *; exactly one void * slot in the callback's signature; one userdata per item), consumes of a void * with no destroy contract (never half-model, §9/§24), consumes … destroyed_by on anything but userdata, a userdata both consumed and retained, retains … by naming a non-resource or a non-receiver parameter, retains of anything but a callback / userdata / C string, callback_thread any on an item with no callback, and callback consumes (refused: not modeled). Every positional diagnostic prints the resolved C parameter (§57). The generic method's call effects (§38, stage 7) are attached to its concrete signature at the call (facade_note_callback_method_sig). Resolve adds the facade's std.box edge when an item keeps or hands C a userdata.

Fixtures

Behavior: behav_c_facade_callback_scope, _retained_callback, _consumes_destroyed_by, _thread_send, _callback_thread_any (header test/behavior/c_facade_callbacks.h). Compile errors (exact text): err_c_facade_thread_bound_not_sent, _share_without_send_arc, _callback_thread_any_userdata_not_sync, _callback_capturing_closure, _retained_userdata_view (a callback-scope value cannot be retained past the call), _consumes_userdata_no_destroy, _userdata_consumed_and_retained, _callback_consumes_not_modeled, _callback_userdata_not_void, _callback_userdata_two_slots, _retains_by_non_resource. Debug-alloc: da_c_facade_consumed_destroyed_once, da_c_facade_retained_released_once (leak count=0; C destroys / the resource releases exactly once on every path). Flip: behav_c_facade_facts_verify and behav_c_facade_parses drop the clause combination that now contradicts itself (a userdata consumed and retained; callback consumes) and gain a db_watch item with the retained/paired form.

Verified with the stage1 built from this tree: check src/main.w ok; with build :dev green; every behav_c_facade_*, c_facade_* phase, err_c_facade_*/err_c_import_* and da_c_facade_* fixture green (the pre_d_build_runner ones need the release compiler, rc=127 on the base too; behav_c_facade_libc_system_headers / behav_c_import_overlay_memchr fail on the base identically — #1485). analyze audit:all on the new fixtures reports only #1300 (any std.box program). Battery not run.

Derived decisions (the ruling is silent; each at worst removes capability)

  1. callback param N userdata param M (ruling §45 pairs nothing; §24 pairs a destroy callback with its userdata by position). Typing a void * as the caller's U is capability-granting — a wrong pairing aliases a foreign object as a With value — so it is stated, never inferred from there being one callback and one void *. The userdata arrives in the callback's one void * parameter; a callback with several is refused. A destroyed_by callback needs no clause: its first parameter is the userdata (§24, verified since stage 2).
  2. Callbacks are captureless. A facade callback parameter is an extern "C" fn and only a captureless fn or closure coerces (§12.4/D63); state goes in U. Closures through the userdata slot (a per-signature extern "C" trampoline in codegen) are not built: D62's owned move environment is not implemented yet (A move closure sent to spawn_os keeps its environment in the caller's frame: a captured Drop value is destroyed on the creator thread after join, and one consumed inside the closure is dropped twice (D62, §12.4) #1605, A closure returned from a function reads its environment from the dead callee frame: fn mk(x: i32) -> fn() -> i32: () => x * 10 gives garbage once mk is not inlined (§12.2 escaping closures) #1567, A closure returning a captured non-Copy local by value double-frees it (§2.3) #1481), so a retained move || would be dropped from the caller's frame. The existing diagnostic stands ("capturing closure cannot coerce to extern "C" fn pointer"); the move || fix-it named in the brief would mislead until the environment is owned.
  3. consumes … destroyed_by transfers unconditionally. §24: "if registration can fail without taking ownership, the contract must state when transfer occurs; absent that evidence, With preserves caller ownership" — no clause spells conditional transfer, so the clause means C owns the value from the call on, whether or not the call reports success (sqlite3_create_function_v2's documented behavior). An API that keeps caller ownership on failure cannot be modeled yet; nothing is inferred.
  4. Retention lasts until the resource is destroyed (§25, §45: "absent a modeled release"); no unregister clause is spelled by the ruling, so none exists. Retention is by the receiver (by param 0); by another parameter is refused, not silently a raw call. A retained C string keeps the Reject call-scoped str temporary for retained C-string params (§16.3c) #602 raw-call rule (not presented).
  5. One userdata per item; a userdata both consumed and retained is an error (one owner). callback consumes param N (§46) parses and is refused as not modeled — accepting it would have With release what the callback took.
  6. Reentrancy needs no "cannot invoke callbacks" clause: with captureless callbacks and &U userdata there is nothing for the assertion to relax; a mutable re-entry is impossible by construction (the exclusivity error in the retained-view fixture's first draft: cannot mutate d while v is a live view into it).
  7. share makes the resource Sync; send (with drop_any_thread) Send; ScopedSend follows Send (a scoped thread operates on the resource, so creator-bound stays out). callback_thread any requires the userdata Send and Sync (the callback reads it on any thread while the registering thread may hold it).

Not implemented / found

Eric Hartford added 2 commits September 24, 2026 00:11
…m here on; `ptr as Box[T]` takes it back (§16.2b.9 userdata)
….9-10)

A callback contract — an fn item that retains a callback or its userdata
(`retains … by param 0`), consumes userdata with a destroy callback
(`consumes … destroyed_by`), types a callback's userdata (`callback param N
userdata param M`), or says `callback_thread any` — is rendered as a method
of the resource its first parameter receives, generic in the userdata type
`U`: the callback is `extern "C" fn(&U, …)` (captureless, §12.4 — C
receives the code pointer alone) and the userdata is `&U` for the call
(§44), `U` owned by the resource until it is destroyed (§45: boxed, handed
to C as the pointer, released after the destroyer by the resource's Drop),
or `U` moved into C and destroyed by the callback the contract names (§24:
the compiler supplies the destroy fn for `U`; the parameter is withheld).
Reentrancy (§47) is by construction: no captures, the userdata a read view.

Sema: `callback param N userdata param M` verified (callable; `void *`; the
callback's one `void *` slot), never inferred from there being one of each
(typing a `void *` is capability-granting); `consumes` of a `void *` with
no destroy contract, a userdata both consumed and retained, `retains … by`
a non-resource or a non-receiver, and `callback consumes` (not modeled)
are errors; the callback argument is checked against the callback type
with `U` bound from the userdata argument, whatever order C declares them;
under `callback_thread any` the userdata type must be Send and Sync (§51).
Thread capabilities (§48-§50): a facade resource is Send/Sync exactly as
its `thread` clause says — thread-bound by default, never inferred from the
representation — and a spawn_os capture of one names the clause to state.

Fixtures: behavior for each rule, compile_errors with exact text,
debug-alloc for consumed userdata destroyed once and retained userdata
released once; behav_c_facade_facts_verify and _parses drop the clause
combination that now contradicts itself.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery green — head 9122b2b on main d783366, pinned seed, cold c_import cache, audits included (consume-with-destroy-callback is drop scheduling):

build        rc=0
:fixpoint    rc=0
:drop-audit  rc=0
:move-audit  rc=0
:test        rc=0   (no red targets)
:test-green  rc=0
:last-green  rc=0

Ready to merge: gh pr merge 1606 --squash. Stage 12 (SQLite facade) is being built on top of it and re-bases onto main once it lands.

@ehartford
ehartford marked this pull request as ready for review September 24, 2026 04:48
@ehartford
ehartford merged commit 2c7ed44 into main Sep 24, 2026
ehartford pushed a commit that referenced this pull request Sep 24, 2026
…trace_v2 present as methods (callback items render on the resource); the snapshot was recorded before #1606 landed
ehartford added a commit that referenced this pull request Sep 24, 2026
…d the audit lane (ruling §52) (#1615)

* rt: foreign-state domain rows for every runtime foreign call (ruling §52, spec §16.2b.14)

Each rt/*.w file that reaches a foreign symbol ends with an internal
`c facade` block declaring the three libc domains — `domain errno thread`,
`domain environ process`, `domain locale process` (ruling §33-§36) — and
one `fn` row per foreign extern: every `extern fn` under `@[link_name]` or
`@[import_module]`, and every one whose name is not an rt_*/with_* runtime
symbol. A row's silence invalidates (§38: unknown effect means invalidate);
`preserves domain D` appears only where the C standard says so, cited in
each block's header: C11 7.5p3 (errno — any library function may set it;
the accessor is the macro's lvalue, 7.5p2), C11 7.22.4.6 with POSIX
setenv/unsetenv/putenv/getenv (environ), C11 7.11.1.1 (locale: setlocale,
never called by the runtime). Win32, Winsock and WASI rows say nothing: the
C standard does not describe them. The LLVM memory.size/grow intrinsics are
not foreign calls.

385 rows over 12 files; each file still checks under --no-prelude, and the
emitted object's text is byte-identical to the row-less one (the facade
renders nothing: no resources, no methods).

* test: runtime-domain-audit fixtures — three the lane must reject, one it must accept

The lane proves it sees before it is trusted: `undeclared_extern.w` (a
libc seam with no row), `no_facade.w` (foreign symbols, no facade),
`missing_domain.w` (a facade that leaves one libc domain undeclared) each
start with `//! expect-violation: <text>` the lane must report;
`clean.w` (`//! expect-clean`) covers the runtime-internal externs the
lane must ignore, the LLVM intrinsic, and comments inside the block.

* build: runtime-domain-audit lane — a runtime foreign extern without a domain row is a red build (ruling §52)

In the shape of libc-surface-check (build/compiler.w): for every rt/*.w,
each foreign extern (@[link_name]/@[import_module], or a name outside
rt_*/with_*) must have an `fn` row in the file's one `c facade` block, and
the block must declare `domain errno thread`, `domain environ process`,
`domain locale process`. The verdict names the extern, its C symbol and
the facade the row belongs in. The compiler verifies what a row says when
the file compiles; the lane verifies nothing is left unsaid. It then runs
itself over test/runtime_domain_audit: each negative fixture must trip it
and the clean one must pass, so a silent lane is itself red. A `:test`
dependency beside libc-surface-check.

* Sema: same-named domains of distinct facade blocks are one domain, a word-for-word restated fn item is one contract (ruling §35)

With the runtime rows in, the dark rt-in-unit lane (WITH_RT_IN_UNIT, D30
R2b) parses every rt/*.w into one Sema and refused `domain errno thread`
as "declared twice" — rt_core.w's block against darwin_aarch64.w's, and
either against a program's libc facade — and then `fn rt_libc_exit` as
"described twice" (four runtime files declare and describe that extern).
Both refusals keyed identity by name across every facade in the unit.

Ruling §35: a facade "may also merge domains from distinct imports when
they refer to the same actual state". collect_facade_domain now merges a
second declaration with the same name and scope into the first — every
declaring block's functions touch the one domain (facade_domain_note_file
consults the merged facade set) — refuses one block declaring it twice
(identity is the block node, not the name: each runtime file's block is
`libc`), and refuses a different scope: one state has one scope (§36).
collect_facade_fn accepts a second block's word-for-word restatement of an
fn item (the same facts, compared as words) and refuses different clauses:
one function has one contract.

Tests: behav_c_facade_domain_merged / err_c_facade_domain_merged_invalidated
prove the merge is real (a bare fn in block B invalidates the text block A
borrowed from errno); err_c_facade_domain_scope_conflict,
err_c_facade_domain_twice, behav_c_facade_fn_restated,
err_c_facade_fn_restated_differently pin the rest. `WITH_RT_IN_UNIT=1
with-stage1 check test/hello.w` is green again (green at the base, red
with the rows before this).

* LibcFacade: getenv does not preserve environ (C11 7.22.4.6p4)

The toolchain libc facade stated `preserves domain environ` on `getenv`,
so a program could hold one getenv view across a second getenv. C11
7.22.4.6p4: the returned string "may be overwritten by a subsequent call
to the getenv function" — the second call invalidates the first view, and
a `preserves` grants a capability the standard does not back (the
ruling's test: never state what can create unsafety). The clause is
deleted from `fn getenv` only; the runtime's own getenv rows (rt/*.w,
ruling §52) already say the same. Every other row is unchanged.

err_c_facade_getenv_view_invalidated pins the refusal;
behav_c_facade_getenv_twice is the accepted spelling — copy the first out
(`to_owned()`) before the second call. No existing fixture holds a getenv
view across a second getenv (rg getenv test/ examples/
build/release_uat_fixtures/: two behavior tests, neither does).

* contract-view snapshot: with stage 9 on main, create_function_v2 and trace_v2 present as methods (callback items render on the resource); the snapshot was recorded before #1606 landed

* analyze: a semantic-snapshot request (contract, audit:contract) over a failed compilation is never ok — it prints the view and exits 1; the retained-no-owner contract fixture is a stage 9 compile error, so it becomes the refused-clause fixture

---------

Co-authored-by: Eric Hartford <[email protected]>
@ehartford
ehartford deleted the modeled-c-stage9 branch September 24, 2026 16:57
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