Skip to content

fix(ffi/zig): migrate to the Zig 0.16 std, then gate it — tests, C ABI exports, and the version pin (#812, #813, #696) - #833

Merged
hyperpolymath merged 6 commits into
mainfrom
fix/812-zig-016-std
Sep 22, 2026
Merged

hyperpolymath merged 6 commits into
mainfrom
fix/812-zig-016-std

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

Closes #812. Closes #813. Closes #696.

The Zig FFI tree did not compile. zig build test failed on all five roots, so
the 18 C exports and 16 connectors were pinned only by the abi-codegen-drift
text gate — never by a compiler. This migrates the tree to the Zig 0.16 std,
then gates it.

The five commits

Commit Issue What
1145e0f #812 Migrate the tree to the 0.16 std API — 16 call sites, all five roots
3ef3627 #812 Widen the CI job from one file to zig build test; rewrite the stale header
6642e96 #696 Pin the 18-symbol C ABI export surface
38478ee #813 Pin mise.toml to Zig 0.16.0 and assert it against ZIG_VERSION
d7705a9 #696 Rebuild from a removed artefact in the export step

#812 — the migration

0.16 did not rename these symbols; it made I/O capability an explicit Io
parameter. std.fs now exports only path and the base64 tables, and the real
homes are std.Io.Dir and std.Io.Clock. Measured against the 0.16 std source
rather than guessed, because a plausible guess here produces a migration that
compiles and is wrong.

The C ABI does not change. src/Hypatia/ABI/FFI.idr enumerates six
normative ABI functions — HealthCheck, ScanRepo, Dispatch,
RecordOutcome, ForceLearningCycle, GetConfidence — and those are exactly
the six exports carrying no handle. Adding an Io parameter or a new init
entry point would change the wire contract this FFI exists to pin. So the
capability is acquired once at the export fn boundary (src/runtime.zig) and
threaded explicitly inwards.

Two decisions worth reviewing rather than skimming:

  • init_single_threaded, deliberately. Io.Threaded.init installs SIGIO
    and SIGPIPE handlers (std/Io/Threaded.zig:1660-1661), which a shared object
    loaded into a host process must not do.
  • getenv via libc, deliberately. 0.16 removed getenv from std and models
    the environment as a process.Environ given to the Io implementation — but
    init_single_threaded sets that block to .empty on every non-Windows target
    (Threaded.zig:1675). An Io-sourced lookup would return null for every key,
    and every orelse default would silently take the default. That is a symbol
    "fixed" by deletion wearing a passing test, which Migrate ffi/zig to the Zig 0.16 std (3 of 4 test roots do not compile) #812 forbids. build.zig
    sets link_libc = true on all six artifacts, so getenv(3) is the honest
    equivalent, and a positive-control test now fails unless the variable is read.

Also fixed, and not a 0.16 change: Handle was declared opaque with two
fields, a compile error under every Zig version. main.zig had therefore never
compiled, which is why nothing caught the rest.

The mutant

A passing suite proves nothing until one dies. Mutating the implementation —
portFor's + 1 to + 2 in unified-api-adapter.zig — rather than a test
literal, so the red proves the suite catches a real wire-layout defect:

error: 'unified-api-adapter.test.port layout matches v-lang reference' failed:
expected 8001, found 8002    at ffi/zig/src/unified-api-adapter.zig:154
Build Summary: 9/11 steps succeeded (1 failed); 20/21 tests passed (1 failed)

All five roots still reported compile test Debug native success, so this is an
assertion failure, not a compile error — which is what #812's third
criterion asks for. Reverting restored rc=0.

The workflow header

Rewritten, not trimmed. Every factual claim in it was about the pre-migration
tree: that zig build test is "independently RED on main", the measured
4/11 steps succeeded (3 failed); 7/7 tests passed, the enumeration of the 16
un-migrated call sites and the opaque-with-fields defect at main.zig:46, and
the instruction to widen the job "once the tree is migrated".

The denominator guard

Kept and re-derived, not dropped. zig build test reports through a different
line than zig test, so the old awk — matching All N tests passed and
N of N tests passed — would have matched nothing, read 0, and failed the step
on arrival. Both forms were measured locally:

Build Summary: 11/11 steps succeeded; 21/21 tests passed
Build Summary: 9/11 steps succeeded (1 failed); 20/21 tests passed (1 failed)

They share a field layout, so one parse covers both. Verified against the real
green log, the failure line from the mutant run, and input with no summary line
at all (yields 0, which fails). --summary all is now explicit: without it a
fully cached build prints no summary line, so the guard would have nothing to
parse on exactly the runs most likely to be green.

The floor is 8, not 21. #812 requires more than the 7 tests the single-file
scope reached; an exact count would redden the gate every time someone adds a
test.

#696 — the C ABI export pin

MUST.contractile states C ABI compatibility as an invariant and nothing
verified it. The gate is zig build plus nm -D --defined-only, asserting
exactly 18 T hypatia_* symbols. 18 is written as a contract, not a
measurement
— the error message says changing it is a deliberate ABI decision,
because a gate whose expected value can be edited to match reality is not a gate.

A count alone cannot see a rename that preserves it, so the six normative
functions are also named individually. There is no C header in this repository
to diff a full name set against; naming the normative six is the honest pin
available.

Both mutants die:

Mutant Count Result
Un-export hypatia_version 18 → 17 fails on the count
Rename hypatia_health_check → hypatia_healthcheck stays 18 fails on the normative-name check

The second is the case the count alone cannot see, and the reason those six are
named. The untouched tree passes before and after each.

d7705a9 came out of that exercise: running the gate after a failed build
reported exported: 18 (expected 18) and passed, because nm read the shared
object left by the previous build. Under set -euo pipefail a failed
zig build aborts first, and a fresh runner has no stale artefact — but the
step now removes the file before rebuilding, so the property does not depend on
either.

#696's other half is already closed. The six byte-identical src/abi/*.idr
duplicates it names were deleted under #815; src/abi/ now holds only the two
.ipkg files and a README.

Not closed here: #696's "For contrast" section recorded two documentation
defects that are not part of either fix — AFFIRMATION.adoc's "zero escape
hatches" claim needing scoping, and docs/proof-debt.md citing a nonexistent
scripts/check-trusted-base.sh and check-trusted-base job. Rather than let
them close silently with this PR, they are #831.

#813 — the version pin

mise.toml said zig = "latest" while the workflow pinned 0.16.0.
Developers built with whatever Zig was current and CI built with 0.16.0, so a
green CI result said nothing about the compiler anyone actually ran — and
latest moves on its own, so the disagreement could appear with nobody touching
the repository.

The Justfile stated a third version: asdf plugin add zig && asdf install zig 0.13.0. Rather than update that literal to 0.16.0 — three places to keep in
step, and a copy the assertion cannot see — it now says mise install zig and
defers to the pin. Three stated versions become two, and the two are asserted
equal. (asdf was the wrong tool to name regardless: this repository configures
mise.)

#813 says a comment naming the other file is the weakest acceptable form, so
this is an assertion: a CI step parses the zig pin out of mise.toml and
compares it to ZIG_VERSION, before the toolchain install so a disagreement
fails in seconds. Verified in all four directions — the real file passes; a pin
of 0.15.1 fails; a pin floated back to latest fails; a deleted zig line
fails as "no pinned version", because mise.toml having no pin is the defect.

And the pinned version is the one measured green, not assumed to be.

Verification

Every step body was run locally, verbatim, before pushing:

STEP: Agree with the mise.toml pin   mise.toml zig = 0.16.0; ZIG_VERSION = 0.16.0   rc=0
STEP: Verify the toolchain           0.16.0                                          rc=0
STEP: Run the Zig tests              Build Summary: 11/11 steps succeeded;
                                     21/21 tests passed → tests run: 21              rc=0
STEP: Pin the C ABI export surface   exported C functions: 18 (expected 18)
                                     all six normative names present                 rc=0

Was: did not compile.

actions.lock is untouched and stays valid — .github/workflows/zig.yml is
already listed and no uses: line changed in this PR, which also avoids the
validate-spdx staged-mode trap on any commit touching the lock.

Also raised, not fixed here

Note on enforcement

main carries exactly one required check (abi-codegen-drift), so the Zig job
lands advisory. It has no paths: filter, deliberately, so it stays
eligible to be made required without the filter/required deadlock — making it
required is an owner action.

🤖 Generated with Claude Code

https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV

hyperpolymath and others added 5 commits September 22, 2026 13:59
…#812)

The Zig FFI tree did not compile. `zig build test` failed on all five roots;
the 18 C exports and 16 connectors were pinned only by the abi-codegen-drift
text gate, never by a compiler.

0.16 did not rename these symbols -- it made I/O capability an explicit `Io`
parameter. `std.fs` now exports only `path` and the base64 tables; the real
homes are `std.Io.Dir` and `std.Io.Clock`. Measured against the 0.16 std source
rather than guessed, because a plausible guess here produces a migration that
compiles and is wrong.

Design: the C ABI does not change. `src/Hypatia/ABI/FFI.idr` enumerates six
normative ABI functions -- HealthCheck, ScanRepo, Dispatch, RecordOutcome,
ForceLearningCycle, GetConfidence -- and those are exactly the six exports that
carry no handle. Adding an `Io` parameter or a new init entry point would change
the wire contract this FFI exists to pin. So the capability is acquired once at
the `export fn` boundary (src/runtime.zig) and threaded explicitly inwards, so
every internal function is testable with an injected `Io`. The 0.15 code was
already ambient (`std.fs.cwd()`, `std.time.timestamp()`, `std.posix.getenv`);
0.16 made the ambient explicit, and this is the faithful translation.

`init_single_threaded` is deliberate: `Io.Threaded.init` installs SIGIO and
SIGPIPE handlers (std/Io/Threaded.zig:1660-1661), which a shared object loaded
into a host process must not do. It also spawns no worker threads.

getenv has no `Io`-based replacement here. 0.16 removed `getenv` from std
entirely and models the environment as a `process.Environ` given to the `Io`
implementation -- but `init_single_threaded` sets that block to `.empty` on every
non-Windows target (Threaded.zig:1675), so an Io-sourced lookup would return null
for every key and every `orelse default` would silently take the default. That is
a symbol "fixed" by deletion wearing a passing test, which #812 forbids. build.zig
sets `link_libc = true` on all six artifacts, so `getenv(3)` is the honest
equivalent, and a positive-control test now fails unless the variable is read.

Per-symbol migration, all 16 sites:
  std.fs.cwd()                 -> std.Io.Dir.cwd()
  dir.createFile/openFile      -> + io parameter
  dir.access                   -> + io parameter
  dir.readFileAlloc(a,p,n)     -> readFileAlloc(io, p, gpa, Io.Limit) [reordered]
  std.fs.openFileAbsolute      -> std.Io.Dir.openFileAbsolute(io, ...)
  std.fs.createFileAbsolute    -> std.Io.Dir.createFileAbsolute(io, ...)
  std.fs.openDirAbsolute       -> std.Io.Dir.openDirAbsolute(io, ...)
  std.fs.deleteFileAbsolute    -> std.Io.Dir.deleteFileAbsolute(io, ...)
  file.close()                 -> file.close(io)
  file.readAll(buf)            -> file.readPositionalAll(io, buf, 0)
  file.writeAll(b)             -> file.writePositionalAll(io, b, offset)
  file.seekFromEnd(0) + write  -> file.length(io) then positional write
  dir.iterate().next()         -> iter.next(io)
  std.time.timestamp()         -> std.Io.Clock.now(.real, io).toSeconds()
  std.posix.getenv(k)          -> runtime.getEnv(k), see above
  std.mem.trimLeft             -> std.mem.trimStart
  callconv(.C)                 -> callconv(.c)

Also fixed, and NOT a 0.16 change: `Handle` was declared `opaque` with two
fields, which is a compile error under every Zig version. main.zig has therefore
never compiled, which is why nothing ever caught the rest. C still sees an opaque
pointer; the state moved to a private `HandleState` reached through `state()`.

`runtime` is wired as a build module rather than a relative import so the
process-wide `Io` is one global, not one per importing module.

Verified: `zig build test` rc=0, 11/11 steps, 21/21 tests across all five roots
(was: did not compile). `zig build` rc=0 and `nm -D` on the built
libhypatia_ffi.so reports exactly 18 `T hypatia_*` symbols, unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV
The job ran `zig test ffi/zig/src/unified-api-adapter.zig` because the other
four test roots did not compile against the 0.16 standard library. 1145e0f
migrated them, so the narrow scope is no longer the maximal green subset --
it is just a smaller one.

The header comment is rewritten rather than trimmed. Every factual claim in it
was about the pre-migration tree: that `zig build test` is "independently RED
on `main`", the measured "4/11 steps succeeded (3 failed); 7/7 tests passed",
the enumeration of the 16 un-migrated call sites and the `opaque`-with-fields
defect at main.zig:46, and the instruction to "widen it to `zig build test`
once the tree is migrated". Leaving any of it in place would leave the file
asserting something no longer true.

The denominator guard is kept and re-derived, not dropped. `zig build test`
reports through a different line than `zig test`, so the old awk -- which
matched `All N tests passed` and `N of N tests passed` -- would have matched
nothing, read 0, and failed the step on arrival. Measured both forms locally:

  Build Summary: 11/11 steps succeeded; 21/21 tests passed
  Build Summary: 9/11 steps succeeded (1 failed); 20/21 tests passed (1 failed)

They share a field layout, so one parse covers both; the new awk takes the
denominator of the `X/Y tests passed` field. Verified against the real green
log, against the failure line from the mutant run, and against input carrying
no summary line at all (yields 0, which fails the step). Still awk rather than
`grep ... || true`, for the reason the original comment gives: a suppressed
exit code is indistinguishable from a masked failure.

`--summary all` is now passed explicitly. Without it a fully cached build
prints no "Build Summary:" line, so the guard would have no input to parse on
exactly the runs most likely to be green.

The floor is 8, not 21. #812 requires this job to cover more than the 7 tests
the single-file scope reached; an exact count would redden the gate every time
someone adds a test, which is drift surface, not a contract.

Verified: `zig build test --summary all` locally reports
"11/11 steps succeeded; 21/21 tests passed", rc=0, and the awk yields 21.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV
`MUST.contractile` states C ABI compatibility as an invariant and nothing
verified it. No workflow ran `zig build` at all, so a breaking change to any
of the 18 exports would have landed silently -- #696's remaining half.

The gate is `zig build` plus `nm -D --defined-only` on the built
libhypatia_ffi.so, asserting exactly 18 `T hypatia_*` symbols. 18 is written
as a contract, not read from the tree: changing it is a deliberate ABI
decision, and the error message says so, because a gate whose expected value
can be edited to match reality is not a gate.

A count alone cannot see a rename that preserves it, so the six functions
src/Hypatia/ABI/FFI.idr declares normative -- HealthCheck, ScanRepo, Dispatch,
RecordOutcome, ForceLearningCycle, GetConfidence, exactly the six exports that
carry no handle -- are also named individually. There is no C header in this
repository to diff a full name set against; naming the normative six is the
honest pin available.

`grep -c` is avoided throughout: it exits 1 on zero matches, which is the
precise case this step exists to catch, so under `set -e` it would need
suppressing and the suppression would be indistinguishable from a masked
failure. Counting through awk leaves the comparison as the only thing that
can fail the step.

#696's other half is already closed: the six byte-identical `src/abi/*.idr`
duplicates it names were deleted under #815, and `src/abi/` now holds only the
two .ipkg files and a README.

Justfile: the help text claimed `ffi/zig/ - 7 exported C functions`. There are
18, measured twice -- `grep -c 'export fn'` over the source and `nm -D` over
the built object both report 18. Corrected to the number this gate now pins.

Verified locally: `zig build` rc=0; the step body reports
"exported C functions: 18 (expected 18)"; all six normative names resolve; and
a deliberately nonexistent symbol correctly does not.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV
mise.toml said `zig = "latest"` while .github/workflows/zig.yml pinned
ZIG_VERSION 0.16.0. Developers therefore built with whatever Zig was current
and CI built with 0.16.0, so a green CI result said nothing about the compiler
anyone actually ran -- and `latest` moves on its own, so the disagreement could
appear without anyone touching the repository.

The Justfile stated a third version: its toolchain advice was
`asdf plugin add zig && asdf install zig 0.13.0`. Rather than updating that
literal to 0.16.0 -- which would leave three places to keep in step, and add
a copy the assertion below cannot see -- it now says `mise install zig` and
defers to the pin. Three stated versions become two, and the two are asserted
equal. asdf was the wrong tool to name in any case: this repository configures
mise, not asdf.

#813 asks for a check that makes the two impossible to drift apart silently,
and says a comment naming the other file is the weakest acceptable form. So
this is an assertion, not a comment: a CI step parses the `zig` pin out of
mise.toml and compares it to ZIG_VERSION. It runs before the toolchain install
so a disagreement fails in seconds rather than after a download. An absent pin
fails explicitly -- mise.toml having no zig line is the defect, not a reason to
skip the check.

Verified in all four directions: the real file passes; a pin of 0.15.1 fails;
a pin floated back to "latest" fails; a deleted zig line fails as "no pinned
version". And the pinned version is the one measured green, not assumed to be:
`zig build test --summary all` under 0.16.0 reports "11/11 steps succeeded;
21/21 tests passed", and the workflow's existing `test "$(zig version)" =
"${ZIG_VERSION}"` step keeps the installed toolchain honest about it.

Not changed here, deliberately: mise.toml also pins `python` and `denojs`,
both banned estate-wide. That is a separate finding with its own blast radius
-- the file carries a whole Python toolchain (pip, black, isort, ruff, pytest)
and PYTHON* env vars -- and is raised as its own issue rather than folded into
a Zig version pin.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV
Found by mutanting the gate rather than by reading it. Un-exporting a symbol
so the build fails, then running the gate, reported "exported: 18 (expected
18)" and passed -- because `nm` had read the shared object left by the
previous successful build. The gate was describing a tree that no longer
compiled.

In the workflow the step runs under `set -euo pipefail`, so a failed
`zig build` aborts before `nm` runs and this cannot happen; and a fresh runner
has no stale artefact to read in the first place. Removing the file before
rebuilding costs nothing and makes the property hold without depending on
either of those, which is worth having in a step whose entire purpose is to
be believed when it says a number.

Both mutants now die correctly. Un-exporting hypatia_version drops the count
to 17 and fails on the count. Renaming hypatia_health_check to
hypatia_healthcheck keeps the count at 18 and fails on the normative-name
check -- which is the case the count alone cannot see, and the reason those
six are named. The untouched tree passes before and after each.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV
@coderabbitai

coderabbitai Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 8ee09bcc-2f86-40d3-a912-da10e790a12c

📥 Commits

Reviewing files that changed from the base of the PR and between cb6b21c and d7705a9.

📒 Files selected for processing (8)
  • .github/workflows/zig.yml
  • Justfile
  • ffi/zig/build.zig
  • ffi/zig/src/file_ops.zig
  • ffi/zig/src/main.zig
  • ffi/zig/src/runtime.zig
  • ffi/zig/test/integration_test.zig
  • mise.toml
 ______________________________________________________________
< Your function has more side effects than my caffeine intake. >
 --------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Comment thread .github/workflows/zig.yml Fixed
…lanation

The Hypatia scanner reported one new alert on this PR: RE005, "step `Run the
Zig tests` swallows non-zero exit via `|| true` -- failures will be masked".

There is no `|| true` in the step. The only occurrence in the file was inside
the comment explaining why the step deliberately uses awk *instead of* grep
with a suppressed exit code. RE005 regexes the raw step body
(`Regex.match?(~r/\|\|\s*true\b/, body)`, lib/rules/research_extensions.ex:608)
with no comment stripping, so it matched the prose arguing against the thing
it was looking for.

The comment is reworded rather than deleted or pragma-suppressed: it explains
a real design decision and should stay legible. Nothing about the step changes.

The detector defect is raised separately -- it is a false-positive class that
will hit anyone who documents avoiding `|| true`, and its sibling in
cicd_rules.ex:938 already strips comments for exactly this reason.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0113HQM9LVGkNCzU1WwkJZSV
@hyperpolymath
hyperpolymath enabled auto-merge (squash) September 22, 2026 13:20
@hyperpolymath
hyperpolymath merged commit 3bf9674 into main Sep 22, 2026
75 of 91 checks passed
@hyperpolymath
hyperpolymath deleted the fix/812-zig-016-std branch September 22, 2026 13:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants