diff --git a/docs/decisions/2026-11-25-registry-lifetimes.adoc b/docs/decisions/2026-11-25-registry-lifetimes.adoc new file mode 100644 index 0000000..06190ba --- /dev/null +++ b/docs/decisions/2026-11-25-registry-lifetimes.adoc @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += Registry retention and synchronous input loans +:revdate: 2026-11-25 + +Successful registration stores callback/context identities until that slot is +unregistered or the idle registry is destroyed. The caller must keep both valid +through that interval. Input memory is borrowed only during a synchronous call. +Unregister and destroy do not own or free callback code or context storage. +Two installed slots sharing one context retain two references; removing one +does not make the remaining registration safe after the context is freed. + +`Abi.RegistryLifetime.Permit resource retained readers` records these obligations +in a hidden-constructor linear caller contract. Retain/dropRetention and +borrowRead/returnRead adjust separate counts. Release consumes a finalizer and a +permit with both counts zero. The Idris negative controls try to release a +retained or borrowed permit and must be rejected. The destroy decision mirrors +the actual idle/busy branches: busy destruction refuses; idle destruction +detaches every registration, including registrations not individually removed. + +`EndpointRegions` associates each callback and optional context with logical +region identities supplied by the boundary contract. Code/context retentions +are computed from the two actual `Abi.Registry` entries, including shared +regions. A theorem over `Abi.RegistryState.unregister` shows that detaching one +of two shared-context slots leaves one context retention. Idle destruction +clears both slots' retentions. Relating logical identities to native allocations +is a correspondence premise; pointer bits do not establish that association. + +The counts are ghost permissions. They are not fields or checks in the Zig ABI. +Acquiring a permit does not prove that a supplied pointer is live or exclusive, +and foreign callers can violate the contract. No stale pointer is passed to the +native fixture: checking arbitrary address bits by dereferencing them is unsafe. +The existing raw-alias counterexample remains part of ownership qualification. + +`RegistryLifetimeTests.zig` imports the actual registry implementation. It tests +shared-context registration, removal of one slot while the other remains +callable, busy destroy/call/register/unregister refusal, repeated detach refusal, +and caller-owned context survival after idle registry destruction. It runs in +four Zig modes. Three compiled mutations must fail for the intended assertions: +incorrect busy-destroy status, failure to detach, and destruction of the other +slot during detach. A zero-exit compiler-error control must also be rejected. +Inputs are hashed before copying, the private copies checked against that +manifest, and both copies/originals rechecked before PASS. + +The source-bound heap interpretation belongs to the companion Atoma change and +requires its own receipts. Valid registry allocation, serialized owner access, +correct allocator/compiler behaviour, readable immutable input, valid retained +callback/context and normal frame-preserving return remain explicit premises. +No ABI signature, calling convention or allocation API changes in this slice. +All new FFI/API fixtures use Zig; contracts remain Idris2. Hosted CI qualification +is required before acceptance; file presence is not a proof or a PWG promotion. diff --git a/scripts/check-registry-lifetime-controls.sh b/scripts/check-registry-lifetime-controls.sh new file mode 100644 index 0000000..be73212 --- /dev/null +++ b/scripts/check-registry-lifetime-controls.sh @@ -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/lifetime-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 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-lifetime.sh" > "$out/reject-diagnostic.txt" 2>&1; then + echo 'FAIL: zero-exit lifetime compiler diagnostic accepted' >&2; exit 1 +fi +grep -q 'FAIL: lifetime compiler diagnostics' "$out/reject-diagnostic.txt" +[[ $(cat "$out/refused/result.txt") == FAIL ]] +echo PASS > "$out/result.txt" diff --git a/scripts/check-registry-lifetime.sh b/scripts/check-registry-lifetime.sh new file mode 100644 index 0000000..309dadb --- /dev/null +++ b/scripts/check-registry-lifetime.sh @@ -0,0 +1,75 @@ +#!/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/lifetime"} +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 35 "$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 ]] +(cd "$root"; sha256sum src/interface/Abi/*.idr \ + src/interface/ffi/src/{registry,registry_state,protocol_tag}.zig \ + src/interface/RegistryLifetimeTests.zig scripts/check-registry-lifetime.sh) > "$out/inputs.sha256" +mkdir -p "$work/src/interface/ffi/src" "$work/scripts" +cp -R "$root/src/interface/Abi" "$work/src/interface/" +cp "$root/src/interface/ffi/src/"{registry,registry_state,protocol_tag}.zig "$work/src/interface/ffi/src/" +cp "$root/src/interface/RegistryLifetimeTests.zig" "$work/src/interface/" +cp "$root/scripts/check-registry-lifetime.sh" "$work/scripts/" +(cd "$work"; sha256sum -c "$out/inputs.sha256") > "$out/snapshot-recheck.txt" +interface="$work/src/interface" +(cd "$interface"; "$idris" --total -Werror --check Abi/RegistryLifetime.idr) > "$out/idris.txt" 2>&1 +if grep -q '^Error:' "$out/idris.txt"; then echo 'FAIL: lifetime compiler diagnostics' >&2; exit 1; fi +(cd "$interface"; printf ':m\n:q\n' | "$idris" --no-banner Abi/RegistryLifetime.idr) > "$out/holes.txt" 2>&1 +grep -q 'No holes' "$out/holes.txt" +if grep -q '^Error:' "$out/holes.txt"; then echo 'FAIL: lifetime hole-check diagnostics' >&2; exit 1; fi +for kind in Retained Borrowed; do + counts='1 0'; [[ $kind != Borrowed ]] || counts='0 1' + cat > "$interface/Bad$kind.idr" < ()) -> (1 permit : Permit resource $counts) -> () +bad f permit = release f permit +IDRIS + (cd "$interface"; "$idris" --total -Werror --check "Bad$kind.idr") > "$out/reject-$kind.txt" 2>&1 || true + grep -q '^Error:' "$out/reject-$kind.txt" + grep -q 'Mismatch between' "$out/reject-$kind.txt" + grep -q "Bad$kind" "$out/reject-$kind.txt" +done +for mode in Debug ReleaseSafe ReleaseFast ReleaseSmall; do + "$zig" test "$interface/RegistryLifetimeTests.zig" -lc -O "$mode" > "$out/native-$mode.txt" 2>&1 +done +cp "$interface/ffi/src/registry.zig" "$work/registry-original.zig" +cp "$interface/ffi/src/registry_state.zig" "$work/state-original.zig" +for mutant in busy-destroy detach preserve-other; do + cp "$work/registry-original.zig" "$interface/ffi/src/registry.zig" + cp "$work/state-original.zig" "$interface/ffi/src/registry_state.zig" + case "$mutant" in + busy-destroy) + awk '/pub export fn uaa_registry_destroy/{inside=1} inside && /if \(registry.active\) return 6;/{sub("return 6;", "return 0;"); inside=0} {print}' \ + "$work/registry-original.zig" > "$interface/ffi/src/registry.zig" + if cmp -s "$work/registry-original.zig" "$interface/ffi/src/registry.zig"; then exit 1; fi ;; + detach) + sed 's/\.next = put(E, s, slot, null)/.next = s/' "$work/state-original.zig" > "$interface/ffi/src/registry_state.zig" + if cmp -s "$work/state-original.zig" "$interface/ffi/src/registry_state.zig"; then exit 1; fi ;; + preserve-other) + sed 's/\.next = put(E, s, slot, null)/.next = .{}/' "$work/state-original.zig" > "$interface/ffi/src/registry_state.zig" + if cmp -s "$work/state-original.zig" "$interface/ffi/src/registry_state.zig"; then exit 1; fi ;; + esac + "$zig" test "$interface/RegistryLifetimeTests.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/registry-original.zig" "$interface/ffi/src/registry.zig" +cp "$work/state-original.zig" "$interface/ffi/src/registry_state.zig" +(cd "$work"; sha256sum -c "$out/inputs.sha256") > "$out/checked-input-recheck.txt" +(cd "$root"; sha256sum -c "$out/inputs.sha256") > "$out/input-recheck.txt" +cp "$interface/RegistryLifetimeTests.zig" "$interface/Abi/RegistryLifetime.idr" "$out/" +echo PASS > "$out/result.txt" +echo 'LIFETIME PILOT PASS: retained/read permission refusals and actual native lifecycle; caller pointer/lifetime premises remain' diff --git a/scripts/check-runtime-registry.sh b/scripts/check-runtime-registry.sh index 6fcfed1..1136990 100644 --- a/scripts/check-runtime-registry.sh +++ b/scripts/check-runtime-registry.sh @@ -57,4 +57,6 @@ 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" +EVIDENCE_DIR="$evidence/lifetime" bash "$root/scripts/check-registry-lifetime.sh" +EVIDENCE_DIR="$evidence/lifetime-controls" bash "$root/scripts/check-registry-lifetime-controls.sh" echo 'PASS: real C ABI, Idris differential matrix, lifetime/refusal regressions and rejecting Zig mutant' diff --git a/src/interface/Abi/RegistryLifetime.idr b/src/interface/Abi/RegistryLifetime.idr new file mode 100644 index 0000000..a6debb8 --- /dev/null +++ b/src/interface/Abi/RegistryLifetime.idr @@ -0,0 +1,164 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell +module Abi.RegistryLifetime +import Abi.Registry +import Abi.RegistryState +import Abi.Status + +%default total + +||| Logical region identities supplied by the boundary correspondence contract. +||| They are not computed by casting or inspecting native pointer bits. +public export +record EndpointRegions where + constructor Regions + codeRegion : Nat + contextRegion : Maybe Nat + +public export +sameRegion : Nat -> Nat -> Bool +sameRegion Z Z = True +sameRegion (S a) (S b) = sameRegion a b +sameRegion _ _ = False + +sameRegionSelf : (region : Nat) -> sameRegion region region = True +sameRegionSelf Z = Refl +sameRegionSelf (S region) = sameRegionSelf region + +public export +contextRefs : Nat -> Maybe EndpointRegions -> Nat +contextRefs region Nothing = 0 +contextRefs region (Just (Regions _ Nothing)) = 0 +contextRefs region (Just (Regions _ (Just target))) = + if sameRegion region target then 1 else 0 + +public export +codeRefs : Nat -> Maybe EndpointRegions -> Nat +codeRefs region Nothing = 0 +codeRefs region (Just endpoint) = + if sameRegion region (codeRegion endpoint) then 1 else 0 + +public export +contextRetentions : Nat -> Registry EndpointRegions -> Nat +contextRetentions region r = + contextRefs region (restEndpoint r) + contextRefs region (mcpEndpoint r) + +public export +codeRetentions : Nat -> Registry EndpointRegions -> Nat +codeRetentions region r = + codeRefs region (restEndpoint r) + codeRefs region (mcpEndpoint r) + +public export +retentions : Nat -> Registry EndpointRegions -> Nat +retentions region r = codeRetentions region r + contextRetentions region r + +public export +sharedContext : Nat -> Nat -> Nat -> Registry EndpointRegions +sharedContext firstCode secondCode context = + MkRegistry (Just (Regions firstCode (Just context))) + (Just (Regions secondCode (Just context))) + +public export +sharedContextHasTwoRetentions : (firstCode, secondCode, context : Nat) -> + contextRetentions context (sharedContext firstCode secondCode context) = 2 +sharedContextHasTwoRetentions firstCode secondCode context = + rewrite sameRegionSelf context in Refl + +||| This uses the existing actual-state ABI transition, not a separate detach +||| model. Removing REST must leave the MCP registration's context retention. +public export +detachOneKeepsSharedContext : (firstCode, secondCode, context : Nat) -> + contextRetentions context + (entries (next (unregister RESTSlot + (MkState (sharedContext firstCode secondCode context) False)))) = 1 +detachOneKeepsSharedContext firstCode secondCode context = + rewrite sameRegionSelf context in Refl + +||| Caller-side permission ledger. The indices count retained registrations and +||| transient readers of a supplied resource; they are not stored by the Zig ABI. +||| Acquisition cannot establish that a copyable pointer is exclusive or live. +export +data Permit : Type -> Nat -> Nat -> Type where + Own : (1 payload : resource) -> Permit resource retained readers + +export +acquire : (1 payload : resource) -> Permit resource 0 0 +acquire payload = Own payload + +export +retain : (1 permit : Permit resource retained readers) -> + Permit resource (S retained) readers +retain (Own payload) = Own payload + +export +dropRetention : (1 permit : Permit resource (S retained) readers) -> + Permit resource retained readers +dropRetention (Own payload) = Own payload + +export +borrowRead : (1 permit : Permit resource retained readers) -> + Permit resource retained (S readers) +borrowRead (Own payload) = Own payload + +export +returnRead : (1 permit : Permit resource retained (S readers)) -> + Permit resource retained readers +returnRead (Own payload) = Own payload + +export +release : ((1 payload : resource) -> ()) -> + (1 permit : Permit resource 0 0) -> () +release destroy (Own payload) = destroy payload + +export +retainDropRestores : (permit : Permit resource retained readers) -> + dropRetention (retain permit) = permit +retainDropRestores (Own payload) = Refl + +export +borrowReturnRestores : (permit : Permit resource retained readers) -> + returnRead (borrowRead permit) = permit +borrowReturnRestores (Own payload) = Refl + +||| Native destroy frees the registry allocation only, on an idle live pointer. +||| Destroyed means its registrations are detached, not that their resources +||| were freed. Valid-pointer, allocator and caller-serialization premises remain. +public export +data DestroyResult : Type -> Type where + Refused : Status -> Maybe (State endpoint) -> DestroyResult endpoint + Destroyed : DestroyResult endpoint + +public export +destroyRegistry : Maybe (State endpoint) -> DestroyResult endpoint +destroyRegistry Nothing = Refused NullPointer Nothing +destroyRegistry (Just (MkState entries True)) = + Refused ProcessFailed (Just (MkState entries True)) +destroyRegistry (Just (MkState entries False)) = Destroyed + +public export +retainedAfter : DestroyResult endpoint -> Registry endpoint +retainedAfter (Refused _ Nothing) = emptyRegistry +retainedAfter (Refused _ (Just state)) = entries state +retainedAfter Destroyed = emptyRegistry + +public export +busyDestroyRefuses : (r : Registry endpoint) -> + destroyRegistry (Just (MkState r True)) = + Refused ProcessFailed (Just (MkState r True)) +busyDestroyRefuses r = Refl + +public export +idleDestroyDetaches : (r : Registry endpoint) -> + retainedAfter (destroyRegistry (Just (MkState r False))) = Abi.Registry.emptyRegistry +idleDestroyDetaches r = Refl + +public export +idleDestroyClearsRetentions : (region : Nat) -> (r : Registry EndpointRegions) -> + retentions region (retainedAfter (destroyRegistry (Just (MkState r False)))) = 0 +idleDestroyClearsRetentions region r = Refl + +-- A shared callback/context registered in two slots needs two retentions. +-- Unregister drops one; idle destroy drops every remaining registration. +-- Transient input borrowing adds readers independently. The caller must apply +-- these transitions consistently with native successes; raw callers can violate +-- the ledger, so it is not a dynamic stale-pointer or lifetime validator. diff --git a/src/interface/RegistryLifetimeTests.zig b/src/interface/RegistryLifetimeTests.zig new file mode 100644 index 0000000..0dec37f --- /dev/null +++ b/src/interface/RegistryLifetimeTests.zig @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell +const std = @import("std"); +const api = @import("ffi/src/registry.zig"); + +const Context = struct { + registry: *api.Registry, + calls: usize = 0, + refusals_ok: bool = true, +}; +var current: ?*Context = null; +var callback_entries: usize = 0; + +fn callback(raw: ?*anyopaque, bytes: ?[*]const u8, len: usize) callconv(.c) c_int { + callback_entries += 1; + const context = current orelse return 6; + if (raw != @as(?*anyopaque, context)) return 6; + const input = bytes orelse return 4; + if (len != 2) return 4; + if (input[0] != 11 or input[1] != 22) return 4; + context.calls += 1; + context.refusals_ok = context.refusals_ok and api.uaa_registry_destroy(context.registry) == 6; + context.refusals_ok = context.refusals_ok and api.uaa_registry_call(context.registry, 9, bytes, len) == 6; + context.refusals_ok = context.refusals_ok and api.uaa_registry_unregister(context.registry, 9) == 6; + context.refusals_ok = context.refusals_ok and api.uaa_registry_register(context.registry, 9, callback, raw) == 6; + return 0; +} + +test "shared context stays retained until each registration is detached" { + var owner: ?*api.Registry = api.uaa_registry_create() orelse return error.OutOfMemory; + defer { if (owner) |registry| { _ = api.uaa_registry_destroy(registry); } } + const registry = owner.?; + const context = try std.testing.allocator.create(Context); + defer std.testing.allocator.destroy(context); + context.* = .{ .registry = registry }; + current = context; + callback_entries = 0; + defer current = null; + const input = [_]u8{ 11, 22 }; + 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, callback, context)); + try std.testing.expectEqual(@as(c_int, 9), api.uaa_registry_register(registry, 9, callback, context)); + try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_call(registry, 1, &input, input.len)); + try std.testing.expect(context.refusals_ok); + try std.testing.expect(!registry.active); + 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, &input, input.len)); + // The other registration still retains the same caller-owned context. + try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_call(registry, 9, &input, input.len)); + try std.testing.expectEqual(@as(usize, 2), context.calls); + try std.testing.expectEqual(@as(usize, 2), callback_entries); + try std.testing.expect(context.refusals_ok); + try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_unregister(registry, 9)); + try std.testing.expectEqual(@as(c_int, 8), api.uaa_registry_unregister(registry, 9)); + try std.testing.expectEqual(@as(c_int, 11), api.uaa_registry_call(registry, 9, &input, input.len)); + try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_destroy(registry)); + owner = null; + // Destroying the registry did not destroy the caller's context allocation. + context.calls += 1; + try std.testing.expectEqual(@as(usize, 3), context.calls); +} + +test "idle destroy detaches installed endpoints without destroying context" { + var owner: ?*api.Registry = api.uaa_registry_create() orelse return error.OutOfMemory; + defer { if (owner) |registry| { _ = api.uaa_registry_destroy(registry); } } + const registry = owner.?; + const context = try std.testing.allocator.create(Context); + defer std.testing.allocator.destroy(context); + context.* = .{ .registry = registry }; + current = context; + callback_entries = 0; + defer current = null; + 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, callback, context)); + try std.testing.expectEqual(@as(c_int, 0), api.uaa_registry_destroy(registry)); + owner = null; + try std.testing.expectEqual(@as(usize, 0), callback_entries); + context.calls = 17; + try std.testing.expectEqual(@as(usize, 17), context.calls); + try std.testing.expectEqual(@as(c_int, 4), api.uaa_registry_destroy(null)); + // No stale pointer is used; the ABI cannot safely validate arbitrary bits. +} diff --git a/src/interface/ffi/src/registry.zig b/src/interface/ffi/src/registry.zig index dbaf20f..6aeab91 100644 --- a/src/interface/ffi/src/registry.zig +++ b/src/interface/ffi/src/registry.zig @@ -10,8 +10,10 @@ pub const Callback = *const fn (?*anyopaque, ?[*]const u8, usize) callconv(.c) c const Endpoint = struct { callback: Callback, context: ?*anyopaque }; pub const Registry = state.State(Endpoint); -// All calls on one live registry must be serialized by its owner. Callback -// code/context and input remain borrowed for the synchronous call only. +// All calls on one live registry must be serialized by its owner. Registered +// callback code/context must remain valid until that registration is removed +// or the registry is destroyed. Input is borrowed for the synchronous call only. +// Destroy/unregister do not free callback/context storage owned by the caller. pub export fn uaa_registry_create() ?*Registry { const r = std.heap.c_allocator.create(Registry) catch return null; r.* = .{};