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
39 changes: 39 additions & 0 deletions docs/decisions/2026-11-25-wrapper-ownership.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: CC-BY-SA-4.0
= Registry wrapper ownership qualification

The ABI remains Idris2-owned and the runtime FFI/API remains pure Zig.
`Abi.RegistryOwnership` adds a linear usage protocol for an already-acquired
logical owner and a callback-frame premise. It does not establish acquisition,
unforgeability, pointer validity or foreign callers' compliance.
The lease's constructors are hidden and its generic resource payload is linear.
Acquisition consumes a supplied resource; it does not turn a copyable registry
value into an exclusive machine allocation. Release requires a consuming finalizer.

`check-registry-ownership.sh` checks the Idris module without holes, rejects
duplicated linear ownership, and executes the actual `registry.zig` wrapper in
four Zig optimisation modes. Fixtures cover exact callback/context identity,
invalid-span cleanup, callback error and out-of-range statuses, reentrant public
operation refusal and endpoint preservation. Compiled cleanup/context/span
mutations must fail these fixtures after compiling successfully. A separate
wrong-callback-pointer mutant must fail with the requested context unchanged;
the endpoints use distinct callback functions. Both direct duplication and
destruct-and-reconstruct duplication of the actual linear payload must reject.

A second fixture intentionally writes through a raw registry alias. The call
clears the busy flag on return but does not restore the endpoint removed by that
write. This expected counterexample demonstrates the necessity of the ownership
premise; it must never be counted as a passing arbitrary-alias safety test.

The owner must serialize access and keep the allocation live. Callback code and
context must stay valid while their registration may be called; unregister
before their lifetime ends. During invocation the input must remain readable
and immutable, the callback may modify only disjoint context, and it must return
normally. Busy refusal cannot validate an arbitrary or stale machine pointer.

