Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions ROADMAP.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@

toc::[]

== Header public-boundary qualification (2026-11-25)

The next Atoma consumer slice adds a bounded Idris2 span contract and instruments
the actual Zig public entry for null-before-call, exact pointer/length forwarding
and error mapping. Four compiled source mutants and an invalid-span type witness
must reject. The real RefC-backed ABI tests remain required alongside the
instrumented backend. Three additional exported-forwarder mutants exercise
pointer, extent and null refusal through the actual library. A bounded pure Zig
benchmark records correctness-guarded timings of the exported Idris-backed
header operation; these initial samples establish no regression threshold.
Hosted qualification remains required for each changed head; no full
pointer-safety or ownership claim follows from the source files alone. See
link:docs/adr/2026-11-25-header-public-boundary.adoc[the boundary decision].

== Lifecycle integration (2026-11-25)

PR246 integrates lifecycle policy with the current Idris-backed header profile
Expand Down
49 changes: 49 additions & 0 deletions benchmarks/header_boundary.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
const std = @import("std");
const builtin = @import("builtin");
const BoolResult = extern struct { status: c_int, value: bool };
extern fn proven_header_has_crlf(?[*]const u8, usize) callconv(.c) BoolResult;

fn requireCorrect(result: BoolResult, expected: bool) !void {
if (result.status != 0) return error.WrongHeaderStatus;
if (result.value != expected) return error.WrongHeaderResult;
}

fn sampleCase(name: []const u8, input: []const u8, expected: bool, iterations: usize) !void {
// Qualify each corpus before measuring. Timed calls retain correctness
// guards too; elapsed time includes those guards, not only the foreign call.
try requireCorrect(proven_header_has_crlf(input.ptr, input.len), expected);
for (0..32) |_| try requireCorrect(proven_header_has_crlf(input.ptr, input.len), expected);
var digest = [_]u8{0} ** 32;
std.crypto.hash.sha2.Sha256.hash(input, &digest, .{});
const input_hash = std.fmt.bytesToHex(digest, .lower);
for (0..3) |sample| {
var checksum: usize = 0;
var timer = try std.time.Timer.start();
for (0..iterations) |_| {
const result = proven_header_has_crlf(input.ptr, input.len);
try requireCorrect(result, expected);
checksum += @intFromBool(result.value);
}
const elapsed = timer.read();
if (elapsed == 0) return error.TimerResolutionUnavailable;
var buffer = [_]u8{0} ** 1024;
const row = try std.fmt.bufPrint(&buffer,
"{{\"schema\":\"proven.header.benchmark/1\",\"backend\":\"actual-exported-refc-abi\",\"case\":\"{s}\",\"zig\":\"{s}\",\"mode\":\"{s}\",\"sample\":{d},\"bytes\":{d},\"iterations\":{d},\"warmup_iterations\":32,\"elapsed_ns\":{d},\"checksum\":{d},\"expected\":{},\"input_sha256\":\"{s}\",\"timed_correctness_guards\":true,\"correctness\":\"PASS\"}}\n",
.{ name, builtin.zig_version_string, @tagName(builtin.mode), sample, input.len, iterations, elapsed, checksum, expected, input_hash });
try std.fs.File.stdout().writeAll(row);
}
}

pub fn main() !void {
var input = [_]u8{'A'} ** 4096;
try sampleCase("empty", input[0..0], false, 4096);
try sampleCase("clean-byte", input[0..1], false, 4096);
try sampleCase("clean-64", input[0..64], false, 2048);
input[63] = 13;
try sampleCase("forbidden-64", input[0..64], true, 2048);
input[63] = 'A';
input[4095] = 10;
try sampleCase("forbidden-4096", &input, true, 256);
}
92 changes: 92 additions & 0 deletions docs/adr/2026-11-25-header-public-boundary.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: CC-BY-SA-4.0
// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
= Header public-entry spans and ownership premises
:revdate: 2026-11-25

== Contract and implementation

