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
50 changes: 50 additions & 0 deletions docs/decisions/2026-11-25-registry-lifetimes.adoc
Original file line number Diff line number Diff line change
@@ -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.
25 changes: 25 additions & 0 deletions scripts/check-registry-lifetime-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/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"
75 changes: 75 additions & 0 deletions scripts/check-registry-lifetime.sh
Original file line number Diff line number Diff line change
@@ -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" <<IDRIS
module Bad$kind
import Abi.RegistryLifetime
%default total
bad : (f : (1 payload : resource) -> ()) -> (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

Check failure on line 53 in scripts/check-registry-lifetime.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=AaISG1-RWHdMt_glIOZK&open=AaISG1-RWHdMt_glIOZK&pullRequest=25
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'
2 changes: 2 additions & 0 deletions scripts/check-runtime-registry.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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'
164 changes: 164 additions & 0 deletions src/interface/Abi/RegistryLifetime.idr
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
-- SPDX-License-Identifier: MPL-2.0
-- Copyright (c) 2026 Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
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.
Loading
Loading