Atoma's https://github.com/hyperpolymath/atoma/pull/33[companion source interpretation]
targets conditional call framing and remains under qualification. No checked
Atoma framing artifact or ownership of arbitrary foreign memory is claimed here.
Allocation failure,
stale-handle rejection, non-local exit, synchronization, compiler refinement and
cross-kernel statement correspondence remain separate obligations. No ABI change
or new checked-handle interface is introduced here.
25 changes: 25 additions & 0 deletions scripts/check-registry-ownership-controls.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out=${EVIDENCE_DIR:-"$root/build/runtime-registry-evidence/ownership-controls"}
mkdir -p "$out"; out=$(cd "$out" && pwd)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
hyperpolymath marked this conversation as resolved.
Resolved
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 compiler failure\n'
exit 0
SH
chmod +x "$work/diagnostic-compiler"
if REAL_IDRIS="$real_idris" IDRIS2="$work/diagnostic-compiler" EVIDENCE_DIR="$out/refused" \
bash "$root/scripts/check-registry-ownership.sh" > "$out/reject-diagnostic.txt" 2>&1; then
echo 'FAIL: zero-exit compiler diagnostic accepted' >&2; exit 1
fi
grep -q 'FAIL: ownership compiler diagnostics' "$out/reject-diagnostic.txt"
[[ $(cat "$out/refused/result.txt") == FAIL ]]
echo PASS > "$out/result.txt"
71 changes: 71 additions & 0 deletions scripts/check-registry-ownership.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0
set -euo pipefail
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out=${EVIDENCE_DIR:-"$root/build/runtime-registry-evidence/ownership"}
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 40 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT
idris=$(command -v "${IDRIS2:-idris2}")
idris=$(cd "$(dirname "$idris")" && pwd)/$(basename "$idris")
zig=$(command -v "${ZIG:-zig}")
zig=$(cd "$(dirname "$zig")" && pwd)/$(basename "$zig")
[[ $("$idris" --version) == 'Idris 2, version 0.8.0-b6cbc25d5' ]]
[[ $("$zig" version) == 0.15.2 ]]
mkdir -p "$work/ffi/src"
cp "$root/src/interface/ffi/src/"{registry,registry_state,protocol_tag}.zig "$work/ffi/src/"
cp "$root/src/interface/RegistryOwnershipTests.zig" "$work/"
cp -R "$root/src/interface/Abi" "$work/"
(cd "$work"; "$idris" --total -Werror --check Abi/RegistryOwnership.idr) > "$out/idris.txt" 2>&1
if grep -q '^Error:' "$out/idris.txt"; then echo 'FAIL: ownership compiler diagnostics' >&2; exit 1; fi
(cd "$work"; printf ':m\n:q\n' | "$idris" --no-banner Abi/RegistryOwnership.idr) > "$out/holes.txt" 2>&1
grep -q 'No holes' "$out/holes.txt"
if grep -q '^Error:' "$out/holes.txt"; then echo 'FAIL: ownership hole-check diagnostics' >&2; exit 1; fi
cat > "$work/BadLease.idr" <<'IDRIS'
module BadLease
import Abi.RegistryOwnership
%default total
duplicate : (1 owner : Lease endpoint Idle) -> (Lease endpoint Idle, Lease endpoint Idle)
duplicate owner = (owner, owner)
IDRIS
(cd "$work"; "$idris" --total -Werror --check BadLease.idr) > "$out/reject-duplicate.txt" 2>&1 || true
grep -q '^Error:' "$out/reject-duplicate.txt"
grep -Ei 'linear|multiplicity|more than once|non-linear' "$out/reject-duplicate.txt" >/dev/null
# The public module hides constructors. Also expose ONLY a private scratch copy
# to show the real linear payload rejects destruct-and-reconstruct duplication.
mkdir "$work/exposed"
cp -R "$work/Abi" "$work/exposed/"
sed 's/^export$/public export/' "$work/Abi/RegistryOwnership.idr" > "$work/exposed/Abi/RegistryOwnership.idr"
cat > "$work/exposed/BadReconstruct.idr" <<'IDRIS'
module BadReconstruct
import Abi.RegistryOwnership
%default total
duplicate : (1 owner : Lease resource Idle) -> (Lease resource Idle, Lease resource Idle)
duplicate (IdleLease payload) = (IdleLease payload, IdleLease payload)
IDRIS
(cd "$work/exposed"; "$idris" --total -Werror --check BadReconstruct.idr) > "$out/reject-reconstruct.txt" 2>&1 || true
grep -q '^Error:' "$out/reject-reconstruct.txt"
grep -Ei 'linear|multiplicity|more than once|non-linear' "$out/reject-reconstruct.txt" >/dev/null
grep -q 'BadReconstruct' "$out/reject-reconstruct.txt"
for mode in Debug ReleaseSafe ReleaseFast ReleaseSmall; do
"$zig" test "$work/RegistryOwnershipTests.zig" -lc -O "$mode" > "$out/native-$mode.txt" 2>&1
done
cp "$work/ffi/src/registry.zig" "$work/original.zig"
for mutant in cleanup context callback guard; do
case "$mutant" in

Check failure on line 56 in scripts/check-registry-ownership.sh

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Add a default case (*) to handle unexpected values.