The actual public RefC root is `ffi/zig/src/main_refc.zig`. Its export delegates
to `core.headerHasCrlf` with `header_refc.zig` as the backend. The unavailable
root in `main.zig` is a separate profile. The production entry is unchanged:
null is refused with status -1 before creating a slice or invoking a backend;
a non-null pointer is forwarded as exactly `p[0..len]`. Success preserves the
backend Boolean, unavailable maps to -99, and other backend errors map to -7.
Every error result has value false. Backend errors also update thread-local
error storage, which is separate from the borrowed input in the contract.

`Proven.FFI.HeaderBoundary` defines a bounded logical span over an exact byte
snapshot. An erased proof requires `offset + count <= length memory`.
`spanLength` proves the selected list has exactly the requested count, and
`entryRefinesFold` composes the public-entry contract with the existing checked
Idris scan and authoritative ByteKernel fold. Null and both error classes have
explicit result laws. These are Idris2 ABI contracts, not runtime pointer checks.

== Native and source qualification

`scripts/test-header-boundary.sh` compiles a fixture importing the actual
`core.zig`. Its deterministic injected backend observes invocation count,
pointer identity, length and result/error forwarding. Every bounded subspan of
the fixture buffer is exercised, including empty slices and interior offsets.
Null tests include the maximum usize length; the null branch must refuse
without constructing a slice or calling the backend. No invalid non-null
pointer or out-of-bounds native span is dereferenced by the test.

Four private source mutants must compile and then fail executable assertions:
wrong slice extent, wrong null status, swapped backend-error statuses and an
extra backend invocation before null refusal. A malformed Idris span must
produce a type error. A zero-exit compiler-error control must invalidate a
planted PASS marker and finish with FAIL. Sources are snapshotted before work,
private copies are checked, and both manifests are rechecked before PASS.

The instrumented backend tests dispatch only. The existing header bridge and
borrow tests continue to link the real exported RefC-backed library, including
every bounded interior subspan of the caller's fixture buffer. All four
caller optimisation modes are checked remotely. Writing these files is not
evidence that the gate passed; the PR and hosted artifacts record qualification.
Atoma separately binds the original public-entry/export source to its heap and
source interpretation; neither test doubles nor hashes alone prove that link.

`scripts/test-header-export-controls.sh` additionally compiles three mutations
of the actual `main_refc.zig` exported forwarder: shortened extent, shifted
pointer with a correspondingly shortened extent, and skipped null refusal.
The real exported-ABI caller must reject each mutant with an assertion failure.
The shifted pointer remains within the valid caller allocation; no deliberately
invalid native address is dereferenced. These controls cover the export layer
that the injected core fixture cannot observe.

== Actual-library benchmark

`scripts/bench-header-boundary.sh LIBRARY_DIR` links the pure Zig benchmark
caller against the qualified real RefC-backed `libproven.so`. Five corpora
(empty, one byte, clean 64 bytes, forbidden byte at the end of 64 bytes and
4096 bytes) run in four caller optimisation modes. Each corpus has a correctness
check, 32 warmups and three bounded samples; timed calls retain correctness
guards. A compiled always-clean Zig export must fail the same caller's checks.

NDJSON evidence records input SHA-256, bytes, iterations, elapsed nanoseconds,
checksum, compiler and caller mode. The environment and actual library hash are
retained separately. All caller modes use the same qualified library binary.
These are initial timing samples, not a performance-regression threshold or
proof of the foreign boundary. CI host noise and the per-call guards affect
timings. The bridge gate retains the report under `header-evidence/benchmark`.

== Remaining premises

For a non-null request the caller supplies a live readable allocation, a span
within that allocation and a representable machine address/range. The pointer
must correspond to the stated logical region/snapshot, and the read lease must
remain valid and immutable throughout the synchronous backend call. The backend
must not retain the input or invalidate its storage. A non-null test does not
establish any of these facts. A logical constructor cannot make stale or forged
machine addresses safe. No ABI compatibility change is introduced here.

Atoma's backend frame premise states final region equality. It does not by
itself prohibit a write followed by restoration during the call. Continuous
immutability and no retention remain distinct foreign-call obligations. Its
thread-local error marker is an effect/presence projection, not the native
pointer identity or a message-storage layout theorem.

