Repository navigation
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
Conversation
…#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
Contributor
|
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 configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (8)
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. Comment |
…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
enabled auto-merge (squash)
September 22, 2026 13:20
10 tasks
hyperpolymath
disabled auto-merge
September 22, 2026 13:20
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #812. Closes #813. Closes #696.
The Zig FFI tree did not compile.
zig build testfailed on all five roots, sothe 18 C exports and 16 connectors were pinned only by the
abi-codegen-drifttext gate — never by a compiler. This migrates the tree to the Zig 0.16 std,
then gates it.
The five commits
1145e0f3ef3627zig build test; rewrite the stale header6642e9638478eemise.tomlto Zig 0.16.0 and assert it againstZIG_VERSIONd7705a9#812 — the migration
0.16 did not rename these symbols; it made I/O capability an explicit
Ioparameter.
std.fsnow exports onlypathand the base64 tables, and the realhomes are
std.Io.Dirandstd.Io.Clock. Measured against the 0.16 std sourcerather 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.idrenumerates sixnormative ABI functions —
HealthCheck,ScanRepo,Dispatch,RecordOutcome,ForceLearningCycle,GetConfidence— and those are exactlythe six exports carrying no handle. Adding an
Ioparameter or a new initentry point would change the wire contract this FFI exists to pin. So the
capability is acquired once at the
export fnboundary (src/runtime.zig) andthreaded explicitly inwards.
Two decisions worth reviewing rather than skimming:
init_single_threaded, deliberately.Io.Threaded.initinstalls SIGIOand SIGPIPE handlers (
std/Io/Threaded.zig:1660-1661), which a shared objectloaded into a host process must not do.
getenvvia libc, deliberately. 0.16 removedgetenvfrom std and modelsthe environment as a
process.Environgiven to theIoimplementation — butinit_single_threadedsets that block to.emptyon every non-Windows target(
Threaded.zig:1675). AnIo-sourced lookup would return null for every key,and every
orelse defaultwould 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.zigsets
link_libc = trueon all six artifacts, sogetenv(3)is the honestequivalent, and a positive-control test now fails unless the variable is read.
Also fixed, and not a 0.16 change:
Handlewas declaredopaquewith twofields, a compile error under every Zig version.
main.zighad therefore nevercompiled, which is why nothing caught the rest.
The mutant
A passing suite proves nothing until one dies. Mutating the implementation —
portFor's+ 1to+ 2inunified-api-adapter.zig— rather than a testliteral, so the red proves the suite catches a real wire-layout defect:
All five roots still reported
compile test Debug native success, so this is anassertion 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 testis "independently RED onmain", the measured4/11 steps succeeded (3 failed); 7/7 tests passed, the enumeration of the 16un-migrated call sites and the
opaque-with-fields defect atmain.zig:46, andthe instruction to widen the job "once the tree is migrated".
The denominator guard
Kept and re-derived, not dropped.
zig build testreports through a differentline than
zig test, so the old awk — matchingAll N tests passedandN of N tests passed— would have matched nothing, read 0, and failed the stepon arrival. Both forms were measured locally:
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 allis now explicit: without it afully 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.contractilestates C ABI compatibility as an invariant and nothingverified it. The gate is
zig buildplusnm -D --defined-only, assertingexactly 18
T hypatia_*symbols. 18 is written as a contract, not ameasurement — 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:
hypatia_versionhypatia_health_check→hypatia_healthcheckThe second is the case the count alone cannot see, and the reason those six are
named. The untouched tree passes before and after each.
d7705a9came out of that exercise: running the gate after a failed buildreported
exported: 18 (expected 18)and passed, becausenmread the sharedobject left by the previous build. Under
set -euo pipefaila failedzig buildaborts first, and a fresh runner has no stale artefact — but thestep 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/*.idrduplicates it names were deleted under #815;
src/abi/now holds only the two.ipkgfiles 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 escapehatches" claim needing scoping, and
docs/proof-debt.mdciting a nonexistentscripts/check-trusted-base.shandcheck-trusted-basejob. Rather than letthem close silently with this PR, they are #831.
#813 — the version pin
mise.tomlsaidzig = "latest"while the workflow pinned0.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
latestmoves on its own, so the disagreement could appear with nobody touchingthe repository.
The
Justfilestated 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 instep, and a copy the assertion cannot see — it now says
mise install ziganddefers 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
zigpin out ofmise.tomlandcompares it to
ZIG_VERSION, before the toolchain install so a disagreementfails in seconds. Verified in all four directions — the real file passes; a pin
of
0.15.1fails; a pin floated back tolatestfails; a deletedziglinefails 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:
Was: did not compile.
actions.lockis untouched and stays valid —.github/workflows/zig.ymlisalready listed and no
uses:line changed in this PR, which also avoids thevalidate-spdxstaged-mode trap on any commit touching the lock.Also raised, not fixed here
mise.tomlalso provisionspythonanddenojs, both bannedestate-wide, plus a Python-only toolchain (
pip,black,isort,ruff,pytest) andPYTHON*env vars around them. Removing the two runtime linesalone would leave tools that cannot run, so it is its own change with its own
blast radius rather than a rider on a Zig version pin.
Note on enforcement
maincarries exactly one required check (abi-codegen-drift), so the Zig joblands advisory. It has no
paths:filter, deliberately, so it stayseligible 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