See more on https://sonarcloud.io/project/issues?id=hyperpolymath_unified-api-adapter&issues=AaIRtc1yP1eH05h6QLHd&open=AaIRtc1yP1eH05h6QLHd&pullRequest=24
cleanup) sed '/defer registry\.\* = state.finish/d' "$work/original.zig" ;;
context) sed 's/endpoint.callback(endpoint.context, bytes, len)/endpoint.callback(null, bytes, len)/' "$work/original.zig" ;;
callback) sed 's/endpoint.callback(endpoint.context, bytes, len)/(registry.rest orelse return 11).callback(endpoint.context, bytes, len)/' "$work/original.zig" ;;
guard) sed '/if (bytes == null and len != 0) return 4;/d' "$work/original.zig" ;;
esac > "$work/ffi/src/registry.zig"
if cmp -s "$work/original.zig" "$work/ffi/src/registry.zig"; then echo 'FAIL: unchanged mutant' >&2; exit 1; fi
"$zig" test "$work/RegistryOwnershipTests.zig" -lc -O ReleaseSafe --test-no-exec -femit-bin="$work/mutant" > "$out/build-$mutant.txt" 2>&1
if "$work/mutant" > "$out/reject-$mutant.txt" 2>&1; then echo "FAIL $mutant escaped" >&2; exit 1; fi
grep -E 'TestUnexpectedResult|TestExpectedEqual' "$out/reject-$mutant.txt" >/dev/null
done
cp "$work/original.zig" "$work/ffi/src/registry.zig"
(cd "$work"; sha256sum Abi/*.idr ffi/src/*.zig RegistryOwnershipTests.zig) > "$out/inputs.sha256"
cp "$work/Abi/RegistryOwnership.idr" "$work/RegistryOwnershipTests.zig" "$out/"
echo PASS > "$out/result.txt"
echo 'OWNERSHIP PILOT PASS: linear protocol, normal-return fixtures, alias counterexample and compiled controls; pointer premises remain'
2 changes: 2 additions & 0 deletions scripts/check-runtime-registry.sh
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,6 @@ if "$work/caller" > "$evidence/mutant.csv" 2> "$evidence/mutant.log"; then
fi
echo PASS > "$evidence/result.txt"
EVIDENCE_DIR="$evidence/state" bash "$root/scripts/check-registry-state.sh"
EVIDENCE_DIR="$evidence/ownership" bash "$root/scripts/check-registry-ownership.sh"
EVIDENCE_DIR="$evidence/ownership-controls" bash "$root/scripts/check-registry-ownership-controls.sh"
echo 'PASS: real C ABI, Idris differential matrix, lifetime/refusal regressions and rejecting Zig mutant'
64 changes: 64 additions & 0 deletions src/interface/Abi/RegistryOwnership.idr
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
-- SPDX-License-Identifier: MPL-2.0
-- Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
module Abi.RegistryOwnership
import Abi.Registry
import Abi.RegistryState

%default total

||| Logical ownership protocol. It does not manufacture pointer validity or
||| establish that arbitrary foreign callers obey linearity.
public export
data Phase = Idle | Calling | Released

export
data Lease : Type -> Phase -> Type where
IdleLease : (1 payload : resource) -> Lease resource Idle
CallingLease : (1 payload : resource) -> Lease resource Calling
ReleasedLease : Lease resource Released

||| Acquisition consumes a supplied resource; it cannot establish that a
||| copyable value was an exclusive native allocation in the first place.
export
acquire : (1 payload : resource) -> Lease resource Idle
acquire payload = IdleLease payload

export
borrow : (1 owner : Lease resource Idle) -> Lease resource Calling
borrow (IdleLease entries) = CallingLease entries

export
returnBorrow : (1 call : Lease resource Calling) -> Lease resource Idle
returnBorrow (CallingLease entries) = IdleLease entries

export
release : ((1 payload : resource) -> ()) ->
(1 owner : Lease resource Idle) -> Lease resource Released
release destroy (IdleLease payload) = case destroy payload of
() => ReleasedLease

export
borrowReturnsOwner : (owner : Lease resource Idle) ->
returnBorrow (borrow owner) = owner
borrowReturnsOwner (IdleLease payload) = Refl

||| A normal callback may change its own disjoint context, but must preserve
||| both registry endpoints. This equality is a premise, not a runtime check.
public export
record CallbackFrame (before : Registry endpoint) where
constructor FramedReturn
after : Registry endpoint
preserved : after = before

public export
finishCurrent : State endpoint -> State endpoint
finishCurrent s = MkState (entries s) False

public export
callbackReturnRestores : (before : Registry endpoint) ->
(result : CallbackFrame before) ->
finishCurrent (MkState (after result) True) = MkState before False
callbackReturnRestores before (FramedReturn before Refl) = Refl

-- No transition releases a Calling lease: destroy is permitted only at Idle.
-- Raw aliases, concurrent calls and non-local exits remain external obligations.
77 changes: 77 additions & 0 deletions src/interface/RegistryOwnershipTests.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// 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 api = @import("ffi/src/registry.zig");
const Context = struct {
registry: *api.Registry,
calls: usize = 0,
status: c_int = 7,
observed_borrow: bool = false,
violate_frame: bool = false,
};
// The fixture retains the typed owner and checks the opaque identity passed by
// the real wrapper; no foreign pointer is cast or dereferenced by this harness.
var active_context: ?*Context = null;
var secondary_calls: usize = 0;
fn secondary_callback(_: ?*anyopaque, _: ?[*]const u8, _: usize) callconv(.c) c_int {
secondary_calls += 1;
return 3;
}
fn callback(raw: ?*anyopaque, bytes: ?[*]const u8, len: usize) callconv(.c) c_int {
const ctx = active_context orelse return 6;
if (raw != @as(?*anyopaque, ctx)) return 6;
ctx.calls += 1;
ctx.observed_borrow = ctx.registry.active and len == 3 and bytes != null;
if (bytes) |p| ctx.observed_borrow = ctx.observed_borrow and p[0] == 0 and p[1] == 13 and p[2] == 255;
// Only supported public operations here; neither may mutate a busy registry.
ctx.observed_borrow = ctx.observed_borrow and api.uaa_registry_unregister(ctx.registry, 9) == 6;
ctx.observed_borrow = ctx.observed_borrow and api.uaa_registry_register(ctx.registry, 9, callback, raw) == 6;
if (ctx.violate_frame) ctx.registry.rest = null;
return ctx.status;
}

test "actual wrapper restores idle and endpoint identities on all normal exits" {
const registry = api.uaa_registry_create() orelse return error.OutOfMemory;
defer _ = api.uaa_registry_destroy(registry);
var context = Context{ .registry = registry };
active_context = &context;
defer active_context = null;
secondary_calls = 0;
var other = Context{ .registry = registry };
const payload = [_]u8{ 0, 13, 255 };
try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_register(registry, 1, callback, &context));
try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_register(registry, 9, secondary_callback, &other));
const before = registry.*;
try std.testing.expectEqual(@as(c_int, 4), api.uaa_registry_call(registry, 1, null, 3));
Comment thread
hyperpolymath marked this conversation as resolved.
Resolved
try std.testing.expectEqual(@as(usize, 0), context.calls);
try std.testing.expectEqualDeep(before, registry.*);
for ([_]c_int{ -2147483648, -1, 0, 7, 11, 12, 2147483647 }) |status| {
context.status = status;
const expected: c_int = if (status >= 0 and status <= 11) status else 6;
try std.testing.expectEqual(expected, api.uaa_registry_call(registry, 1, &payload, payload.len));
try std.testing.expect(context.observed_borrow);
try std.testing.expectEqualDeep(before, registry.*);
}
try std.testing.expectEqual(@as(usize, 7), context.calls);
try std.testing.expectEqual(@as(usize, 0), other.calls);
try std.testing.expectEqual(@as(usize, 0), secondary_calls);
try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_unregister(registry, 1));
try std.testing.expectEqual(@as(c_int, 11), api.uaa_registry_call(registry, 1, &payload, payload.len));
}

test "raw alias counterexample demonstrates necessity of the callback frame premise" {
const registry = api.uaa_registry_create() orelse return error.OutOfMemory;
defer _ = api.uaa_registry_destroy(registry);
var context = Context{ .registry = registry, .violate_frame = true };
active_context = &context;
defer active_context = null;
const payload = [_]u8{ 0, 13, 255 };
try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_register(registry, 9, callback, &context));
try std.testing.expect(registry.rest != null);
try std.testing.expectEqual(@as(c_int, 7), api.uaa_registry_call(registry, 9, &payload, payload.len));
try std.testing.expect(context.observed_borrow);
try std.testing.expect(!registry.active);
// This is the EXPECTED counterexample, not an ownership safety pass.
try std.testing.expect(registry.rest == null);
try std.testing.expectEqual(@as(c_int, 11), api.uaa_registry_call(registry, 9, &payload, payload.len));
}
2 changes: 1 addition & 1 deletion src/interface/RegistryStateOracle.idr
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
module Main
import Abi.Registry
import Abi.RegistryState
import Abi.RegistryOwnership
import Abi.Status
%default total

Expand Down Expand Up @@ -51,4 +52,3 @@ main = do
putStrLn (render first ++ " " ++ render second)
for_ [-2147483648,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,256,2147483647] $ \z =>
putStrLn ("status " ++ show z ++ " " ++ show (statusTag (sanitize z)))

Loading