Skip to content

Modeled C stage 6: dependency (ruling §26-§30) - #1519

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

ehartford merged 2 commits into
mainfrom
modeled-c-stage6

Conversation

@ehartford

@ehartford ehartford commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Modeled C stage 6 (docs/modeled-c-implementation-plan.md; ruling §26–§30, §8, §57, §60, §61, §65; spec §16.2b.6, §21.1 Rules 6/7, §22).

Draft. Iterate-tier evidence only (:dev, targeted tests, :move-audit, :drop-audit). No :fixpoint/:test battery has run. Stage 6 is alone in its batch (ownership analysis). Two commits, based on main at 02301f8; the seed is 7c3ed983.

What a dependent producer renders to

Stage 5 rendered no constructor for a producer that receives another resource, and warned at the resource. It now renders one. The received resource is a borrow &P, handed to C as p.repr. The product is the plan's ephemeral struct, holding a view of each parent. Against the real sqlite3.h, with the ruling's own clauses (from sqlite3_prepare_v2(out param 3) / drop sqlite3_finalize / borrows param 0):

type Statement = ephemeral { parent: &Database, repr: *mut sqlite3_stmt, live: bool }
impl Drop for Statement:
    move fn drop():
        if self.live: unsafe { sqlite3_finalize(self.repr) }
fn Statement.sqlite3_prepare_v2(db: &Database, zSql: str, nByte: c_int, pzTail: *mut *const i8) -> (c_int, Option[Statement]):
    var slot: *mut sqlite3_stmt = null
    let status = unsafe { sqlite3_prepare_v2(db.repr, zSql, nByte, &raw mut slot, pzTail) }
    (status, if slot == null: None else: Some(Statement { parent: db, repr: slot, live: true }))

Because the dependency is an ordinary view, the ordinary analysis enforces it. The child is destroyed before its parent on every path. It cannot be returned past the parent or stored where the relationship is lost. The parent cannot be moved, destroyed or replaced while the child lives. No reference count or generation check is added (ruling §29).

The forms of dependency:

  • independent renders an ordinary, storable resource.
  • borrows param N names exactly the parents of the producer stated before it: a from, or the init.
  • Several parents become several view fields (parent_0, parent_1).
  • A parent that some producers do not receive is Option[&P].
  • An in-place resource's init may receive its parent.