Atoma's heap model tracks retained references and active read borrows; release
is permitted only when both counts are zero. Connecting that model to physical
allocations, compiler lowering, foreign calls and cross-kernel proof transport
remains explicit work. Independent hand re-proofs remain BRIDGE-PENDING.
15 changes: 15 additions & 0 deletions ffi/zig/build_standalone.zig
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,19 @@ pub fn build(b: *std.Build) void {
const run_unit_tests = b.addRunArtifact(unit_tests);
const test_step = b.step("test", "Run proven_ffi unit tests");
test_step.dependOn(&run_unit_tests.step);

// Instrument the real public entry with a deterministic backend double.
// The existing test step above continues to qualify the actual RefC path.
const boundary_mod = b.createModule(.{
.root_source_file = b.path("src/header_boundary_tests.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
boundary_mod.addImport("lifecycle", lifecycle_mod);
const boundary_tests = b.addTest(.{ .root_module = boundary_mod });
b.step("header-boundary-test", "Check actual header entry dispatch and span forwarding")
.dependOn(&b.addRunArtifact(boundary_tests).step);
b.step("header-boundary-build", "Compile the public-entry fixture without running it")
.dependOn(&b.addInstallArtifact(boundary_tests, .{ .dest_sub_path = "header-boundary-tests" }).step);
}
104 changes: 104 additions & 0 deletions ffi/zig/src/header_boundary_tests.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
const std = @import("std");
const core = @import("core.zig");

// This double observes the actual public entry's dispatch. The separate real
// ABI fixtures still link the Idris backend; this is not a replacement for it.
const Probe = struct {
const Mode = enum { clean, found, unavailable, invalid };
var mode: Mode = .clean;
var calls: usize = 0;
var received: ?[*]const u8 = null;
var length: usize = 0;

fn reset(next: Mode) void {
mode = next;
calls = 0;
received = null;
length = 0;
}

pub fn detect(bytes: []const u8) error{ BackendUnavailable, InvalidRefcResult }!bool {
calls += 1;
received = bytes.ptr;
length = bytes.len;
return switch (mode) {
.clean => false,
.found => true,
.unavailable => error.BackendUnavailable,
.invalid => error.InvalidRefcResult,
};
}
};

test "header public boundary refuses null before invoking backend" {
for ([_]usize{ 0, 9, std.math.maxInt(usize) }) |len| {
Probe.reset(.found);
const result = core.headerHasCrlf(Probe, null, len);
try std.testing.expectEqual(@as(c_int, -1), result.status);
try std.testing.expectEqual(false, result.value);
try std.testing.expectEqual(@as(usize, 0), Probe.calls);
try std.testing.expectEqual(@as(?[*]const u8, null), Probe.received);
}
}

test "header public boundary forwards every bounded subspan once and preserves storage" {
var memory = [_]u8{ 255, 0, 13, 128, 10, 7 };
const before = memory;
for (0..memory.len + 1) |offset| {
for (offset..memory.len + 1) |end| {
const span = memory[offset..end];
for ([_]Probe.Mode{ .clean, .found }) |mode| {
Probe.reset(mode);
const result = core.headerHasCrlf(Probe, span.ptr, span.len);
Comment thread
hyperpolymath marked this conversation as resolved.
Resolved
try std.testing.expectEqual(@as(c_int, 0), result.status);
try std.testing.expectEqual(mode == .found, result.value);
try std.testing.expectEqual(@as(usize, 1), Probe.calls);
try std.testing.expectEqual(@as(?[*]const u8, span.ptr), Probe.received);
try std.testing.expectEqual(span.len, Probe.length);
try std.testing.expectEqualSlices(u8, &before, &memory);
}
}
}
}

test "header public boundary preserves error classes and rejects their Boolean" {
const memory = [_]u8{ 0, 255, 13 };
for ([_]Probe.Mode{ .unavailable, .invalid }) |mode| {
for ([_]usize{ 0, memory.len }) |len| {
Probe.reset(mode);
const result = core.headerHasCrlf(Probe, &memory, len);
const expected: c_int = if (mode == .unavailable) -99 else -7;
try std.testing.expectEqual(expected, result.status);
try std.testing.expectEqual(false, result.value);
try std.testing.expectEqual(@as(usize, 1), Probe.calls);
try std.testing.expectEqual(len, Probe.length);
}
}
}

// The exported C entries cannot take a backend double without linking either
// the Idris archive or the unavailable stub. Observe their forwarding instead:
// each exported entry must be exactly one delegation that passes its own
// `ptr` and `len` unchanged to the shared boundary, with no other statement.
fn entryBody(source: []const u8) error{EntryNotFound}![]const u8 {
const head = "pub export fn proven_header_has_crlf(ptr: ?[*]const u8, len: usize) callconv(.c)";
const start = std.mem.indexOf(u8, source, head) orelse return error.EntryNotFound;
const open = std.mem.indexOfPos(u8, source, start, "{") orelse return error.EntryNotFound;
const close = std.mem.indexOfPos(u8, source, open, "\n}") orelse return error.EntryNotFound;
return std.mem.trim(u8, source[open + 1 .. close], " \n");
}

test "exported header entries forward ptr and len unchanged in a single delegation" {
const standalone = try entryBody(@embedFile("main.zig"));
const refc = try entryBody(@embedFile("main_refc.zig"));
try std.testing.expectEqualStrings(
"return core.headerHasCrlf(@import(\"header_unavailable.zig\"), ptr, len);",
standalone,
);
try std.testing.expectEqualStrings(
"return core.headerHasCrlf(@import(\"header_refc.zig\"), ptr, len);",
refc,
);
}
70 changes: 70 additions & 0 deletions scripts/bench-header-boundary.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
set -euo pipefail
[[ $# == 1 && -f $1/libproven.so ]]
library=$(cd "$1" && pwd)
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out=${EVIDENCE_DIR:-"$root/build/header-evidence/benchmark"}
mkdir -p "$out"; out=$(cd "$out" && pwd)
echo INCOMPLETE > "$out/result.txt"
work=$(mktemp -d)
trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; tail -n 25 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT
zig=$(command -v "${ZIG:-zig}")
zig=$(cd "$(dirname "$zig")" && pwd)/$(basename "$zig")
idris=$(command -v "${IDRIS2:-idris2}")
idris=$(cd "$(dirname "$idris")" && pwd)/$(basename "$idris")
[[ $("$zig" version) == 0.15.2 ]]
[[ $("$idris" --version) == 'Idris 2, version 0.8.0-b6cbc25d5' ]]
sha256sum "$root/benchmarks/header_boundary.zig" "$root/scripts/bench-header-boundary.sh" \
"$library/libproven.so" > "$out/inputs.sha256"
cp "$root/benchmarks/header_boundary.zig" "$work/header_boundary.zig"
cp "$library/libproven.so" "$work/libproven.so"
cmp "$root/benchmarks/header_boundary.zig" "$work/header_boundary.zig"
cmp "$library/libproven.so" "$work/libproven.so"
sha256sum -c "$out/inputs.sha256" > "$out/snapshot-recheck.txt"
(cd "$work"; sha256sum header_boundary.zig libproven.so) > "$out/checked-inputs.sha256"
{
date -u '+UTC %Y-%m-%dT%H:%M:%SZ'
uname -a
"$zig" version
"$idris" --version
if command -v lscpu >/dev/null; then lscpu; fi
printf '%s\n' 'Caller modes vary; all use the same qualified library binary.' \
'Timings include per-call correctness guards. Samples only; no regression baseline or threshold.'
} > "$out/environment.txt"
for mode in Debug ReleaseSafe ReleaseFast ReleaseSmall; do
"$zig" build-exe "$work/header_boundary.zig" -lc -L "$work" -lproven -rpath "$work" \
-O "$mode" -femit-bin="$work/benchmark" > "$out/build-$mode.txt" 2>&1
timeout -k 5 60 "$work/benchmark" > "$out/$mode.jsonl" 2> "$out/run-$mode.txt"
jq -e -s --arg mode "$mode" '
length == 15 and all(.[];
.schema == "proven.header.benchmark/1" and .backend == "actual-exported-refc-abi" and
.mode == $mode and .zig == "0.15.2" and .correctness == "PASS" and
.timed_correctness_guards == true and .warmup_iterations == 32 and
.iterations > 0 and .elapsed_ns > 0 and (.sample >= 0 and .sample < 3) and
(.input_sha256 | test("^[0-9a-f]{64}$")) and
.checksum == (if .expected then .iterations else 0 end)) and
(group_by(.case) | length == 5 and all(.[]; length == 3 and ([.[].sample] | sort) == [0,1,2]))
' "$out/$mode.jsonl" > "$out/validate-$mode.txt"
done
# A compiled wrong exported implementation must fail correctness before its
# timing rows can be treated as a qualified benchmark. This is a Zig fixture.
cat > "$work/always-clean.zig" <<'ZIG'
const BoolResult = extern struct { status: c_int, value: bool };
export fn proven_header_has_crlf(_: ?[*]const u8, _: usize) callconv(.c) BoolResult {
return .{ .status = 0, .value = false };
}
ZIG
"$zig" build-obj "$work/always-clean.zig" -O ReleaseSafe -femit-bin="$work/always-clean.o" > "$out/build-control.txt" 2>&1
"$zig" build-exe "$work/header_boundary.zig" "$work/always-clean.o" -lc -O ReleaseSafe \
-femit-bin="$work/wrong-benchmark" > "$out/build-control-caller.txt" 2>&1
if timeout -k 5 60 "$work/wrong-benchmark" > "$out/reject-always-clean.txt" 2>&1; then
echo 'FAIL benchmark accepted incorrect library' >&2; exit 1
fi
grep -q 'WrongHeaderResult' "$out/reject-always-clean.txt"
(cd "$work"; sha256sum -c "$out/checked-inputs.sha256") > "$out/checked-input-recheck.txt"
sha256sum -c "$out/inputs.sha256" > "$out/input-recheck.txt"
cp "$work/header_boundary.zig" "$out/"
echo PASS > "$out/result.txt"
echo 'HEADER BENCHMARK PASS: correctness-guarded real library samples; no performance regression baseline claimed'
28 changes: 28 additions & 0 deletions scripts/test-header-boundary-controls.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0
# Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out=${EVIDENCE_DIR:-"$root/build/header-evidence/boundary-controls"}
mkdir -p "$out"; out=$(cd "$out" && pwd)
echo INCOMPLETE > "$out/result.txt"
work=$(mktemp -d)
trap 'status=$?; if ((status)); then echo FAIL > "$out/result.txt"; fi; rm -rf "$work"' EXIT
real_idris=$(command -v "${IDRIS2:-idris2}")
real_idris=$(cd "$(dirname "$real_idris")" && pwd)/$(basename "$real_idris")
cat > "$work/diagnostic-compiler" <<'SH'
#!/usr/bin/env bash
if [[ $1 == --version ]]; then exec "$REAL_IDRIS" "$@"; fi
printf 'Error: planted zero-exit boundary compiler failure\n'
exit 0
SH
chmod +x "$work/diagnostic-compiler"
mkdir -p "$out/refused"
echo PASS > "$out/refused/result.txt"
if REAL_IDRIS="$real_idris" IDRIS2="$work/diagnostic-compiler" EVIDENCE_DIR="$out/refused" \
bash "$root/scripts/test-header-boundary.sh" > "$out/reject-diagnostic.txt" 2>&1; then
echo 'FAIL: zero-exit boundary compiler diagnostic accepted' >&2; exit 1
fi
grep -q 'FAIL: boundary compiler diagnostics' "$out/reject-diagnostic.txt"
[[ $(cat "$out/refused/result.txt") == FAIL ]]
echo PASS > "$out/result.txt"
Loading
Loading