The call site publishes the parent origin (the plan's "one gap"). A constructor's effect summary is inferred from its body. The rendered constructors are spliced after every user declaration, so every call to one was checked before its body: the summary was empty, and the dependency was not enforced. That is a general declaration-order bug, filed as #1473. The facade states the dependency, so the constructor signature now carries it as a declared summary, the way D39 declares an interface's origin.

Diagnostics (§8, §57)

Rule 6, Rule 7, returned-view escape, and mutation-while-viewed errors on a facade child now add:

  • what the child depends on;
  • the producer, and the resolved C parameter;
  • the evidence;
  • for a conservative dependency, the independent/borrows help (§8's own example).

For example, against the real sqlite3.h:

error: implicit drop of `stmt` uses `&db` after `db` is moved (§21.1 Rule 7)
 --> src/e_drop.w:26:10
26 |     drop(db)
  = label @26:10 `db` is moved here while `stmt` still borrows it
  = note: dependency: 'Statement' depends on 'Database', which producer 'sqlite3_prepare_v2' receives as param 0: *mut sqlite3 db — stated by 'borrows param 0' in facade sqlite (§16.2b.6)
  = help: drop or finish with `stmt` before `db` is moved or consumed

Without borrows, the note reads "conservative default of facade dbf: unknown independence means dependency", and a help names independent.

Two Rule 7 changes, both general and not facade-only:

  • "Implicit drop is a use" now covers a view whose type carries a Drop value. This includes Option[S], Vec[S] and tuples of it, not only S itself. Before, an Option[Statement] declared before its database was accepted, and its statement was finalized after the close. Pure-With fixture: err_implicit_drop_option_view_declared_before_origin.
  • Moving or consuming the origin is reported at the move ("after db is moved"). Before, it was reported at the view's declaration, and the origin's symbol id was passed where a node belonged.

§30.

error: 'App' stores a 'Statement', which depends on its 'Database' and cannot be stored in a non-ephemeral type; a type holding a 'Database' and a 'Statement' that depends on it is a self-referential layout (§16.2b.6)
  = note: dependency: …
  = help: borrow the parent instead of owning it, so App lives no longer than it: `type App = ephemeral { db: &Database, stmt: Statement }`; or keep the 'Statement' in a local declared after its parent

The fix-it compiles and runs (behav_c_facade_statement_cache).

§61 checks (each one a compile-error fixture)

  • borrows naming a parameter that receives no modeled resource: "With does not invent an origin" (§16.2b.7).
  • borrows naming the out slot.
  • independent together with borrows.
  • A received representation that several resources wrap: both candidates are named.
  • A pointer to a pointer resource's handle, which C could replace.
  • A pinned representation passed by value.
  • A preinit that receives a resource.

Each of these prints the resolved C parameter. A net under the renderer also requires that the rendered type is ephemeral exactly when the facts say the resource is dependent.

The two open surfaces, rendered per existing canon (commit 2)

Eric's reading of the canon (2026-09-23, on this PR): both are answered by the ruling as written.

1. ok on a dependent producer. Ruling §18: "A facade-specific error type may itself temporarily own the failure-state resource where required." It is not required here and cannot be done: an error escapes scopes, a dependent value cannot. So the generated <R>Error never owns a dependent child. D51's asymmetry test settles the fallback: a failing call that still produced a child has it destroyed at once by the facade's drop (exactly once; da_c_facade_dependent_ok_failure_destroyed_once witnesses it under the debug allocator) and returns Err(Failed(status)); a NULL slot with a failed status is Failed; success with NULL is NothingProduced. Against the real header, ok SQLITE_OK on sqlite3_prepare_v2 renders:

error StatementError =
    | Failed(status: c_int)
    | NothingProduced(status: c_int)
fn Statement.sqlite3_prepare_v2(db: &Database, zSql: str, nByte: c_int, pzTail: *mut *const i8) -> Result[Statement, StatementError]:
    var slot: *mut sqlite3_stmt = null
    let status = unsafe { sqlite3_prepare_v2(db.repr, zSql, nByte, &raw mut slot, pzTail) }
    if status != SQLITE_OK:
        if slot == null: return Err(StatementError.Failed(status))
        unsafe { sqlite3_finalize(slot) }
        return Err(StatementError.Failed(status))
    if slot == null: return Err(StatementError.NothingProduced(status))
    Ok(Statement { parent: db, repr: slot, live: true })

Real header: SELEKT nonsense gives Failed(1), "" gives NothingProduced(0), a ? chain works, memory returns to baseline, leak count 0. The stage-5 warning is gone.

2. returns borrow R from param N. Ruling §26: "The result: has no Drop; cannot outlive the named origin; cannot independently be consumed or destroyed. Nullable borrowed returns become Option of the borrowed modeled value." With D59's distinct-type precedent, the borrowed modeled value is Borrowed<R>: ephemeral, holding a view of the resource param N receives, carrying R's lend methods and none of its destroyers or Drop; the operation is a lend method of the resource its first parameter receives, and its result is Option[Borrowed<R>] (unknown nullability is nullable, §16.2b.8):

type BorrowedDatabase = ephemeral { origin: &Statement, repr: *mut sqlite3 }
impl BorrowedDatabase:
    fn sqlite3_errmsg() -> *const i8: unsafe { sqlite3_errmsg(self.repr) }
impl Statement:
    fn sqlite3_db_handle() -> Option[BorrowedDatabase]:
        let repr = unsafe { sqlite3_db_handle(self.repr) }
        if repr == null: None else: Some(BorrowedDatabase { origin: self, repr: repr })

Real header: stmt.sqlite3_db_handle() then sqlite3_errmsg through it prints "not an error"; back.sqlite3_close_v2() is "unknown method for type 'BorrowedDatabase'"; keeping back past stmt's scope is the Rule 6 error and drop(stmt) while back is used is the outlive error, each with the note "'BorrowedDatabase' is borrowed from the 'Statement' that 'sqlite3_db_handle' receives as param 0: *mut sqlite3_stmt p0 — stated by 'returns borrow Database from param 0' in facade sqlite". §61: the origin parameter and the first parameter each receive exactly one resource, and two items borrowing R from different resources are refused (one Borrowed<R>, one origin type) rather than given a second type.

Two general analysis fixes this needed:

  • A view returned from a method of an ephemeral value depends on that value. record_call_view_origins added the argument's root only when the argument had no origins of its own, so a view of an ephemeral receiver depended on the receiver's origins and not on the receiver, and outlived it. Pure-With repro (err_view_of_ephemeral_receiver_outlives_it): s.view() on an ephemeral Drop s, drop(s), use the view — accepted before.
  • Rule 7's "Drop value" test no longer sees a destructor through a reference (type_owns_user_drop): type_has_drop_impl(&W) answers as for W (A &P field of a mut self receiver is moved and blanked when P: Drop — reading self.db into a child nulls the receiver's field (segfault) #1492's mechanism), so a non-Drop view holding &Statement was reported as an implicit drop.

Behavior fixtures and witnesses

  • behav_c_facade_child_drop_order. A counting C header, test/behavior/c_facade_children.h, logs every finalize and close, and each close records the statements still open. A finalize reads its database, and a closed database is marked. The statement is finalized before its database on every path:
    • scope end;
    • early return;
    • ?;
    • loop break;
    • inside a Vec;
    • inside an Option;
    • in a match arm;
    • in a helper that borrows the database;
    • returned from a helper that borrows the database.
  • behav_c_facade_dependency_forms:
    • an independent snapshot is kept past its database and stored in a struct;
    • with borrows param 0, the second database closes while the link lives;
    • a backup with two parents finishes before both;
    • a cursor with an optional parent;
    • an in-place iterator over a database.
  • behav_c_facade_statement_cache. Ruling §30's compatible pattern: a cache that borrows the connection and owns its statements serves repeats from the cache, and finalizes everything before the close.
  • da_c_facade_child_before_parent (debug-alloc lane). The same paths run under the debug allocator. The order is asserted and the leak count is 0.
  • behav_c_facade_dependent_ok and da_c_facade_dependent_ok_failure_destroyed_once (commit 2): every outcome of an ok producer of a dependent child, with the destroy-order witness; a failure that produced is finalized exactly once under the debug allocator.
  • behav_c_facade_borrowed_return (commit 2): a borrowed database through a statement; nullable becomes Option; nothing is closed through it.
  • 28 facade compile-error fixtures and 3 pure-With fixtures. Rule 6/7 errors appear at the right site with their §57 notes, plus the §30, §61 and borrowed-return fixtures.
  • Rewritten for the new behavior:
    • behav_c_facade_pending_producer_warns now pins that the check runs warning-free, that a dependent producer has a constructor, and that Row.rw_open is a Result[Row, RowError].
    • behav_c_facade_parses and behav_c_facade_facts_verify no longer state independent beside borrows on one resource. That combination is now an error.
  • Real sqlite3.h (with get c.sqlite3 3.53.4, scratch project, not committed; build/release_uat_fixtures/ and examples/ untouched, §66):
    • SELECT sum(v) returns 49.
    • A helper borrows the connection.
    • Three statements are held in a Vec.
    • sqlite3_memory_used() returns exactly to its baseline after the scope, and again after db.sqlite3_close_v2() following a finalize.
    • A raw-C control shows the witness is sensitive: closing with an open statement returns SQLITE_BUSY (5).
    • --debug-alloc reports leak count 0, and the program exits 0 under guard malloc.
    • drop(db), db.sqlite3_close_v2(), returning the statement, and type App { db, stmt } are each refused with the note naming param 0: *mut sqlite3 db — stated by 'borrows param 0' in facade sqlite.

Evidence (iterate tier, stage1 at this commit)

  • Builds: :dev (seed to stage1) and the full build chain, which :move-audit and :drop-audit depend on (seed, stage1, stage2, release), both pass.
  • Facade and Rule 6/7 tests: all 124 *c_facade* tests (behavior, compile_errors, phase, debug_alloc) plus six Rule 6/7 tests pass on the release binary, 130/130. On stage1, behav_c_facade_libc_system_headers fails exactly as on main (memchr), and the p7 runner fixture needs stage2.
  • Regression sample (248 tests): every view, ephemeral, origin, Rule 6/7, retain and c_import test in test/, run on stage1 against main's stage1 (ba2d5d1). This PR fails nothing that passes on main: 197 pass here, 190 on main. The 51 that still fail here also fail on main, mostly d_acceptance and non_compliant/d22 under the stage1 runner.
  • Debug-alloc lane: debug_drop check (release) over the six facade fixtures: PASS, leak count 0.
  • :move-audit (rerun after commit 2): 73 cells, 0 FAIL against expectations. It also shows 42 DIFF against the seed baseline: all of them are field_* cells where the seed predates the strict field-move rule. The candidate's verdict columns are byte-identical to main's stage1 run with the same seed.
  • :drop-audit (rerun after commit 2): 176 cells, 0 non-PASS, 0 regressions.
  • analyze audit:all: passes on behav_c_facade_child_drop_order, behav_c_facade_statement_cache, behav_c_facade_dependent_ok, behav_c_facade_borrowed_return and da_c_facade_child_before_parent. behav_c_facade_dependency_forms has one violation: the Box.drop receiver violation (analyze audit:all reports two pre-existing violations on any program that uses std.box (with_free marshalling fact, sig receiver requirement) #1300), which main reproduces on behav_c_facade_resource_in_place_pinned.
  • Examples: examples/**/*.w give the same with check verdicts as on main.

Filed while doing this

Flip: none. UAT fixtures and examples are untouched, and the spec is untouched.

Eric Hartford added 2 commits September 23, 2026 17:28
A producer that receives modeled resources now gets its constructor, and
what it produces depends on them (spec §16.2b.6: "unknown independence
means dependency"). Stage 5 rendered no constructor for such a producer and
warned at the resource; that warning is replaced.

Rendering (compiler/FacadeRender.w). A received resource is presented to
the constructor as a borrow `&P` and handed to C as `p.repr` (or the pinned
cell's address); the raw handle of a modeled resource is never a
constructor parameter. A dependent resource is the plan's ephemeral struct
holding a view of each parent:

    type Statement = ephemeral { parent: &Database, repr: *mut sqlite3_stmt, live: bool }
    fn Statement.sqlite3_prepare_v2(db: &Database, zSql: str, nByte: c_int, pzTail: *mut *const i8) -> (c_int, Option[Statement]):
        var slot: *mut sqlite3_stmt = null
        let status = unsafe { sqlite3_prepare_v2(db.repr, zSql, nByte, &raw mut slot, pzTail) }
        (status, if slot == null: None else: Some(Statement { parent: db, repr: slot, live: true }))

so the ordinary origin and ephemeral analysis (§21.1, §22) enforces the
dependency; no reference count or generation check is added (ruling §29).
`independent` renders an ordinary resource; `borrows param N` names
exactly the parents of the producer stated before it (a `from` or the
`init`); several parents are several view fields; a parent some producers
lack is `Option[&P]`; an in-place resource's `init` may receive its parent.

Facts and verification (SemaFacade.w, ruling §61, §57). `borrows` names a
parameter of the producer before it and never its out slot or storage;
the parameter must receive a modeled resource (With does not invent an
origin, §16.2b.7); `independent` with `borrows` is refused; a received
representation several resources wrap names the candidates; a received
shape a borrow cannot present (a pointer to a pointer resource's handle, a
pinned representation by value) and a `preinit` receiving a resource are
errors naming the resolved C parameter. A net checks the rendered type is
ephemeral exactly when the facts say the resource is dependent.

The call site publishes the parent origin. A constructor's effect summary
is inferred from its body, and the rendered constructors are spliced after
every user declaration, so every call was checked before the body it
calls and tied nothing (#1473 is the general declaration-order bug). The
facade states the dependency, so the constructor's signature carries it as
a declared summary (apply_facade_dependency_effects), the way D39 declares
an interface's origin.

Diagnostics (§8, §57). Rule 6, Rule 7, the returned-view escape and the
mutation-while-viewed errors on a value carrying a dependent facade
resource add what it depends on, the producer, the resolved C parameter
and the evidence ("stated by 'borrows param 0' in facade sqlite" or
"conservative default of facade dbf: unknown independence means
dependency"), and, for a conservative dependency, the `independent` /
`borrows` help (§8's own example).

Rule 7 (Sema.w). "Implicit drop is a use" now covers a view binding whose
type carries a Drop value — `Option[S]`, `(i32, Option[S])`, `Vec[S]` of an
ephemeral Drop `S` — not only `S` itself: an `Option[Statement]` declared
before its database was accepted and finalized after the close. A move or
consumption of the origin (`drop(db)`, `let moved = db`, a `move fn`
destroyer) is reported at the move ("after `db` is moved"); it was reported
at the view's declaration with the origin's symbol id as the node.

Ruling §30. A type storing a dependent resource is the §5 ephemeral-storage
error, reported for a facade resource with its dependency and a fix that
compiles: `type App { db: Database, stmt: Statement }` gets
"help: borrow the parent instead of owning it, so App lives no longer than
it: `type App = ephemeral { db: &Database, stmt: Statement }`".

Not rendered, and said so loudly (open questions for a ruling):
- `ok` on a dependent resource's out-parameter producer: its
  failed-but-produced resource would be a dependent value inside
  `<R>Error.FailedWithResource`; no constructor, warning at the resource.
- `returns borrow R from param N`: collected and verified, but the
  borrowed modeled value has no With type; the operation stays raw C,
  warning at the fn item.

Tests: behav_c_facade_child_drop_order (destroy-order witness on every
path), behav_c_facade_dependency_forms (independent, borrows, two parents,
optional parent, in place), behav_c_facade_statement_cache (§30's cache
and the App fix-it compile and run), da_c_facade_child_before_parent
(debug allocator, leak count 0, order asserted), 22 compile-error fixtures
(Rule 6/7 at the right site with §57 notes, §30, §61), two pure-With Rule
7 fixtures; behav_c_facade_pending_producer_warns rewritten for the new
warnings; behav_c_facade_parses/_facts_verify stop combining
`independent` with `borrows` on one resource.
…ders `Borrowed<R>` (ruling §18, §26)

The two surfaces the first stage-6 commit left unrendered, resolved from
existing canon (Eric, 2026-09-23, on #1519).

`ok` on a dependent resource's out-parameter producer (ruling §18: "A
facade-specific error type may itself temporarily own the failure-state
resource where required"). The generated `<R>Error` never owns a dependent
child: an error escapes scopes and a dependent value cannot, so it is not
required here and cannot be done. D51's asymmetry test settles the fallback
— a failing call that still produced a child has it destroyed at once by
the facade's `drop`, exactly once, and returns `Err(Failed(status))`; a NULL
slot with a failed status is `Failed`; success with NULL is
`NothingProduced`. So `ok SQLITE_OK` on `sqlite3_prepare_v2` renders
`Result[Statement, StatementError]` with `StatementError = Failed |
NothingProduced` and no `FailedStatement`:

    fn Statement.sqlite3_prepare_v2(db: &Database, zSql: str, nByte: c_int, pzTail: *mut *const i8) -> Result[Statement, StatementError]:
        var slot: *mut sqlite3_stmt = null
        let status = unsafe { sqlite3_prepare_v2(db.repr, zSql, nByte, &raw mut slot, pzTail) }
        if status != SQLITE_OK:
            if slot == null: return Err(StatementError.Failed(status))
            unsafe { sqlite3_finalize(slot) }
            return Err(StatementError.Failed(status))
        if slot == null: return Err(StatementError.NothingProduced(status))
        Ok(Statement { parent: db, repr: slot, live: true })

The stage-5 "no constructor is rendered" warning is gone with the pending
producer it reported.

`returns borrow R from param N` (ruling §26: "The result: has no Drop;
cannot outlive the named origin; cannot independently be consumed or
destroyed. Nullable borrowed returns become Option of the borrowed modeled
value"). The borrowed modeled value is the distinct type `Borrowed<R>`
(D59's precedent): ephemeral, holding a view of the resource param N
receives, carrying R's lend methods over the same `repr` and none of its
destroyers or Drop; the operation is a lend method of the resource its
first parameter receives, returning `Option[Borrowed<R>]`:

    type BorrowedDatabase = ephemeral { origin: &Statement, repr: *mut sqlite3 }
    impl BorrowedDatabase:
        fn sqlite3_errmsg() -> *const i8: unsafe { sqlite3_errmsg(self.repr) }
    impl Statement:
        fn sqlite3_db_handle() -> Option[BorrowedDatabase]:
            let repr = unsafe { sqlite3_db_handle(self.repr) }
            if repr == null: None else: Some(BorrowedDatabase { origin: self, repr: repr })

Verified (§61): the origin parameter receives exactly one resource, the
first parameter does (so the operation has a resource to be a method of),
and every item borrowing R names one origin resource — `Borrowed<R>` holds
one view type, and a borrowed value with several origin types is refused
rather than given a second type. `Borrowed<R>` joins the generated names a
same-named type collides with. The net checks the type and the method were
rendered, and the method's signature carries the origin as a declared
summary, as the constructors do. Rule 6/7 and outlive errors on a borrowed
value name what it is borrowed from and the clause (§8, §57).

Two analysis fixes the borrowed value needed, both general:
- A call result depends on a VALUE argument's own storage
  (record_call_view_origins): the root was added only when the argument
  had no origins of its own, so a view returned from a method of an
  ephemeral value — a statement's borrowed database, a token from a
  `Parser` value — depended on the value's origins and not on the value,
  and outlived it (§21.1 Rule 6, §5.5). A reference argument stays
  transparent. Pure-With repro: `s.view()` on an ephemeral Drop `s`,
  `drop(s)`, use the view — accepted before.
- Rule 7's "Drop value" test sees no destructor through a reference
  (type_owns_user_drop): `type_has_drop_impl(&W)` answers as for `W`
  (get_type_name looks through references, #1492), so a non-Drop view
  holding `&Statement` was reported as an implicit drop; it is reported as
  a view that outlives its origin.

Tests: behav_c_facade_dependent_ok (each outcome with the destroy-order
witness; `?` chains), da_c_facade_dependent_ok_failure_destroyed_once
(debug allocator: a failure that produced is finalized exactly once, leak
count 0, order asserted), behav_c_facade_borrowed_return (borrowed
database through a statement; nullable → Option; no close through it),
five borrowed-return compile-error fixtures (outlives its origin, origin
dropped with the §57 note, destroyer not presented, stored in a struct,
origin not a resource, two origin resources);
behav_c_facade_pending_producer_warns rewritten: the check runs
warning-free and `Row.rw_open` is a `Result[Row, RowError]`.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery green — head f55dff7 (rebased on main 02301f8, no diff change), driven by the pinned seed with a cold c_import cache, audits included because stage 6 adds ownership surfaces (StatementError, BorrowedDatabase):

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.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 22:54
@ehartford
ehartford merged commit cfeaa6b into main Sep 24, 2026
@ehartford
ehartford deleted the modeled-c-stage6 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