From 0b1cd29e783c1cbe10a259dd88bbe4622270ce1c Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 5 Oct 2026 14:20:39 -0500 Subject: [PATCH 1/6] R16 G6: operator control interface contract (before code) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit How the operator's enrolled credential and the RX_WORLD_RES_CONTROL capability reach the running production program, the owner-only Unix socket entry point (SO_PEERCRED plus credential), request and reply formats, command semantics, revocation and per-start rotation, the validated state directory, restart while stopped before any work, and the stop's boundary (spec §7.4). Co-Authored-By: Claude Opus 5.5 --- docs/r16-operator-control.md | 190 +++++++++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 docs/r16-operator-control.md diff --git a/docs/r16-operator-control.md b/docs/r16-operator-control.md new file mode 100644 index 000000000..3926afab7 --- /dev/null +++ b/docs/r16-operator-control.md @@ -0,0 +1,190 @@ +# R16 G6: operator control of the production program (interface contract) + +Status: CONTRACT, written before the code (lane ESTOP, CAND-3). The runtime control it +wires is `spec/r16-operator-emergency-stop.md` (merged #300); this document says how an +operator outside the running production program reaches that control, and what the +program does with a request. It adds no authority scheme: every decision is made by the +existing world authority (`rx_world_emergency_stop` / `_resume`, `halt_authorize` in +`src/runtime/rx_world.c`). + +Production program: `tests/runtime/rx_r13_living.c`, built without `AIEN_TEST_BUILD` as +`build/rx_r13_living_host` and `build/rx_r13_living_silicon`. It runs six modes, each in +its own world. Every statement below holds for each of those worlds. + +## 1. Who the operator is and how its authority reaches the program + +* One operator subject, `RX_OPERATOR_SUBJ` (70), not used by any faculty, reaction or + composition subject (`rx_living.h` 61-64, `rx_omega.h` 21-22, `rx_aien.h` 31, + `rx_aegis.h` 41-42, `rx_compose.h` 200+). +* **Credential.** At each world start, with the other production subjects and before + enrollment closes (`rx_living_enroll_callers`, then `rx_world_bind_callers`), the + program enrolls the operator with `rx_world_enroll_caller`: a fresh 32-byte random + secret and a generation, issued by the runtime. The program keeps no copy after + handing it over (below) and wipes its buffer. +* **Capability.** The program mints, through the native AIENOS authority it already + starts (`aienos_cap_start`, the same `mint()` path every production grant uses), one + capability for `RX_OPERATOR_SUBJ` on `RX_WORLD_RES_CONTROL` (0x906) with + `RX_WORLD_RIGHT_HALT` (`RX_RIGHT_EPOCH`: privileged, never delegable). No other + subject is minted anything on that resource; the program's authority sweep fails the + run if any live capability on it belongs to another subject or carries another right. +* **Hand-over.** Both are written to the operator credential file + `/control/operator.cred` (format §3), created mode 0600 in a 0700 directory + owned by the program's user, written to a temporary file, fsynced and renamed. It is + the operator's copy; the world holds only the credential digest and the authority + holds the capability. Anyone who can read the file is, by construction, the operator + account (the program's own uid, or root). +* **No editable boolean grants authority.** The file carries a credential the world + checks in constant time and a capability reference the authority validates; editing + either makes it fail. Nothing in the file, the socket, the environment or the command + line switches a check off. +* **A reaction subject can never control the world.** The world refuses any subject + that a registered reaction runs under (`halt_authorize`, spec §2 point 2). The + operator subject runs no reaction. The program's own reaction credentials never leave + the program, so they cannot be presented from outside; that refusal is proven + in-process by `make test-rx-emergency` (E1) and is not re-proven from outside. + +## 2. The outside entry point + +* An `AF_UNIX` stream socket `/control/operator.sock`, created when the world is + ready for operator requests and removed when the world is torn down. Between worlds + there is no socket: a client gets "connection refused" and the request does nothing. +* Two walls before the credential: the directory is 0700 and owned by the program's + user (validated at startup, §5), and every accepted connection is checked with + `SO_PEERCRED`: the peer uid must equal the program's effective uid, else the reply + is `REFUSED reason=peer` and nothing is read further. Root can pass the directory but + not the peer check. +* One request per connection, read with a 2 s receive timeout; at most 511 bytes up to + the first newline. One reply line, then the connection is closed. Requests are served + one at a time by one listener thread (`src/runtime/rx_operator.c`); it never holds the + world lock across a request. +* Client: `build/rx_operator` (`tools/rx_operator.c`). It reads the credential file and + sends one request: `rx_operator --control /control [reason]`, or + `--cred ` to present another file (used by the tests for stale and forged + credentials), or `--raw ` (malformed-request tests). + +## 3. Formats + +Credential file (text): + +``` +aien-operator-credential v1 +world +socket +subject 70 +cred <64 hex secret> +cap +``` + +Request (one line): + +``` +aien-operator v1 subject= gen= secret=<64 hex> cap=: [reason=] +``` + +`` is `status`, `stop`, `resume`, `revoke-cap`, `revoke` or `shutdown`. Any other +token, a missing or repeated field, a secret that is not 64 hex digits, a number out of +range or extra bytes is `BAD_REQUEST`, decided before any world call. + +Reply (one line): `aien-operator v1 key=value ...`. RESULT is one of `OK`, +`ALREADY` (stop of a stopped world), `NOT_STOPPED` (resume or shutdown of a running world), +`REFUSED reason=peer|identity|authority`, `BAD_REQUEST`, `ERROR rc=`. +A refusal says nothing about the world: no state, no counters. + +## 4. Commands + +Every command except `BAD_REQUEST` cases goes to the world authority first. `status`, +`revoke-cap`, `revoke` and `shutdown` are checked by `rx_world_operator_authorize` (the +same `halt_authorize` the stop and resume use, under the same locks, added to +`rx_world.c` so no second authority check exists). `stop` and `resume` are checked inside +`rx_world_emergency_stop` / `_resume` themselves. + +| command | world call | reply on success | +|---|---|---| +| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= crumbs= objects=` plus program counters `served= production_commits= inforce= active_generation=` | +| `stop [reason]` | `rx_world_emergency_stop` | `OK state=stopped seq= crumb= durable=`; a second stop: `ALREADY` with no new crumb | +| `resume` | `rx_world_emergency_resume` | `OK state=running seq=`; a running world: `NOT_STOPPED` | +| `revoke-cap` | authorize, then `aienos_cap_revoke` of the presented control capability by the authority's office | `OK revoked=capability`; afterwards every request with that capability is `REFUSED reason=authority` | +| `revoke` | authorize, then `aienos_cap_revoke` (capability) and `rx_world_revoke_caller` (credential); the credential file is removed | `OK revoked=capability,credential`; afterwards `REFUSED reason=identity` | +| `shutdown` | authorize; only while stopped | `OK state=stopped shutdown=1`; the program ends the current mode, tears the world down with the stop still in force, writes no R13 receipt and exits 3. The durable mark stays. | + +A revoked operator cannot be re-enrolled in the same world (enrollment is closed); the +world keeps running without operator control until the program starts the next world, +which issues a new credential and capability. Revoking while stopped leaves the world +stopped for the rest of that world's life; the durable mark makes the next start of that +mode come up stopped, and the next credential can resume it. + +**Stale credentials.** A credential is valid for one world of one program start: every +world start enrolls a new random secret and mints a new capability. A credential from an +earlier world or an earlier program start fails the constant-time caller check +(`REFUSED reason=identity`). + +## 5. State directory, durability and restart + +* `--state-dir ` names the program's durable state (default: a fresh 0700 scratch + directory under `$TMPDIR`, as before, so `make test-r13-host` keeps running unchanged). + Layout: `/control/` (credential file and socket) and one generation store per mode, + `/gen-/` (`positive`, `no-aien`, `no-promotion`, `revoked-experiment`, + `stale-gpu`, `failed-verification`). +* **Validated at startup, refuse if wrong.** `` and each subdirectory must be a real + directory (checked with `lstat`, a symlink is refused), owned by the effective uid, with + no group or other permission bits (`mode & 077 == 0`). A missing subdirectory is + created 0700. A path too long for a socket address is refused. On any refusal the + program prints the reason and exits 2 before any world starts. +* **The durable halt directory is the generation store's directory**: + `rx_world_set_halt_dir(w, /gen-)`, called right after the store is opened + and bound and **before any object is created or any work is published**. A mark there + (`OPERATOR_HALT`, sealed) makes the world start stopped (spec §4: a torn or unreadable + mark also stops it). The program then serves operator requests on the socket and does + nothing else until a resume (or `shutdown`); only then does it build the world's + objects and run. So a restart while stopped restores the stop before it accepts any + work, including its own setup. +* Resume keeps the sealed resumed record `OPERATOR_HALT.resumed..` and only + then removes the mark (spec §4, unchanged). +* Directory protection beyond these checks (another process of the same uid deleting the + mark while no program runs) is the operating system's job (spec §7.3). + +## 6. What a stop covers, and what it does not + +* It stops the world's publications and promotions, exactly as spec §3 lists: no commit, + no outside publication (the production request stream included), no seat result, no + object create or retire, no generation proposal or promotion. In-flight activations + are refused at commit and run again on resume. +* The program keeps its own clocks honest: time spent stopped does not count toward the + episode's deadlines (`run_clock`), a production request refused by the stop is + published again after resume, and the end-of-mode checks wait while the world is + stopped. A stop therefore delays the episode; it does not fail it. +* Evidence: at the end of every mode the program reads its crumb log (the canonical + evidence, spec §4) and prints `R13 operator : stops S resumes R restored X + open O; under stop: commits 0 externals 0 cancelled C`. Any COMMIT or EXTERNAL crumb + between an OPERATOR_STOP and its OPERATOR_RESUME (or after an unresumed stop) fails the + mode. The R13 receipt carries the totals under `"operator"`. +* **Outside effects already underway (spec §7.4).** A stop does not reach a durable + executor already performing an effect outside the world, and it does not interrupt a + GPU kernel already running on the resident seat. The production program has one + outside effect path, the resident seat: a seat result that lands under a stop is + refused and the output window re-projected from the world (spec §3, R12 + `t_emergency_stop`); the kernel's work is discarded and runs again on resume. A stop + does not stop the process, its threads, ARGUS observation or the authority; it is not a + kill switch and not a rollback. + +## 7. Proof (G6 by execution) + +`make test-r16-operator-host` (`tests/runtime/rx_operator_host.sh`) starts the production +host binary and drives it only through `build/rx_operator` and signals, checking replies, +the files in the state directory and the program's crumb-log audit lines: authorized stop +and resume; forged secret, wrong capability, wrong peer (root via `sudo -n`, reported +SKIPPED and therefore NOT_RUN if sudo is unavailable), malformed request; stale +credential (earlier world, earlier program start); `revoke-cap` and `revoke`; repeated +stop and resume; repeated stop and resume cycles under production load (in-flight work +refused and re-run); promotion blocked while stopped and completed after resume; restart +while stopped after `shutdown` and after `SIGKILL`; recovery to a passing R13 episode; +startup refusal of a group-readable, foreign-owned or symlinked state directory. +`tests/runtime/rx_operator_mutants.sh` rebuilds the production program from mutated +copies and requires the test to fail against each (wiring missing, handler disconnected, +success reply without a state transition, unauthorized resume accepted, wiring present +only in a comment, wiring present only as an unused call, and the others it lists). +`make test-r16-operator-silicon` runs the same test on `build/rx_r13_living_silicon` +(resident GB10 seat) without the SIGKILL phase (a chip program is never killed). The +receipt labels host and silicon results separately. The G6 item +`operator_emergency_controls_passing` is PASS only when both ran and passed in the same +qualification run on the candidate. From daaef795c427e377961f84016b60ba85eb9ab4c0 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 5 Oct 2026 15:42:23 -0500 Subject: [PATCH 2/6] R16 G6: operator control of the production program, proven by execution The production R13 program (host and silicon builds, no AIEN_TEST_BUILD) now wires the runtime emergency stop and exposes one outside entry point, as the contract in docs/r16-operator-control.md says: - operator subject 70, enrolled with the production subjects before enrollment closes; a fresh RX_WORLD_RES_CONTROL capability with the halt right minted per world start through the native AIENOS authority; both handed over in a 0600 credential file, never kept by the program - owner-only AF_UNIX socket (src/runtime/rx_operator.c, SO_PEERCRED uid check), strict one-line requests, client build/rx_operator (tools/rx_operator.c): status, stop, resume, revoke-cap, revoke, shutdown - --state-dir, validated at startup (lstat, owner, no group/other bits); each mode's generation store directory is its durable halt directory, set before any object exists; a restart while stopped restores the stop and does no work until an operator resume - rx_world_operator_authorize: the same halt_authorize, for the non-stop commands - the program audits its crumb log per mode: no COMMIT or EXTERNAL between an OPERATOR_STOP and its OPERATOR_RESUME; stopped time does not count toward the episode deadlines Bug found by the new test and fixed: a durable promotion or proposal the store refused because of a stop (RX_GEN_ERR_HALTED) was recorded as the final outcome, so the positive episode never promoted after a resume. rx_living.c now defers and re-runs it after the resume (halted_wait). G6 by execution: make test-r16-operator-host drives the production program from outside (63 checks); make test-r16-operator-mutants rebuilds it from 14 mutated copies (wiring missing, wiring in a comment, unused call, handler disconnected, OK without a transition, unauthorized resume accepted, ...) and requires the test to fail on each; make test-r16-operator-silicon runs the same test on the resident seat. tools/r16_qualify.sh drops the string-presence check: the operator item needs all three, host and silicon labelled apart. Self-test fixtures updated with counterexamples. Co-Authored-By: Claude Opus 5.5 --- Makefile | 27 +- docs/r16-operator-control.md | 21 +- docs/r16-production-entry-point.md | 14 + spec/r16-operator-emergency-stop.md | 39 ++- src/runtime/rx_living.c | 24 +- src/runtime/rx_operator.c | 396 +++++++++++++++++++++++++++ src/runtime/rx_operator.h | 54 ++++ src/runtime/rx_world.c | 10 + src/runtime/rx_world.h | 5 + tests/r16_qualify/run.sh | 64 ++++- tests/runtime/rx_operator_host.sh | 342 +++++++++++++++++++++++ tests/runtime/rx_operator_mutants.sh | 79 ++++++ tests/runtime/rx_r13_living.c | 314 +++++++++++++++++++-- tools/r16_qualify.sh | 14 +- tools/rx_operator.c | 107 ++++++++ 15 files changed, 1447 insertions(+), 63 deletions(-) create mode 100644 src/runtime/rx_operator.c create mode 100644 src/runtime/rx_operator.h create mode 100644 tests/runtime/rx_operator_host.sh create mode 100644 tests/runtime/rx_operator_mutants.sh create mode 100644 tools/rx_operator.c diff --git a/Makefile b/Makefile index f216481d4..0de1d65b8 100644 --- a/Makefile +++ b/Makefile @@ -638,6 +638,7 @@ RX_R13_SRCS = src/runtime/rx_caproot.c src/runtime/rx_world.c \ src/runtime/rx_coherent.c src/runtime/rx_native_bind.c \ src/runtime/rx_aegis.c src/runtime/rx_aien.c src/runtime/rx_omega.c \ src/runtime/rx_generation.c src/runtime/rx_living.c \ + src/runtime/rx_operator.c \ src/sha256.c src/omega_evidence.c src/omega_canonical.c \ src/omega_validate.c src/omega_core.c src/omega_codec.c \ src/aarch64_encoder.c src/aarch64_decoder.c src/omega_realize.c \ @@ -707,7 +708,7 @@ test-jspace-prod: $(RX_JSPACE_PROD_TEST) # R14: the R13 organism attacked while alive. Host uses the R12 processor # stand-in and cannot claim the gate; silicon runs D and E on the GB10 seat. -RX_R14_SRCS = $(filter-out tests/runtime/rx_r13_living.c,$(RX_R13_SRCS)) \ +RX_R14_SRCS = $(filter-out tests/runtime/rx_r13_living.c src/runtime/rx_operator.c,$(RX_R13_SRCS)) \ tests/runtime/rx_r14_recovery.c RX_R14_HOST = $(OUT_DIR)/rx_r14_recovery_host RX_R14_SILICON = $(OUT_DIR)/rx_r14_recovery_silicon @@ -748,7 +749,7 @@ test-r15-instr: $(RX_R15_INSTR) # R15: SEQ semantic parity gate (spec §16 C1 item 9). The R13 body is built # by tests/runtime/rx_r15_rig.c for RES-1 and for the sequential reference. -RX_R15_RIG_SRCS = $(filter-out tests/runtime/rx_r13_living.c,$(RX_R13_SRCS)) \ +RX_R15_RIG_SRCS = $(filter-out tests/runtime/rx_r13_living.c src/runtime/rx_operator.c,$(RX_R13_SRCS)) \ src/runtime/rx_seq_reference.c tests/runtime/rx_r15_rig.c RX_R15_RIG_HDRS = src/runtime/rx_living.h src/runtime/rx_seq_reference.h \ src/runtime/rx_world.h tests/runtime/rx_r15_rig.h @@ -1308,6 +1309,28 @@ test-prod-refuses-test-pieces: $(ARGUS_STAMP) $(AIENOS_CAP_LIB) $(RX_R13_HOST) CC="$(CC)" CFLAGS="$(CFLAGS)" ARGUS_SRC="$(ARGUS_SRC)" OUT="$(OUT_DIR)/prod-refuses" MAKE="$(MAKE)" PROD_BIN="$(RX_R13_HOST)" \ sh tools/r16_prod_refuses.sh +# R16 G6 operator control by execution (docs/r16-operator-control.md): the +# production program driven from outside through its operator entry point. +# Host: the production host binary (R12 processor stand-in). Silicon: the +# production GB10 binary on the resident seat, needs the quiet lock, never +# killed (no SIGKILL phase). The mutants rebuild the production host program +# from mutated copies; the test must fail against each. +RX_OPERATOR_CLI = $(OUT_DIR)/rx_operator +$(RX_OPERATOR_CLI): tools/rx_operator.c | $(OUT_DIR) + $(CC) $(CFLAGS) -o $@ tools/rx_operator.c + +.PHONY: test-r16-operator-host test-r16-operator-silicon test-r16-operator-mutants +test-r16-operator-host: $(RX_R13_HOST) $(RX_OPERATOR_CLI) + bash tests/runtime/rx_operator_host.sh host $(RX_R13_HOST) $(RX_OPERATOR_CLI) + +test-r16-operator-silicon: $(RX_R13_SILICON) $(RX_OPERATOR_CLI) + bash tests/runtime/rx_operator_host.sh silicon $(RX_R13_SILICON) $(RX_OPERATOR_CLI) + +test-r16-operator-mutants: $(RX_R13_HOST) $(RX_OPERATOR_CLI) + CC="$(CC)" CFLAGS="$(CFLAGS)" RX_PROD_ARGUS_FLAGS="$(RX_PROD_ARGUS_FLAGS)" \ + RX_R13_SRCS="$(RX_R13_SRCS)" RX_PROD_ARGUS_SRCS="$(RX_PROD_ARGUS_SRCS)" \ + AIENOS_CAP_LIB="$(AIENOS_CAP_LIB)" bash tests/runtime/rx_operator_mutants.sh $(RX_OPERATOR_CLI) + ARGUS_R7 = $(ARGUS_OUT)/rx_r7_native_test ARGUS_R8 = $(ARGUS_OUT)/rx_r8_aegis_test ARGUS_R9 = $(ARGUS_OUT)/rx_r9_barrier_test diff --git a/docs/r16-operator-control.md b/docs/r16-operator-control.md index 3926afab7..5ba2f991e 100644 --- a/docs/r16-operator-control.md +++ b/docs/r16-operator-control.md @@ -1,7 +1,8 @@ # R16 G6: operator control of the production program (interface contract) -Status: CONTRACT, written before the code (lane ESTOP, CAND-3). The runtime control it -wires is `spec/r16-operator-emergency-stop.md` (merged #300); this document says how an +Status: CONTRACT, written before the code (lane ESTOP, CAND-3), then implemented. Two +points were corrected from the code: when the socket opens (section 2) and a store +refusal under a stop (section 6). The runtime control it wires is `spec/r16-operator-emergency-stop.md` (merged #300); this document says how an operator outside the running production program reaches that control, and what the program does with a request. It adds no authority scheme: every decision is made by the existing world authority (`rx_world_emergency_stop` / `_resume`, `halt_authorize` in @@ -45,9 +46,13 @@ its own world. Every statement below holds for each of those worlds. ## 2. The outside entry point -* An `AF_UNIX` stream socket `/control/operator.sock`, created when the world is - ready for operator requests and removed when the world is torn down. Between worlds - there is no socket: a client gets "connection refused" and the request does nothing. +* An `AF_UNIX` stream socket `/control/operator.sock`, created right after the + world's credential, capability and halt directory exist (before its objects are + built) and removed when the world is torn down. While the program sets the world + up, a request waits (the client allows 60 s) and is answered once setup is done, so + a stop never lands inside setup; a world restored stopped answers at once (it does + no setup until resumed). Between worlds there is no socket: a client gets + "connection refused" and the request does nothing. * Two walls before the credential: the directory is 0700 and owned by the program's user (validated at startup, §5), and every accepted connection is checked with `SO_PEERCRED`: the peer uid must equal the program's effective uid, else the reply @@ -100,7 +105,7 @@ same `halt_authorize` the stop and resume use, under the same locks, added to | command | world call | reply on success | |---|---|---| -| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= crumbs= objects=` plus program counters `served= production_commits= inforce= active_generation=` | +| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= crumbs= reactions=` plus program counters `served= production_commits= inforce= active_generation=` | | `stop [reason]` | `rx_world_emergency_stop` | `OK state=stopped seq= crumb= durable=`; a second stop: `ALREADY` with no new crumb | | `resume` | `rx_world_emergency_resume` | `OK state=running seq=`; a running world: `NOT_STOPPED` | | `revoke-cap` | authorize, then `aienos_cap_revoke` of the presented control capability by the authority's office | `OK revoked=capability`; afterwards every request with that capability is `REFUSED reason=authority` | @@ -152,7 +157,9 @@ earlier world or an earlier program start fails the constant-time caller check * The program keeps its own clocks honest: time spent stopped does not count toward the episode's deadlines (`run_clock`), a production request refused by the stop is published again after resume, and the end-of-mode checks wait while the world is - stopped. A stop therefore delays the episode; it does not fail it. + stopped. A durable generation proposal or promotion that the store refuses + because of the stop (`RX_GEN_ERR_HALTED`) is not an outcome: the activation waits + and posts it again after the resume (`halted_wait`, `src/runtime/rx_living.c`). A stop therefore delays the episode; it does not fail it. * Evidence: at the end of every mode the program reads its crumb log (the canonical evidence, spec §4) and prints `R13 operator : stops S resumes R restored X open O; under stop: commits 0 externals 0 cancelled C`. Any COMMIT or EXTERNAL crumb diff --git a/docs/r16-production-entry-point.md b/docs/r16-production-entry-point.md index 8e1935bc6..337d5aed4 100644 --- a/docs/r16-production-entry-point.md +++ b/docs/r16-production-entry-point.md @@ -31,6 +31,20 @@ credential, and work can no longer be added already done. | recovery | `tests/runtime/rx_r14_recovery.c` on the same sources | `test-r14-host`, `test-r14-silicon` | | proof that no legacy orchestrator is in the path (G3) | link map, strings and exec trace of the production binaries above | `test-r16-authpath`, `test-r16-authpath-silicon` | +### Operator control (R16 G6, CAND-3) + +The production program takes one optional argument, `--state-dir `: its +durable state, validated at startup (a real directory owned by the program's +user, no group or other permission bits; anything else is refused with exit 2 +before any world starts). Without it the program uses a fresh 0700 scratch +directory, as before. `/gen-/` is each mode's generation store and +also its durable halt directory; `/control/` holds the operator credential +file and the owner-only socket `operator.sock`. The only outside entry point is +that socket, driven by `build/rx_operator` (`tools/rx_operator.c`): status, stop, +resume, revoke-cap, revoke, and shutdown while stopped. The contract is +`docs/r16-operator-control.md`; the proof is `make test-r16-operator-host`, +`make test-r16-operator-mutants` and `make test-r16-operator-silicon`. + ### Production program and test build (Lane 32) Test-only pieces build only with one flag, `AIEN_TEST_BUILD` (`-DAIEN_TEST_BUILD=1`, diff --git a/spec/r16-operator-emergency-stop.md b/spec/r16-operator-emergency-stop.md index 58d37b0d6..4ab5ed29d 100644 --- a/spec/r16-operator-emergency-stop.md +++ b/spec/r16-operator-emergency-stop.md @@ -1,10 +1,12 @@ # R16 G6: operator emergency stop (contract) -Status: runtime control IMPLEMENTED and host-tested. G6 item -`operator_emergency_controls_passing` stays **MISSING_IMPLEMENTATION**: the -production R13 program does not wire the control (no `rx_world_set_halt_dir` -call, no operator entry point), so no operator can reach it on the candidate, -and no silicon run exercises a stop. See "Not done" at the end. +Status: runtime control IMPLEMENTED and host-tested; WIRED into the production R13 +program with an outside operator entry point (`docs/r16-operator-control.md`, +CAND-3 lane ESTOP). G6 item `operator_emergency_controls_passing` is operated +only by execution: the host integration test `make test-r16-operator-host` and its +mutants `make test-r16-operator-mutants`, plus the silicon run +`make test-r16-operator-silicon`. It is not PASS until a silicon receipt from the +candidate exists. See "Not done" at the end. Source: `src/runtime/rx_world.c` (`rx_world_emergency_stop`, `rx_world_emergency_resume`, `rx_world_set_halt_dir`, `rx_world_halt_status`), @@ -155,16 +157,23 @@ stand-in): a seat result that lands after the stop is refused, canonical B and B's window keep the world's value, the dependent does not run, no claim is posted under the stop; after resume the seat runs again and B = X + Y, C = X + Y + 1. -## 7. Not done (why the G6 item stays MISSING_IMPLEMENTATION) - -1. **Production wiring.** The production R13 program - (`tests/runtime/rx_r13_living.c`) does not set a halt directory and exposes no - operator entry point. An operator console needs a design for how the - operator's credential and control capability reach a running program; that - design is not written. The G6 item names `rx_world_set_halt_dir` in the R13 - program as a required symbol, so it reads MISSING until that lands. -2. **Silicon.** No silicon run exercises a stop. The resident-seat case runs on - the R12 host stand-in only. +## 7. Not done + +1. **Production wiring: DONE (CAND-3).** The production R13 program sets the + generation store's directory as the halt directory before any object exists, + restores a durable stop before it accepts work, and serves an owner-only + operator socket (`src/runtime/rx_operator.c`, client `build/rx_operator`). The + interface contract is `docs/r16-operator-control.md`. The old string-presence + check (`rx_world_set_halt_dir` text in the R13 source) is gone: the G6 item now + needs the operator integration test, its mutants and the silicon run to pass. + Found by the integration test and fixed with it: a durable promotion or + proposal that the store refused because of a stop (`RX_GEN_ERR_HALTED`) was + recorded as the final outcome, so the positive episode never promoted after + the resume. `src/runtime/rx_living.c` now treats that refusal as "run again + after the resume" (`halted_wait`). +2. **Silicon.** The silicon run of the operator test (`make + test-r16-operator-silicon`, resident GB10 seat, no SIGKILL phase) is the only + chip evidence; until it has passed on the candidate the item is not PASS. 3. **Mark authenticity.** The seal is an unkeyed sha256: it detects a damaged mark, not a forged one. A forged mark can only stop the world (fail closed). Removing the mark while no world runs bypasses the restart restoration; diff --git a/src/runtime/rx_living.c b/src/runtime/rx_living.c index a10d917a5..2efb1c46b 100644 --- a/src/runtime/rx_living.c +++ b/src/runtime/rx_living.c @@ -179,6 +179,17 @@ static void resume_promoter(void *ctx) { rx_world_resume(p->world, p->reaction); } +/* R16 G6: a durable store step refused because an operator stop is in force + * (RX_GEN_ERR_HALTED, from the world or the durable mark) is not an outcome. + * The activation waits in place: it defers and asks to run again, and no + * worker takes work while the world is stopped, so the re-run comes after the + * resume and posts the step again (spec section 3: in-flight work runs again + * on resume). Recording the refusal instead would make it final. */ +static int halted_wait(RxWorld *w, uint32_t reaction) { + rx_world_resume(w, reaction); + return RX_FN_DEFER; +} + static int fn_candidate(RxCtx *c) { RxLiving *l = c->user; RxWorld *w = l->world; @@ -302,6 +313,7 @@ static int fn_candidate(RxCtx *c) { RxGenJobResult jr; if (rx_gen_job_state(l->store, RX_GEN_JOB_PROPOSE, &jr) == RX_GEN_JOB_DONE) { rx_gen_job_take(l->store, RX_GEN_JOB_PROPOSE); + if (jr.rc == RX_GEN_ERR_HALTED) return halted_wait(w, l->r_candidate); if (jr.rc == RX_GEN_OK) { l->proposed_epoch = jr.key; l->candidate_id = jr.id; @@ -335,10 +347,13 @@ static int fn_candidate(RxCtx *c) { /* The store's fsyncs run on the durable executor, not on this * worker. A proposal still in flight (this epoch's or an older * one's) resumes this activation when it lands. */ - if (rx_gen_job_state(l->store, RX_GEN_JOB_PROPOSE, NULL) == RX_GEN_JOB_IDLE && - rx_gen_post_propose_as(l->store, epoch, RX_LIVING_PREPARE_SUBJ, - rx_caller_find(l->keys, RX_LIVING_PREPARE_SUBJ), &draft, - resume_candidate, l) != RX_GEN_OK) { + int prc = RX_GEN_OK; + if (rx_gen_job_state(l->store, RX_GEN_JOB_PROPOSE, NULL) == RX_GEN_JOB_IDLE) + prc = rx_gen_post_propose_as(l->store, epoch, RX_LIVING_PREPARE_SUBJ, + rx_caller_find(l->keys, RX_LIVING_PREPARE_SUBJ), &draft, + resume_candidate, l); + if (prc == RX_GEN_ERR_HALTED) return halted_wait(w, l->r_candidate); + if (prc != RX_GEN_OK) { decline(l, RX_LIVING_WHY_PROPOSE); return -1; } @@ -462,6 +477,7 @@ static int fn_promote(RxCtx *c) { int rc = RX_GEN_OK; if (rx_gen_exec_running(p->store)) { if (promote_durable(p, id, &rc, &active, &ns)) return RX_FN_DEFER; + if (rc == RX_GEN_ERR_HALTED) return halted_wait(p->world, p->reaction); } else { promote_inline(p, id, &rc, &active, &ns); } diff --git a/src/runtime/rx_operator.c b/src/runtime/rx_operator.c new file mode 100644 index 000000000..b1b79c788 --- /dev/null +++ b/src/runtime/rx_operator.c @@ -0,0 +1,396 @@ +/* R16 G6 operator entry point (docs/r16-operator-control.md). */ +#include "rx_operator.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct RxOperator { + RxOperatorConfig cfg; + char sock_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; + char cred_path[512]; + int listen_fd; + int wake[2]; /* a byte on wake[1] ends the listener */ + pthread_t thread; + int thread_live; + pthread_mutex_t gate; /* held by the program while it sets the world up */ +}; + +int rx_operator_dir_check(const char *dir, int create, char *why, size_t n) { + struct stat st; + if (!dir || !dir[0]) { snprintf(why, n, "no directory"); return -1; } + if (lstat(dir, &st) != 0) { + if (errno != ENOENT || !create) { snprintf(why, n, "%s: %s", dir, strerror(errno)); return -1; } + if (mkdir(dir, 0700) != 0 || lstat(dir, &st) != 0) { + snprintf(why, n, "%s: cannot create: %s", dir, strerror(errno)); + return -1; + } + } + if (S_ISLNK(st.st_mode)) { snprintf(why, n, "%s is a symlink", dir); return -1; } + if (!S_ISDIR(st.st_mode)) { snprintf(why, n, "%s is not a directory", dir); return -1; } + if (st.st_uid != geteuid()) { + snprintf(why, n, "%s is owned by uid %u, not by this program's uid %u", dir, + (unsigned)st.st_uid, (unsigned)geteuid()); + return -1; + } + if (st.st_mode & 077) { + snprintf(why, n, "%s has mode %03o: group or other may reach it (need no bits in 077)", + dir, (unsigned)(st.st_mode & 0777)); + return -1; + } + return 0; +} + +static void hex32(const uint8_t *b, char out[65]) { + for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", b[i]); +} + +static uint64_t realtime_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; +} + +/* The operator's copy of its credential: 0600, written whole or not at all. */ +static int write_cred(RxOperator *op, uint32_t subject, const RxCallerCred *cred, RxCapRef cap) { + char tmp[600], secret[65], buf[1024]; + hex32(cred->secret, secret); + int len = snprintf(buf, sizeof buf, + "aien-operator-credential v1\nworld %s %ld %llu\nsocket %s\nsubject %u\n" + "cred %llu %s\ncap %u %llu\n", + op->cfg.world_key ? op->cfg.world_key : "-", (long)getpid(), + (unsigned long long)realtime_ns(), op->sock_path, subject, + (unsigned long long)cred->generation, secret, cap.cap_id, + (unsigned long long)cap.generation); + for (size_t i = 0; i < sizeof secret; i++) ((volatile char *)secret)[i] = 0; + if (len <= 0 || (size_t)len >= sizeof buf) return -1; + if ((size_t)snprintf(tmp, sizeof tmp, "%s.partial", op->cred_path) >= sizeof tmp) return -1; + int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); + int rc = fd < 0 ? -1 : 0; + if (rc == 0 && fchmod(fd, 0600) != 0) rc = -1; + for (int off = 0; rc == 0 && off < len;) { + ssize_t w = write(fd, buf + off, (size_t)(len - off)); + if (w < 0 && errno == EINTR) continue; + if (w <= 0) rc = -1; else off += (int)w; + } + if (rc == 0 && fsync(fd) != 0) rc = -1; + if (fd >= 0) close(fd); + for (size_t i = 0; i < sizeof buf; i++) ((volatile char *)buf)[i] = 0; + if (rc == 0 && rename(tmp, op->cred_path) != 0) rc = -1; + if (rc != 0) unlink(tmp); + return rc; +} + +/* ---- one request ---------------------------------------------------------- */ + +typedef struct { + char cmd[16]; + uint32_t subject; + RxCallerCred cred; + RxCapRef cap; + int32_t reason; + int have_subject, have_gen, have_secret, have_cap, have_reason; +} Req; + +static int hexval(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +/* Strict unsigned decimal into *out, at most `max`. */ +static int udec(const char *s, uint64_t max, uint64_t *out) { + if (!*s) return -1; + uint64_t v = 0; + for (; *s; s++) { + if (*s < '0' || *s > '9') return -1; + uint64_t d = (uint64_t)(*s - '0'); + if (v > (max - d) / 10) return -1; + v = v * 10 + d; + } + *out = v; + return 0; +} + +static int parse(char *line, Req *q) { + memset(q, 0, sizeof *q); + char *save = NULL; + char *t = strtok_r(line, " ", &save); + if (!t || strcmp(t, "aien-operator") != 0) return -1; + if (!(t = strtok_r(NULL, " ", &save)) || strcmp(t, "v1") != 0) return -1; + if (!(t = strtok_r(NULL, " ", &save)) || strlen(t) >= sizeof q->cmd) return -1; + snprintf(q->cmd, sizeof q->cmd, "%s", t); + while ((t = strtok_r(NULL, " ", &save))) { + char *eq = strchr(t, '='); + if (!eq) return -1; + *eq = 0; + const char *k = t, *v = eq + 1; + uint64_t x, y; + if (strcmp(k, "subject") == 0 && !q->have_subject) { + if (udec(v, UINT32_MAX, &x) != 0) return -1; + q->subject = (uint32_t)x; q->have_subject = 1; + } else if (strcmp(k, "gen") == 0 && !q->have_gen) { + if (udec(v, UINT64_MAX, &x) != 0) return -1; + q->cred.generation = x; q->have_gen = 1; + } else if (strcmp(k, "secret") == 0 && !q->have_secret) { + if (strlen(v) != 2 * RX_CALLER_SECRET_LEN) return -1; + for (unsigned i = 0; i < RX_CALLER_SECRET_LEN; i++) { + int hi = hexval(v[2 * i]), lo = hexval(v[2 * i + 1]); + if (hi < 0 || lo < 0) return -1; + q->cred.secret[i] = (uint8_t)(hi << 4 | lo); + } + q->have_secret = 1; + } else if (strcmp(k, "cap") == 0 && !q->have_cap) { + char a[24]; + const char *c = strchr(v, ':'); + if (!c || (size_t)(c - v) >= sizeof a) return -1; + memcpy(a, v, (size_t)(c - v)); + a[c - v] = 0; + if (udec(a, UINT32_MAX, &x) != 0 || udec(c + 1, UINT64_MAX, &y) != 0) return -1; + q->cap = (RxCapRef){(uint32_t)x, y}; q->have_cap = 1; + } else if (strcmp(k, "reason") == 0 && !q->have_reason) { + if (udec(v, INT32_MAX, &x) != 0) return -1; + q->reason = (int32_t)x; q->have_reason = 1; + } else { + return -1; + } + } + if (!q->have_subject || !q->have_gen || !q->have_secret || !q->have_cap) return -1; + if (q->have_reason && strcmp(q->cmd, "stop") != 0) return -1; + return 0; +} + +static const char *refusal(int rc) { + return rc == RX_ERR_IDENTITY ? "identity" : rc == RX_ERR_AUTHORITY ? "authority" : NULL; +} + +static void handle(RxOperator *op, Req *q, char *out, size_t n) { + RxWorld *w = op->cfg.world; + RxHaltStatus h; + memset(&h, 0, sizeof h); + int stop = strcmp(q->cmd, "stop") == 0, resume = strcmp(q->cmd, "resume") == 0; + int rc; + if (stop) { + rc = rx_world_emergency_stop(w, q->subject, &q->cred, q->cap, q->reason, &h); + if (rc == RX_OK) { + if (op->cfg.on_halt) op->cfg.on_halt(op->cfg.ctx, 1); + snprintf(out, n, "OK state=stopped seq=%llu crumb=%llu durable=%d", + (unsigned long long)h.seq, (unsigned long long)h.crumb, h.durable); + } else if (rc == RX_HALT_ALREADY) { + snprintf(out, n, "ALREADY state=stopped seq=%llu", (unsigned long long)h.seq); + } else if (refusal(rc)) { + snprintf(out, n, "REFUSED reason=%s", refusal(rc)); + } else { + snprintf(out, n, "ERROR rc=%d", rc); + } + return; + } + if (resume) { + rc = rx_world_emergency_resume(w, q->subject, &q->cred, q->cap, &h); + if (rc == RX_OK) { + if (op->cfg.on_halt) op->cfg.on_halt(op->cfg.ctx, 0); + snprintf(out, n, "OK state=running seq=%llu", (unsigned long long)h.seq); + } else if (rc == RX_HALT_NOT_STOPPED) { + snprintf(out, n, "NOT_STOPPED state=running"); + } else if (refusal(rc)) { + snprintf(out, n, "REFUSED reason=%s", refusal(rc)); + } else { + snprintf(out, n, "ERROR rc=%d", rc); + } + return; + } + int status = strcmp(q->cmd, "status") == 0, shutdown = strcmp(q->cmd, "shutdown") == 0; + int revoke = strcmp(q->cmd, "revoke") == 0, revoke_cap = strcmp(q->cmd, "revoke-cap") == 0; + if (!status && !shutdown && !revoke && !revoke_cap) { snprintf(out, n, "BAD_REQUEST"); return; } + rc = rx_world_operator_authorize(w, q->subject, &q->cred, q->cap); + if (rc != RX_OK) { + if (refusal(rc)) snprintf(out, n, "REFUSED reason=%s", refusal(rc)); + else snprintf(out, n, "ERROR rc=%d", rc); + return; + } + rx_world_halt_status(w, &h); + if (status) { + int used = snprintf(out, n, "OK state=%s restored=%d seq=%llu durable=%d refused=%llu " + "crumbs=%llu reactions=%u", + h.halted ? "stopped" : "running", h.restored ? 1 : 0, + (unsigned long long)h.seq, h.durable, (unsigned long long)h.refused, + (unsigned long long)__atomic_load_n(&w->n_crumbs, __ATOMIC_RELAXED), + (unsigned)__atomic_load_n(&w->n_reactions, __ATOMIC_RELAXED)); + if (op->cfg.describe && used > 0 && (size_t)used + 2 < n) { + out[used++] = ' '; + op->cfg.describe(op->cfg.ctx, out + used, n - (size_t)used); + } + return; + } + if (shutdown) { + if (!h.halted) { snprintf(out, n, "NOT_STOPPED state=running"); return; } + if (op->cfg.on_shutdown) op->cfg.on_shutdown(op->cfg.ctx); + snprintf(out, n, "OK state=stopped shutdown=1"); + return; + } + /* revoke-cap / revoke: the authority's office voids the control + * capability; revoke also retires the caller enrollment (it needs the + * current credential, so only its holder can). */ + AienosCapRef office; + if (aienos_cap_office(op->cfg.admin, &office) != 0 || + aienos_cap_revoke(op->cfg.admin, office, + (AienosCapRef){q->cap.cap_id, q->cap.generation}) != 0) { + snprintf(out, n, "ERROR rc=revoke-capability"); + return; + } + if (revoke) { + rc = rx_world_revoke_caller(w, q->subject, &q->cred); + if (rc != RX_CALLER_OK) { snprintf(out, n, "ERROR rc=revoke-credential %d", rc); return; } + unlink(op->cred_path); + snprintf(out, n, "OK revoked=capability,credential"); + return; + } + snprintf(out, n, "OK revoked=capability"); +} + +static void serve_one(RxOperator *op, int fd) { + char line[RX_OPERATOR_LINE], body[RX_OPERATOR_LINE + 512]; + struct ucred pc; + socklen_t pl = sizeof pc; + struct timeval tv = {2, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); + if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &pc, &pl) != 0 || pl != sizeof pc || + pc.uid != geteuid()) { + snprintf(body, sizeof body, "REFUSED reason=peer"); + goto reply; + } + size_t got = 0; + int complete = 0; + while (got < sizeof line - 1) { + ssize_t r = read(fd, line + got, sizeof line - 1 - got); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + got += (size_t)r; + char *nl = memchr(line, '\n', got); + if (nl) { + size_t len = (size_t)(nl - line); + *nl = 0; + /* nothing after the newline, no NUL byte inside the line */ + complete = len == got - 1 && strlen(line) == len; + break; + } + } + Req q; + memset(&q, 0, sizeof q); + if (!complete || parse(line, &q) != 0) { + snprintf(body, sizeof body, "BAD_REQUEST"); + } else { + pthread_mutex_lock(&op->gate); + handle(op, &q, body, sizeof body); + pthread_mutex_unlock(&op->gate); + } + for (size_t i = 0; i < sizeof q; i++) ((volatile uint8_t *)&q)[i] = 0; + for (size_t i = 0; i < sizeof line; i++) ((volatile char *)line)[i] = 0; +reply:; + char out[sizeof body + 32]; + int len = snprintf(out, sizeof out, "aien-operator v1 %s\n", body); + if (len > 0) { + size_t sent = 0; + while (sent < (size_t)len) { + ssize_t s = send(fd, out + sent, (size_t)len - sent, MSG_NOSIGNAL); + if (s < 0 && errno == EINTR) continue; + if (s <= 0) break; + sent += (size_t)s; + } + } +} + +/* The listener: one connection at a time until the wake pipe fires. It + * sequences no faculty; it carries operator requests to the world. */ +static void *listener_main(void *arg) { + RxOperator *op = arg; + for (;;) { + struct pollfd p[2] = {{op->listen_fd, POLLIN, 0}, {op->wake[0], POLLIN, 0}}; + int r = poll(p, 2, -1); + if (r < 0 && errno == EINTR) continue; + if (r < 0 || (p[1].revents & (POLLIN | POLLHUP | POLLERR))) break; + if (!(p[0].revents & POLLIN)) continue; + int fd = accept4(op->listen_fd, NULL, NULL, SOCK_CLOEXEC); + if (fd < 0) continue; + serve_one(op, fd); + close(fd); + } + return NULL; +} + +int rx_operator_open(RxOperator **out, const RxOperatorConfig *cfg, uint32_t subject, + RxCallerCred *cred, RxCapRef cap) { + if (!out || !cfg || !cfg->world || !cfg->admin || !cfg->control_dir || !cred) return -1; + *out = NULL; + char why[256]; + if (rx_operator_dir_check(cfg->control_dir, 0, why, sizeof why) != 0) { + fprintf(stderr, "R13 operator: control directory refused: %s\n", why); + return -1; + } + RxOperator *op = calloc(1, sizeof *op); + if (!op) return -1; + op->cfg = *cfg; + op->listen_fd = -1; + op->wake[0] = op->wake[1] = -1; + if ((size_t)snprintf(op->sock_path, sizeof op->sock_path, "%s/%s", cfg->control_dir, + RX_OPERATOR_SOCK) >= sizeof op->sock_path || + (size_t)snprintf(op->cred_path, sizeof op->cred_path, "%s/%s", cfg->control_dir, + RX_OPERATOR_CRED) >= sizeof op->cred_path) { + fprintf(stderr, "R13 operator: control path too long for a socket address\n"); + free(op); + return -1; + } + pthread_mutex_init(&op->gate, NULL); + pthread_mutex_lock(&op->gate); /* held until rx_operator_release */ + unlink(op->sock_path); /* a socket left by an earlier start */ + struct sockaddr_un a; + memset(&a, 0, sizeof a); + a.sun_family = AF_UNIX; + memcpy(a.sun_path, op->sock_path, strlen(op->sock_path) + 1); + op->listen_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + mode_t old = umask(077); + int ok = op->listen_fd >= 0 && bind(op->listen_fd, (struct sockaddr *)&a, sizeof a) == 0; + umask(old); + ok = ok && chmod(op->sock_path, 0600) == 0 && listen(op->listen_fd, 8) == 0 && + pipe2(op->wake, O_CLOEXEC) == 0 && write_cred(op, subject, cred, cap) == 0; + for (size_t i = 0; i < sizeof *cred; i++) ((volatile uint8_t *)cred)[i] = 0; + if (ok && pthread_create(&op->thread, NULL, listener_main, op) == 0) { + op->thread_live = 1; + *out = op; + return 0; + } + fprintf(stderr, "R13 operator: entry point could not start: %s\n", strerror(errno)); + pthread_mutex_unlock(&op->gate); + rx_operator_close(op); + return -1; +} + +void rx_operator_hold(RxOperator *op) { if (op) pthread_mutex_lock(&op->gate); } +void rx_operator_release(RxOperator *op) { if (op) pthread_mutex_unlock(&op->gate); } + +void rx_operator_close(RxOperator *op) { + if (!op) return; + if (op->thread_live) { + char b = 1; + while (write(op->wake[1], &b, 1) < 0 && errno == EINTR) {} + pthread_join(op->thread, NULL); + } + if (op->listen_fd >= 0) close(op->listen_fd); + if (op->wake[0] >= 0) close(op->wake[0]); + if (op->wake[1] >= 0) close(op->wake[1]); + unlink(op->sock_path); + unlink(op->cred_path); + pthread_mutex_destroy(&op->gate); + free(op); +} diff --git a/src/runtime/rx_operator.h b/src/runtime/rx_operator.h new file mode 100644 index 000000000..5f35b5919 --- /dev/null +++ b/src/runtime/rx_operator.h @@ -0,0 +1,54 @@ +#ifndef RX_OPERATOR_H +#define RX_OPERATOR_H +/* R16 G6: the operator's outside entry point to a running production world + * (docs/r16-operator-control.md). An owner-only Unix-domain socket in a + * validated 0700 directory, a SO_PEERCRED check, and one line per request + * carrying the operator's runtime-issued caller credential and its + * RX_WORLD_RES_CONTROL capability. Every decision is the world's + * (rx_world_emergency_stop / _resume / rx_world_operator_authorize); this + * module only carries requests and replies. */ +#include "rx_world.h" +#include "aienos_cap.h" + +#include +#include + +#define RX_OPERATOR_SUBJ 70u /* runs no reaction; holds only the control capability */ +#define RX_OPERATOR_CRED "operator.cred" +#define RX_OPERATOR_SOCK "operator.sock" +#define RX_OPERATOR_LINE 512u + +typedef struct RxOperator RxOperator; + +typedef struct { + RxWorld *world; + AienosCapAdmin *admin; /* the authority: its office revokes the capability */ + const char *control_dir; /* validated with rx_operator_dir_check */ + const char *world_key; /* the mode this world runs, for the credential file */ + /* Program counters appended to a status reply (key=value ...). */ + void (*describe)(void *ctx, char *buf, size_t n); + /* Called after the world accepted a stop (1) or a resume (0). */ + void (*on_halt)(void *ctx, int halted); + /* Called after an authorized shutdown of a stopped world. */ + void (*on_shutdown)(void *ctx); + void *ctx; +} RxOperatorConfig; + +/* `dir` must be a real directory (lstat; no symlink), owned by the effective + * uid, with no group or other permission bits. With `create`, a missing + * directory is made 0700 first. 0 ok; -1 refused, with the reason in `why`. */ +int rx_operator_dir_check(const char *dir, int create, char *why, size_t n); + +/* Write the credential file (0600, temporary file, fsync, rename), wipe + * `cred`, bind the socket and start the listener. The request gate starts + * HELD by the caller: no request is served until rx_operator_release. */ +int rx_operator_open(RxOperator **out, const RxOperatorConfig *cfg, uint32_t subject, + RxCallerCred *cred, RxCapRef cap); +/* The request gate: while the program holds it (world setup), requests wait. */ +void rx_operator_hold(RxOperator *op); +void rx_operator_release(RxOperator *op); +/* Stop the listener, remove the socket and the credential file. The gate + * must not be held by the caller. */ +void rx_operator_close(RxOperator *op); + +#endif diff --git a/src/runtime/rx_world.c b/src/runtime/rx_world.c index d5a711ca1..be82545f2 100644 --- a/src/runtime/rx_world.c +++ b/src/runtime/rx_world.c @@ -1153,6 +1153,16 @@ int rx_world_emergency_resume(RxWorld *w, uint32_t subject, const RxCallerCred * return rc; } +int rx_world_operator_authorize(RxWorld *w, uint32_t subject, const RxCallerCred *cred, RxCapRef cap) { + if (!w) return RX_ERR_ARG; + pthread_mutex_lock(&w->mu); + pthread_mutex_lock(&w->callers_mu); + int rc = halt_authorize(w, subject, cred, cap); + pthread_mutex_unlock(&w->callers_mu); + pthread_mutex_unlock(&w->mu); + return rc; +} + void rx_world_halt_status(RxWorld *w, RxHaltStatus *out) { if (!w || !out) return; pthread_mutex_lock(&w->mu); diff --git a/src/runtime/rx_world.h b/src/runtime/rx_world.h index 5743a3e22..9b4806eda 100644 --- a/src/runtime/rx_world.h +++ b/src/runtime/rx_world.h @@ -824,6 +824,11 @@ int rx_world_emergency_stop(RxWorld *w, uint32_t subject, const RxCallerCred *c int rx_world_emergency_resume(RxWorld *w, uint32_t subject, const RxCallerCred *cred, RxCapRef cap, RxHaltStatus *out); void rx_world_halt_status(RxWorld *w, RxHaltStatus *out); +/* The same authority check as stop and resume (credential, not a reaction + * subject, live control capability), without acting: RX_OK, RX_ERR_IDENTITY + * or RX_ERR_AUTHORITY. For operator requests that read or retire the + * operator's own authority (docs/r16-operator-control.md). Never call with mu held. */ +int rx_world_operator_authorize(RxWorld *w, uint32_t subject, const RxCallerCred *cred, RxCapRef cap); /* A stimulus from outside the organism (sensor, human input). Requires a * capability for (external_subject, object resource, WRITE). Returns the diff --git a/tests/r16_qualify/run.sh b/tests/r16_qualify/run.sh index e2b3b0b2b..2a728bf37 100755 --- a/tests/r16_qualify/run.sh +++ b/tests/r16_qualify/run.sh @@ -17,7 +17,7 @@ check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; FAILS=$((FAILS W=$SCR/w mkdir -p "$W/tools" cp "$HERE/tools/r16_qualify.sh" "$HERE/tools/aienos_lock_source.sh" "$W/tools/" -G6FILES="src/omega_accelerator_world.c src/runtime/rx_generation.c src/omega_world_gates.c tools/omegatool.c src/runtime/rx_native_bind.c src/omega_evidence.c src/omega_verify.c src/runtime/rx_resident_gpu.c src/runtime/rx_seq_reference.c src/runtime/rx_world.c src/runtime/rx_living.c" +G6FILES="src/omega_accelerator_world.c src/runtime/rx_generation.c src/omega_world_gates.c tools/omegatool.c src/runtime/rx_native_bind.c src/omega_evidence.c src/omega_verify.c src/runtime/rx_resident_gpu.c src/runtime/rx_seq_reference.c src/runtime/rx_world.c src/runtime/rx_living.c src/runtime/rx_operator.c tests/runtime/rx_r13_living.c" for p in $G6FILES; do mkdir -p "$W/$(dirname "$p")"; cp "$HERE/$p" "$W/$p"; done printf 'build/\n' > "$W/.gitignore" g() { git -C "$W" -c user.name=r16 -c user.email=r16@invalid -c commit.gpgsign=false "$@"; } @@ -49,8 +49,8 @@ check "output under evidence/: exit 2" '[ $rc = 2 ]' out=$(Q R16_RUN_ID=none 2>&1); rc=$? R=$W/build/r16-raw/none/DRY-RUN-receipt.json check "no fixtures: exit 3 (nothing ran)" '[ $rc = 3 ]' -check "no fixtures: G6 MISSING_IMPLEMENTATION (one item has no implementation; no test ran)" 'echo "$out" | grep -q "G6=MISSING_IMPLEMENTATION (items missing: 1)"' -check "no fixtures: summary all NOT_RUN" 'echo "$out" | grep -q "^Gates: G1=NOT_RUN G2=NOT_RUN G3=NOT_RUN G4=NOT_RUN G5=NOT_RUN G6=MISSING_IMPLEMENTATION G7=NOT_RUN G8=NOT_RUN$"' +check "no fixtures: G6 NOT_RUN (every item implemented, no test ran)" 'echo "$out" | grep -q " G6=NOT_RUN" && ! echo "$out" | grep -q "G6=MISSING_IMPLEMENTATION"' +check "no fixtures: summary all NOT_RUN" 'echo "$out" | grep -q "^Gates: G1=NOT_RUN G2=NOT_RUN G3=NOT_RUN G4=NOT_RUN G5=NOT_RUN G6=NOT_RUN G7=NOT_RUN G8=NOT_RUN$"' check "no fixtures: receipt gate NOT_RUN" 'grep -q "\"gate\": \"NOT_RUN\"" "$R"' check "no fixtures: receipt has no PASS value" '! grep -q "\"PASS\"" "$R"' check "no fixtures: silicon_observed false (computed)" 'grep -q "\"silicon_observed\": false" "$R"' @@ -79,7 +79,7 @@ check "bad exit status with pass line: G5 FAIL, exit 1" '[ $rc = 1 ] && echo "$o echo 0 > "$F/r16_surface.log.rc" out=$(Q R16_RUN_ID=fx 2>&1); rc=$? check "good G4/G5 fixtures: those gates PASS" 'echo "$out" | grep -q "G4=PASS" && echo "$out" | grep -q "G5=PASS"' -check "all-good G4/G5 still exit 3 (G6 tests did not run)" '[ $rc = 3 ] && echo "$out" | grep -q "G6=MISSING_IMPLEMENTATION"' +check "all-good G4/G5 still exit 3 (G6 tests did not run)" '[ $rc = 3 ] && echo "$out" | grep -q "G6=NOT_RUN"' # 6b. R11 that skipped its living run (load > 2) exits 0 with "failures 0": NOT_RUN, never PASS printf 'checks 400 failures 0\n' > "$F/r11_aien.log"; echo 0 > "$F/r11_aien.log.rc" @@ -232,14 +232,20 @@ RX_EMERGENCY_MUTANTS: PASS" g6log r15_parity_host.log "SEQ_SEMANTIC_PARITY=PASS" g6log r15_parity_silicon.log "SEQ_SEMANTIC_PARITY=PASS" g6log r15_receipt.log "r15 receipt test: 0 failure(s)" + g6log r16_operator_host.log "R16 operator: 120 checks, 0 failures, 0 skipped (host, phases: startup control restart kill) +R16 operator gate: R16_G6_OPERATOR=HOST_PASS_NON_SILICON" + g6log r16_operator_mutants.log "RX_OPERATOR_MUTANTS: 14 mutants, 0 failures, 0 skipped +RX_OPERATOR_MUTANTS: PASS" + g6log r16_operator_silicon.log "R16 operator: 100 checks, 0 failures, 0 skipped (silicon, phases: startup control restart kill) +R16 operator gate: R16_G6_OPERATOR=PASS" } G6Q() { Q R16_RUN_ID=g6 2>&1; } R=$G/DRY-RUN-receipt.json g6_item() { sed -n 's/^.*"item": "'"$1"'", "status": "\([A-Z_]*\)".*$/\1/p' "$R"; } g6_good_logs out=$(G6Q); rc=$? -check "G6 all good: G6 is MISSING_IMPLEMENTATION (operator emergency controls named nowhere), never PASS" 'echo "$out" | grep -q "G6=MISSING_IMPLEMENTATION" && ! echo "$out" | grep -q "G6=PASS"' -check "G6 all good: eleven items PASS, operator emergency controls MISSING_IMPLEMENTATION" '[ "$(grep -c "\"item\": \"[a-z0-9_]*\", \"status\": \"PASS\"" "$R")" = 11 ] && [ "$(g6_item operator_emergency_controls_passing)" = MISSING_IMPLEMENTATION ]' +check "G6 all good: every item implemented and operated, G6 PASS" 'echo "$out" | grep -q " G6=PASS"' +check "G6 all good: twelve items PASS, operator emergency controls among them" '[ "$(grep -c "\"item\": \"[a-z0-9_]*\", \"status\": \"PASS\"" "$R")" = 12 ] && [ "$(g6_item operator_emergency_controls_passing)" = PASS ]' check "G6 all good: protected_surfaces_kept six presence flags true" '[ "$(grep -c "_present\": true" "$R")" = 6 ]' check "G6 all good: no FAIL anywhere and G6 alone does not make the run pass (exit 3)" '[ $rc = 3 ] && ! echo "$out" | grep -q "G6=FAIL"' check "G6 all good: receipt names file and symbol per item" 'grep -q "\"file\": \"src/runtime/rx_generation.c\", \"symbol\": \"rx_gen_recover\", \"source\": \"omega_tree\", \"defined\": true" "$R"' @@ -283,7 +289,7 @@ check "G6 fake log reporting failures (no pass line): FAIL, exit 1" '[ $rc = 1 ] g6log r9_barrier.log "generation barrier kept a single coherent generation through every injected stop" g6log r12_silicon.log "checks 40 failures 3 silicon 1" 1 out=$(G6Q) -check "G6 operator emergency controls stay MISSING_IMPLEMENTATION even when its mapped test fails or passes" '[ "$(g6_item operator_emergency_controls_passing)" = MISSING_IMPLEMENTATION ] && echo "$out" | grep -q "G6=FAIL"' +check "G6 a failing silicon seat-loss run: G6 FAIL" 'echo "$out" | grep -q "G6=FAIL" && [ "$(g6_item r12_seat_loss_handling_passing)" = FAIL ]' g6log r12_silicon.log "checks 40 failures 0 silicon 1" g6log m19_world.log "STAGE 1 / PERSISTENT WORLD QUALIFICATION: 17 / 18 M19 GATES PASSED [FAIL] OMEGA_ACCEL_RESIDENT_FAULT_RECOVERY_PASS : x" 0 @@ -291,6 +297,44 @@ out=$(G6Q) check "G6 M19 log with a [FAIL] gate line (exit 0): known_good_fallback FAIL" '[ "$(g6_item known_good_fallback_present)" = FAIL ]' g6log m19_world.log "STAGE 1 / PERSISTENT WORLD QUALIFICATION: 18 / 18 M19 GATES PASSED" +# operator emergency controls: operated only by execution of the production program, +# host and silicon apart; the old string-presence check can no longer pass it. +g6log r16_operator_silicon.log "R16 operator gate: R16_G6_OPERATOR=HOST_PASS_NON_SILICON" +out=$(G6Q) +check "G6 operator: a host result in the silicon slot is not a silicon pass: item FAIL" '[ "$(g6_item operator_emergency_controls_passing)" = FAIL ]' +rm -f "$G/r16_operator_silicon.log" "$G/r16_operator_silicon.log.rc" +out=$(G6Q) +check "G6 operator: host test and mutants passed, no silicon receipt: item NOT_RUN, G6 not PASS" '[ "$(g6_item operator_emergency_controls_passing)" = NOT_RUN ] && ! echo "$out" | grep -q "G6=PASS"' +g6log r16_operator_silicon.log "[SKIPPED] unauthorized: peer of another uid (sudo -n unavailable) +R16 operator gate: R16_G6_OPERATOR=PASS" +out=$(G6Q) +check "G6 operator: silicon log with a SKIPPED case and the pass line: NOT_RUN, never PASS" '[ "$(g6_item operator_emergency_controls_passing)" = NOT_RUN ]' +g6log r16_operator_silicon.log "[-] stop: authorized stop accepted, durable +R16 operator gate: R16_G6_OPERATOR=FAIL" 1 +out=$(G6Q) +check "G6 operator: failed silicon run: item FAIL, G6 FAIL" '[ "$(g6_item operator_emergency_controls_passing)" = FAIL ] && echo "$out" | grep -q "G6=FAIL"' +g6log r16_operator_silicon.log "R16 operator gate: R16_G6_OPERATOR=PASS" +g6log r16_operator_host.log "R16 operator gate: R16_G6_OPERATOR=FAIL" 1 +out=$(G6Q) +check "G6 operator: failed host run with a passing silicon log: item FAIL" '[ "$(g6_item operator_emergency_controls_passing)" = FAIL ]' +g6log r16_operator_host.log "R16 operator gate: R16_G6_OPERATOR=PASS" +out=$(G6Q) +check "G6 operator: a host log carrying the silicon pass line is not the host verdict: FAIL" '[ "$(g6_item operator_emergency_controls_passing)" = FAIL ]' +g6log r16_operator_host.log "R16 operator gate: R16_G6_OPERATOR=HOST_PASS_NON_SILICON" +g6log r16_operator_mutants.log "ok O1 wiring missing: killed +FAIL O5 success reply without a state transition: SURVIVED (exit 0) +RX_OPERATOR_MUTANTS: FAIL" 1 +out=$(G6Q) +check "G6 operator: a surviving mutant: item FAIL" '[ "$(g6_item operator_emergency_controls_passing)" = FAIL ]' +g6log r16_operator_mutants.log "RX_OPERATOR_MUTANTS: PASS" +RL=$W/tests/runtime/rx_r13_living.c +sed -i 's|^static int operator_open(Rig \*r) {|/* static int operator_open(Rig *r) { */ static int operator_0pen(Rig *r) {|' "$RL"; g add -A; g commit -qm "mutation: entry point only in a comment" +out=$(G6Q) +check "G6 operator: production wiring present only in a comment (string still in the file), every log passing: MISSING_IMPLEMENTATION" '[ "$(g6_item operator_emergency_controls_passing)" = MISSING_IMPLEMENTATION ] && grep -q "operator_open(Rig" "$RL" && ! echo "$out" | grep -q "G6=PASS"' +g6_unmut +out=$(G6Q) +check "G6 operator: reverted, all logs passing: PASS" '[ "$(g6_item operator_emergency_controls_passing)" = PASS ]' + # skipped tests are never PASS g6log r9_barrier.log "[-] living run not exercised: SKIPPED-LOADED generation barrier kept a single coherent generation through every injected stop" @@ -375,12 +419,12 @@ check "prebuilt AIENOS_CAP_LIB override refused (exit 2)" '[ $rc = 2 ] && echo " # receipt is valid JSON; each item says plainly what its mapping is (no shared boilerplate) check "G6 receipt is valid JSON (jq)" 'jq -e . "$R" >/dev/null' check "G6 receipt: twelve items, twelve different basis texts" '[ "$(jq "[.g6_items[].basis] | unique | length" "$R")" = 12 ] && [ "$(jq ".g6_items | length" "$R")" = 12 ]' -check "G6 receipt: proxy mappings say PROXY, emergency item says MISSING_IMPLEMENTATION" '[ "$(jq "[.g6_items[] | select(.basis | startswith(\"PROXY\"))] | length" "$R")" -ge 5 ] && jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | .basis | startswith(\"MISSING_IMPLEMENTATION\")" "$R" >/dev/null' +check "G6 receipt: proxy mappings say PROXY, emergency item says it is operated only by execution" '[ "$(jq "[.g6_items[] | select(.basis | startswith(\"PROXY\"))] | length" "$R")" -ge 5 ] && jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | .basis | contains(\"operated only by execution\")" "$R" >/dev/null' check "G6 receipt: seat kill hook is not an item symbol" '! jq -e ".g6_items[].implementation[] | select(.symbol==\"rx_gpu_seat_kill\")" "$R" >/dev/null' -check "G6 emergency item: runtime symbols defined, production wiring absent, RX_EMERGENCY cited" 'jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | (.implementation[] | select(.symbol==\"rx_world_emergency_stop\") | .defined == true) and (.implementation[] | select(.symbol==\"rx_world_set_halt_dir\") | .defined == false) and (.tests[] | select(.name==\"RX_EMERGENCY\") | .status == \"PASS\" and .target == \"test-rx-emergency\")" "$R" >/dev/null' +check "G6 emergency item: runtime and production wiring defined, RX_EMERGENCY cited" 'jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | (.implementation[] | select(.symbol==\"rx_world_emergency_stop\") | .defined == true) and (.implementation[] | select(.symbol==\"operator_open\") | .defined == true) and (.tests[] | select(.name==\"R16_OP_SILICON\") | .target == \"test-r16-operator-silicon\") and (.tests[] | select(.name==\"RX_EMERGENCY\") | .status == \"PASS\" and .target == \"test-rx-emergency\")" "$R" >/dev/null' g6log rx_emergency.log "RX_EMERGENCY_STOP: PASS (0 failures; host CPU, real caproot authority)" out=$(G6Q) -check "G6 emergency test without the mutant pass line: test FAIL in the receipt, item still MISSING_IMPLEMENTATION, G6 never PASS" '! echo "$out" | grep -q "G6=PASS" && [ "$(g6_item operator_emergency_controls_passing)" = MISSING_IMPLEMENTATION ] && jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | .tests[] | select(.name==\"RX_EMERGENCY\") | .status == \"FAIL\"" "$R" >/dev/null' +check "G6 emergency test without the mutant pass line: test FAIL in the receipt, item FAIL, G6 never PASS" '! echo "$out" | grep -q "G6=PASS" && [ "$(g6_item operator_emergency_controls_passing)" = FAIL ] && jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | .tests[] | select(.name==\"RX_EMERGENCY\") | .status == \"FAIL\"" "$R" >/dev/null' g6log rx_emergency.log "RX_EMERGENCY_MUTANTS: PASS" out=$(G6Q) check "G6 emergency test without the stop pass line: test FAIL in the receipt" 'jq -e ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | .tests[] | select(.name==\"RX_EMERGENCY\") | .status == \"FAIL\"" "$R" >/dev/null' diff --git a/tests/runtime/rx_operator_host.sh b/tests/runtime/rx_operator_host.sh new file mode 100644 index 000000000..99d3a45c8 --- /dev/null +++ b/tests/runtime/rx_operator_host.sh @@ -0,0 +1,342 @@ +#!/bin/bash +# R16 G6 operator control by execution (docs/r16-operator-control.md §7). +# +# rx_operator_host.sh +# +# Starts the PRODUCTION R13 program (built without AIEN_TEST_BUILD) and drives +# it only from outside: the rx_operator client over the owner-only socket, and +# signals. Every check reads a reply, a file the world wrote in its state +# directory, the program's exit status or the program's crumb-log audit line. +# A case that cannot run here prints SKIPPED and the gate line is NOT_RUN, +# never a pass. Silicon: the program is never killed (no SIGKILL phase; on a +# failed check the world is resumed and the program is waited for). +# +# Environment: RX_OP_PHASES (default "startup control restart kill") runs a +# subset (mutants); RX_OP_FAILFAST=1 stops at the first failed check (host). +set -u +SEAT=${1:?host or silicon}; BIN=${2:?binary}; CLI=${3:?client} +case "$SEAT" in host|silicon) ;; *) echo "seat must be host or silicon" >&2; exit 2 ;; esac +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +BIN=$(cd "$(dirname "$BIN")" && pwd)/$(basename "$BIN") +CLI=$(cd "$(dirname "$CLI")" && pwd)/$(basename "$CLI") +PHASES=${RX_OP_PHASES:-"startup control restart kill"} +FAILFAST=${RX_OP_FAILFAST:-0} +W=$(mktemp -d "${TMPDIR:-/tmp}/rx-op.XXXXXX"); chmod 700 "$W" +if [ "$SEAT" = silicon ]; then WORLD_WAIT=900; EXIT_WAIT=3600; else WORLD_WAIT=120; EXIT_WAIT=300; fi +CHECKS=0; FAILS=0; SKIPS=0; PID="" +SUDO=0; if sudo -n true 2>/dev/null; then SUDO=1; fi + +cleanup() { + if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then + if [ "$SEAT" = host ]; then kill -9 "$PID" 2>/dev/null; wait "$PID" 2>/dev/null + else "$CLI" --control "$S/control" resume >/dev/null 2>&1; wait "$PID" 2>/dev/null; fi + fi + [ "$SUDO" = 1 ] && sudo -n rm -rf "$W" 2>/dev/null || rm -rf "$W" +} +trap cleanup EXIT + +receipt() { + local dir="$HERE/build/r16-operator" commit dirty sum + mkdir -p "$dir" + commit=$(git -C "$HERE" rev-parse HEAD 2>/dev/null || echo unknown) + if [ -n "$(git -C "$HERE" status --porcelain 2>/dev/null)" ]; then dirty=true; else dirty=false; fi + sum=$(sha256sum "$BIN" | cut -d' ' -f1) + cat > "$dir/operator_${SEAT}_receipt.json" < + CHECKS=$((CHECKS + 1)) + if eval "$2"; then echo "[+] $1" + else + echo "[-] $1"; FAILS=$((FAILS + 1)) + if [ "$FAILFAST" = 1 ]; then finish; fi + fi +} +skip() { echo "[SKIPPED] $1"; SKIPS=$((SKIPS + 1)); } + +REPLY_="" +op() { REPLY_=$("$CLI" "$@" 2>&1); return $?; } # op : sets REPLY_ +kv() { printf '%s\n' "$REPLY_" | tr ' ' '\n' | sed -n "s/^$1=//p" | head -1; } +has() { printf '%s\n' "$REPLY_" | grep -Fq -- "$1"; } + +start_prog() { # start_prog + "$BIN" --state-dir "$1" > "$2" 2>&1 < /dev/null & + PID=$! +} +alive() { [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; } +# wait_world : this program start's credential file for that world is +# there (a file left by a killed earlier start names another pid) and its socket exists. +wait_world() { + local i=0 lim=$((WORLD_WAIT * 50)) + while [ $i -lt $lim ]; do + if grep -q "^world $2 $PID " "$1/control/operator.cred" 2>/dev/null && [ -S "$1/control/operator.sock" ]; then + return 0 + fi + alive || return 1 + sleep 0.02; i=$((i + 1)) + done + return 1 +} +wait_line() { # wait_line : until the program printed it (or exited) + local i=0 lim=$((WORLD_WAIT * 20)) + while [ $i -lt $lim ]; do + grep -Fq -- "$2" "$1" && return 0 + alive || { grep -Fq -- "$2" "$1"; return $?; } + sleep 0.05; i=$((i + 1)) + done + return 1 +} +# wait_exit: the program ends by itself. A program still running after EXIT_WAIT +# seconds (a world left stopped by a failed check) is a failure: on host it is +# killed, on silicon it is resumed and waited for (a chip program is never killed). +wait_exit() { + local i=0 lim=$((EXIT_WAIT * 20)) late=0 + while alive && [ $i -lt $lim ]; do sleep 0.05; i=$((i + 1)); done + if alive; then + late=1; echo "program still running after ${EXIT_WAIT}s" + if [ "$SEAT" = host ]; then kill -9 "$PID" 2>/dev/null + else "$CLI" --control "$S/control" resume >/dev/null 2>&1; fi + fi + wait "$PID"; RC=$?; PID="" + [ $late = 0 ] || RC=124 +} +sealed() { # sealed : last line is "sha256 <64 hex>" + [ -f "$1" ] && tail -n 1 "$1" | grep -Eq '^sha256 [0-9a-f]{64}$' +} +forge() { # forge + sed -e "$3" "$1" > "$2"; chmod 600 "$2" +} +audit_ok() { # audit_ok + grep -Eq "^R13 operator $2: stops $3 resumes $4 restored $5 open 0; under stop: commits 0 externals 0 cancelled [0-9]+; order ok$" "$1" +} + +echo "R16 operator control ($SEAT): binary $BIN" + +# ---- startup: the state directory is validated before any world starts ------------- +if [[ " $PHASES " == *" startup "* ]]; then + mkdir -m 755 "$W/open755" + "$BIN" --state-dir "$W/open755" > "$W/s1.log" 2>&1; rc=$? + check "startup: a group/other-readable state directory is refused (exit 2) before any world" \ + '[ $rc = 2 ] && grep -q "state directory refused" "$W/s1.log" && [ ! -e "$W/open755/control" ]' + mkdir -m 700 "$W/real"; ln -s "$W/real" "$W/link" + "$BIN" --state-dir "$W/link" > "$W/s2.log" 2>&1; rc=$? + check "startup: a symlinked state directory is refused" '[ $rc = 2 ] && grep -q "is a symlink" "$W/s2.log"' + mkdir -m 700 "$W/ctl"; mkdir -m 750 "$W/ctl/control" + "$BIN" --state-dir "$W/ctl" > "$W/s3.log" 2>&1; rc=$? + check "startup: a group-readable control directory is refused" '[ $rc = 2 ] && grep -q "control directory refused" "$W/s3.log"' + if [ "$SUDO" = 1 ]; then + mkdir -m 700 "$W/foreign"; sudo -n chown root "$W/foreign" + "$BIN" --state-dir "$W/foreign" > "$W/s4.log" 2>&1; rc=$? + check "startup: a state directory owned by another uid is refused" '[ $rc = 2 ] && grep -q "owned by uid 0" "$W/s4.log"' + else + skip "startup: foreign-owned state directory (needs sudo -n to chown)" + fi +fi + +# ---- control: one program start driven through four of its worlds -------------------- +S="$W/state-a"; mkdir -m 700 "$S"; LA="$W/run-a.log" +if [[ " $PHASES " == *" control "* ]] || [[ " $PHASES " == *" restart "* ]]; then + start_prog "$S" "$LA" + check "control: the positive world opens the operator entry point" 'wait_world "$S" positive' + C="$S/control"; cp "$C/operator.cred" "$W/cred-positive" + forge "$W/cred-positive" "$W/forged" 's/^\(cred [0-9]* \)\(.\)\(.*\)$/\1\3\2/' # rotated secret: right length, wrong bytes + op --control "$C" status + check "control: authorized status, world running, no stop yet" 'has "OK state=running" && [ "$(kv seq)" = 0 ]' +fi +if [[ " $PHASES " == *" control "* ]]; then + # Unauthorized requests: each refused, nothing changes, no state revealed. + op --cred "$W/forged" --control "$C" stop + check "unauthorized: forged secret, stop REFUSED identity" 'has "REFUSED reason=identity" && ! has state=' + op --cred "$W/forged" --control "$C" status + check "unauthorized: forged secret, status REFUSED identity (no state revealed)" 'has "REFUSED reason=identity" && ! has state=' + forge "$W/cred-positive" "$W/wrongcap" 's/^cap \([0-9]*\) /cap 1\1 /' + op --cred "$W/wrongcap" --control "$C" stop + check "unauthorized: another capability, stop REFUSED authority" 'has "REFUSED reason=authority"' + forge "$W/cred-positive" "$W/wrongsubj" 's/^subject 70$/subject 61/' + op --cred "$W/wrongsubj" --control "$C" stop + check "unauthorized: a reaction subject (61) with the operator secret, REFUSED identity" 'has "REFUSED reason=identity"' + op --control "$C" --raw "aien-operator v1 stop" + check "unauthorized: request without credential fields is BAD_REQUEST" 'has "BAD_REQUEST"' + op --control "$C" --raw "$(sed -n 's/^cred \([0-9]*\) \([0-9a-f]*\)$/aien-operator v1 explode subject=70 gen=\1 secret=\2 cap=0:0/p' "$W/cred-positive")" + check "unauthorized: unknown command with a full credential is BAD_REQUEST" 'has "BAD_REQUEST"' + if [ "$SUDO" = 1 ]; then + REPLY_=$(sudo -n "$CLI" --control "$C" stop 2>&1) + check "unauthorized: a peer of another uid (root) is REFUSED peer, even with the credential" 'has "REFUSED reason=peer"' + else + skip "unauthorized: peer of another uid (needs sudo -n)" + fi + op --control "$C" status + check "unauthorized: after every refusal the world still runs, no stop taken, no mark" \ + 'has "OK state=running" && [ "$(kv seq)" = 0 ] && [ ! -e "$S/gen-positive/OPERATOR_HALT" ]' + + # Authorized stop: the world freezes; the promotion cannot happen under it. + op --control "$C" stop 7 + check "stop: authorized stop accepted, durable" 'has "OK state=stopped" && [ "$(kv seq)" = 1 ] && [ "$(kv durable)" = 1 ]' + M="$S/gen-positive/OPERATOR_HALT" + check "stop: sealed mark in the generation store directory" \ + 'head -n 1 "$M" | grep -qx "aien-operator-halt v1" && grep -qx "reason 7" "$M" && grep -qx "subject 70" "$M" && sealed "$M"' + op --control "$C" status; S1=$REPLY_ + sv1=$(kv served); pc1=$(kv production_commits); ag1=$(kv active_generation); pr1=$(kv promotion); if1=$(kv inforce) + check "stop: status says stopped, the promotion has not happened yet" 'has "state=stopped" && [ "$pr1" = 0 ] && [ "$if1" = 0 ] && [ -n "$sv1" ]' + sleep 2 + op --control "$C" status + check "stop: two seconds later nothing was served, committed or promoted" \ + '[ "$(kv served)" = "$sv1" ] && [ "$(kv production_commits)" = "$pc1" ] && [ "$(kv active_generation)" = "$ag1" ] && [ "$(kv promotion)" = 0 ] && [ "$(kv inforce)" = 0 ]' + op --cred "$W/forged" --control "$C" resume + check "stop: a forged resume is REFUSED and the world stays stopped" 'has "REFUSED reason=identity"' + op --cred "$W/wrongcap" --control "$C" resume + check "stop: a resume with another capability is REFUSED" 'has "REFUSED reason=authority"' + op --control "$C" status + check "stop: still stopped after the refused resumes" 'has "state=stopped" && [ "$(kv served)" = "$sv1" ]' + op --control "$C" stop 8 + check "repeat: a second stop answers ALREADY, same stop" 'has "ALREADY state=stopped" && [ "$(kv seq)" = 1 ]' + op --control "$C" resume + check "resume: authorized resume accepted" 'has "OK state=running" && [ "$(kv seq)" = 1 ]' + check "resume: the mark is gone and the sealed resumed record kept" \ + '[ ! -e "$M" ] && R=$(ls "$S"/gen-positive/OPERATOR_HALT.resumed.1.* 2>/dev/null | head -1) && [ -n "$R" ] && grep -qx "resumed_by 70" "$R" && grep -qx "reason 7" "$R" && sealed "$R"' + op --control "$C" resume + check "repeat: resume of a running world answers NOT_STOPPED" 'has "NOT_STOPPED"' + op --control "$C" shutdown + check "shutdown of a running world answers NOT_STOPPED (the program goes on)" 'has "NOT_STOPPED"' + ok=0 + for i in $(seq 1 200); do op --control "$C" status; [ "$(kv served)" != "$sv1" ] && { ok=1; break; }; sleep 0.05; done + check "resume: production serves again after the resume" '[ $ok = 1 ]' + + # In-flight work under production load: stop and resume while requests run. + cycles=0 + for i in $(seq 1 12); do + op --control "$C" stop 9 || break + has "OK state=stopped" || break + sleep 0.05 + op --control "$C" resume || break + has "OK state=running" || break + cycles=$((cycles + 1)) + done + check "in-flight: at least 6 stop/resume cycles while the positive world runs ($cycles)" '[ $cycles -ge 6 ]' + check "positive world: the promotion happens after the resume (generation advanced)" 'wait_line "$LA" "R13 positive: generation"' + check "positive world: crumb log shows $((1 + cycles)) stops, as many resumes, nothing committed or published under a stop" \ + 'audit_ok "$LA" positive $((1 + cycles)) $((1 + cycles)) 0' + cancelled=$(sed -n 's/^R13 operator positive: .*cancelled \([0-9]*\);.*$/\1/p' "$LA") + check "in-flight: activations caught computing by a stop were refused at commit (cancelled ${cancelled:-?})" '[ "${cancelled:-0}" -ge 1 ]' + + # Next world (A no AIEN): stale credential, then the capability revoked by the authority. + check "rotation: the next world opens with a new credential" 'wait_world "$S" no-aien' + check "rotation: the new credential differs from the earlier world's" '! cmp -s "$W/cred-positive" "$C/operator.cred"' + op --cred "$W/cred-positive" --control "$C" status + check "stale: the earlier world's credential is REFUSED identity" 'has "REFUSED reason=identity"' + op --control "$C" revoke-cap + check "revoke-cap: the authority revokes the control capability" 'has "OK revoked=capability"' + op --control "$C" stop + check "revoke-cap: a stop with the revoked capability is REFUSED authority" 'has "REFUSED reason=authority"' + op --control "$C" status + check "revoke-cap: status with it is REFUSED authority" 'has "REFUSED reason=authority"' + check "revoke-cap: the world runs on without operator control (control A passes, no stop)" \ + 'wait_line "$LA" "R13 control A:" && audit_ok "$LA" no-aien 0 0 0 && [ ! -e "$S/gen-no-aien/OPERATOR_HALT" ]' + + # Next world (B no promotion authority): the credential revoked. + check "revoke: world B opens" 'wait_world "$S" no-promotion' + cp "$C/operator.cred" "$W/cred-b" + op --control "$C" revoke + check "revoke: capability and credential revoked, credential file removed" 'has "OK revoked=capability,credential" && [ ! -e "$C/operator.cred" ]' + op --cred "$W/cred-b" --control "$C" stop + check "revoke: a stop with the revoked credential is REFUSED identity" 'has "REFUSED reason=identity"' + check "revoke: world B completes without a stop" 'wait_line "$LA" "R13 control B:" && audit_ok "$LA" no-promotion 0 0 0' +fi +if [[ " $PHASES " == *" control "* ]] || [[ " $PHASES " == *" restart "* ]]; then + # World C: stop, then shut the program down while stopped. + check "shutdown: world C opens" 'wait_world "$S" revoked-experiment' + cp "$C/operator.cred" "$W/cred-c" + op --control "$C" stop 11 + check "shutdown: stop world C" 'has "OK state=stopped"' + op --cred "$W/forged" --control "$C" shutdown + check "shutdown: a forged shutdown is REFUSED" 'has "REFUSED reason=identity"' + op --control "$C" shutdown + check "shutdown: authorized shutdown of the stopped world" 'has "OK state=stopped shutdown=1"' + wait_exit + check "shutdown: the program exits 3, writes no receipt, the stop stays on disk" \ + '[ $RC = 3 ] && grep -q "shutdown while stopped in revoked-experiment" "$LA" && ! grep -q "R13 gate:" "$LA" && sealed "$S/gen-revoked-experiment/OPERATOR_HALT" && [ ! -e "$C/operator.sock" ]' +fi + +# ---- restart while stopped (after the shutdown) ----------------------------------------- +if [[ " $PHASES " == *" restart "* ]]; then + LB="$W/run-b.log" + start_prog "$S" "$LB" + check "restart: world C reopens" 'wait_world "$S" revoked-experiment' + op --control "$C" status + check "restart: world C comes up STOPPED, restored, before any work (no reaction registered)" \ + 'has "OK state=stopped" && [ "$(kv restored)" = 1 ] && [ "$(kv reactions)" = 0 ] && has "setup=pending"' + k1=$(kv crumbs) + check "restart: the program says the stop was restored" 'grep -q "^R13 operator revoked-experiment: restored STOPPED" "$LB"' + op --cred "$W/cred-c" --control "$C" status + check "stale: the credential of the earlier program start is REFUSED identity" 'has "REFUSED reason=identity"' + sleep 1 + op --control "$C" status + check "restart: one second later still stopped, nothing built, no crumb added" \ + 'has "state=stopped" && [ "$(kv reactions)" = 0 ] && [ "$(kv crumbs)" = "$k1" ]' + op --control "$C" resume + check "recovery: resume of the restored stop" 'has "OK state=running"' + check "recovery: the mark is gone, the resumed record kept" \ + '[ ! -e "$S/gen-revoked-experiment/OPERATOR_HALT" ] && ls "$S"/gen-revoked-experiment/OPERATOR_HALT.resumed.* >/dev/null 2>&1' + wait_exit + if [ "$SEAT" = host ]; then want="R13 gate: R13_LIVING_SYSTEM=HOST_PASS_NON_SILICON"; else want="R13 gate: R13_LIVING_SYSTEM="; fi + check "recovery: the program completes every mode and passes its R13 checks (exit 0)" \ + '[ $RC = 0 ] && grep -q "R13 control C:" "$LB" && grep -Fq "$want" "$LB" && ! grep -q "R13_LIVING_SYSTEM=FAIL" "$LB"' + check "recovery: crumb log of world C shows the restored stop and its resume, nothing under it" \ + 'audit_ok "$LB" revoked-experiment 1 1 1' +fi + +# ---- crash while stopped (host only: a chip program is never killed) ------------------ +if [[ " $PHASES " == *" kill "* ]]; then + if [ "$SEAT" = host ]; then + S="$W/state-k"; mkdir -m 700 "$S"; C="$S/control"; LC="$W/run-c.log"; LD="$W/run-d.log" + start_prog "$S" "$LC" + check "crash: positive world opens" 'wait_world "$S" positive' + op --control "$C" stop 13 + check "crash: stop accepted" 'has "OK state=stopped"' + kill -9 "$PID"; wait "$PID" 2>/dev/null; PID="" + check "crash: after SIGKILL the sealed mark is on disk" 'sealed "$S/gen-positive/OPERATOR_HALT" && grep -qx "reason 13" "$S/gen-positive/OPERATOR_HALT"' + start_prog "$S" "$LD" + check "crash restart: positive world reopens" 'wait_world "$S" positive' + op --control "$C" status + check "crash restart: comes up STOPPED before any work" 'has "OK state=stopped" && [ "$(kv restored)" = 1 ] && [ "$(kv reactions)" = 0 ]' + op --control "$C" resume + check "crash recovery: resume accepted" 'has "OK state=running"' + wait_exit + check "crash recovery: positive promotes after the restart, every mode passes (exit 0)" \ + '[ $RC = 0 ] && grep -q "R13 positive: generation" "$LD" && grep -Fq "R13 gate: R13_LIVING_SYSTEM=HOST_PASS_NON_SILICON" "$LD" && audit_ok "$LD" positive 1 1 1' + else + echo "kill phase: host only by design (a chip program is never killed); restart on silicon is proven by the shutdown phase" + fi +fi + +finish diff --git a/tests/runtime/rx_operator_mutants.sh b/tests/runtime/rx_operator_mutants.sh new file mode 100644 index 000000000..9ffbc2a00 --- /dev/null +++ b/tests/runtime/rx_operator_mutants.sh @@ -0,0 +1,79 @@ +#!/bin/bash +# R16 G6 operator control: every link from the outside request to the world's +# stop is load-bearing. Each mutant changes one place in a temporary copy of the +# PRODUCTION sources; the production host program is rebuilt from that copy with +# the production flags, and tests/runtime/rx_operator_host.sh must FAIL against it +# (exit non-zero with at least one failed check). The unmutated copy must PASS. +# A pattern that does not match exactly once fails this script, never a skip. +# +# rx_operator_mutants.sh +# Environment from make: CC CFLAGS RX_PROD_ARGUS_FLAGS RX_R13_SRCS RX_PROD_ARGUS_SRCS AIENOS_CAP_LIB +set -u +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +CLI=$(cd "$(dirname "$1")" && pwd)/$(basename "$1") +W=$(mktemp -d "${TMPDIR:-/tmp}/rx-op-mut.XXXXXX") +trap 'rm -rf "$W"' EXIT +JOBS=${RX_OP_MUT_JOBS:-4} + +# name|file|phases the test runs against it|perl substitution (applied with -0, must match once) +MUTANTS='O1 wiring missing: no durable halt directory|tests/runtime/rx_r13_living.c|control|s/int halt_mark = rx_world_set_halt_dir\(&r->w, r->generation_dir\);/int halt_mark = 0;/ +O2 wiring only in a comment|tests/runtime/rx_r13_living.c|control|s/int halt_mark = rx_world_set_halt_dir\(&r->w, r->generation_dir\);/int halt_mark = 0; \/* rx_world_set_halt_dir(\&r->w, r->generation_dir); *\// +O3 entry point referenced, never called|tests/runtime/rx_r13_living.c|control|s/ if \(operator_open\(r\) != 0\) return -1;/ if (0 \&\& operator_open(r) != 0) return -1;/ +O4 command handler disconnected (stop never routed)|src/runtime/rx_operator.c|control|s/int stop = strcmp\(q->cmd, "stop"\) == 0,/int stop = 0,/ +O5 success reply without a state transition|src/runtime/rx_operator.c|control|s/rc = rx_world_emergency_stop\(w, q->subject, &q->cred, q->cap, q->reason, &h\);/rc = RX_OK; h.seq = 1; h.durable = 1;/ +O6 unauthorized resume accepted (check called, result unused)|src/runtime/rx_world.c|control|s/int rc = halt_authorize\(w, subject, cred, cap\);\n if \(rc == RX_OK && !w->halted\) rc = RX_HALT_NOT_STOPPED;/int rc = (halt_authorize(w, subject, cred, cap), RX_OK);\n if (rc == RX_OK \&\& !w->halted) rc = RX_HALT_NOT_STOPPED;/ +O7 peer uid check removed|src/runtime/rx_operator.c|control|s/pl != sizeof pc \|\|\n pc\.uid != geteuid\(\)\) \{/pl != sizeof pc) {/ +O8 status without the authority check|src/runtime/rx_operator.c|control|s/rc = rx_world_operator_authorize\(w, q->subject, &q->cred, q->cap\);/rc = RX_OK;/ +O9 revoke-cap does not revoke|src/runtime/rx_operator.c|control|s/aienos_cap_revoke\(op->cfg\.admin, office,\n\s+\(AienosCapRef\)\{q->cap\.cap_id, q->cap\.generation\}\) != 0/0/ +O10 restart does not wait for the resume|tests/runtime/rx_r13_living.c|restart|s/ if \(world_halted\(r\)\) \{\n r->op_restored = 1;/ if (0) {\n r->op_restored = 1;/ +O11 startup accepts a group-readable directory|src/runtime/rx_operator.c|startup|s/if \(st\.st_mode & 077\) \{/if (0) {/ +O12 audit does not count stops|tests/runtime/rx_r13_living.c|control|s/ stops\+\+;\n// +O13 shutdown accepted while running|src/runtime/rx_operator.c|control|s/if \(!h\.halted\) \{ snprintf\(out, n, "NOT_STOPPED state=running"\); return; \}// +O14 stop reply before the world call (handler answers from the request)|src/runtime/rx_operator.c|control|s/ rc = rx_world_emergency_stop\(w, q->subject, &q->cred, q->cap, q->reason, &h\);\n if \(rc == RX_OK\) \{/ rc = RX_OK; rx_world_halt_status(w, \&h);\n if (rc == RX_OK) {/' + +copy() { mkdir -p "$1"; (cd "$HERE" && tar -cf - src tests/runtime tests/fabric tools) | tar -xf - -C "$1"; ln -s "$HERE/build" "$1/build"; } +build() { # dir: the production host program, production flags and sources + (cd "$1" && $CC $CFLAGS $RX_PROD_ARGUS_FLAGS -pthread -o prog $RX_R13_SRCS $RX_PROD_ARGUS_SRCS \ + $AIENOS_CAP_LIB -lm) > "$1/build.log" 2>&1 +} + +fails=0; n_mut=0 +copy "$W/base" +names="" +while IFS='|' read -r name file phases sub; do + [ -n "$name" ] || continue + id=${name%% *}; d="$W/$id"; copy "$d" + n=$(perl -0 -e 'my $s = do { local $/; }; my $c = eval "\$s =~ $ARGV[0]g"; die $@ if $@; print $c ? $c + 0 : 0' "$sub" < "$d/$file") + if [ "$n" != 1 ]; then echo "FAIL $name: pattern matched ${n:-?} times (must be 1)"; fails=$((fails + 1)); continue; fi + perl -0pi -e "$sub" "$d/$file" + if cmp -s "$d/$file" "$HERE/$file"; then echo "FAIL $name: substitution changed nothing"; fails=$((fails + 1)); continue; fi + echo "$phases" > "$d/phases"; echo "$name" > "$d/name" + names="$names $id" +done <<< "$MUTANTS" + +# Builds in parallel, tests one at a time (each test starts the production program). +export CC CFLAGS RX_PROD_ARGUS_FLAGS RX_R13_SRCS RX_PROD_ARGUS_SRCS AIENOS_CAP_LIB +export -f build +printf '%s\n' base $names | xargs -P "$JOBS" -I{} bash -c 'build "$0/{}" || echo "build failed: {}"' "$W" + +if [ -x "$W/base/prog" ] && bash "$HERE/tests/runtime/rx_operator_host.sh" host "$W/base/prog" "$CLI" > "$W/base/run.log" 2>&1; then + echo "ok unmutated: PASS ($(grep -c '^\[+\]' "$W/base/run.log") checks)" +else + echo "FAIL unmutated: did not pass"; grep -E '^\[-\]|SKIPPED|build failed' "$W/base/run.log" "$W/base/build.log" | head -5 + fails=$((fails + 1)) +fi +skipped=$(grep -c '^\[SKIPPED\]' "$W/base/run.log" 2>/dev/null); skipped=${skipped:-0} +for id in $names; do + d="$W/$id"; name=$(cat "$d/name"); n_mut=$((n_mut + 1)) + if [ ! -x "$d/prog" ]; then echo "FAIL $name: mutant did not build"; tail -3 "$d/build.log"; fails=$((fails + 1)); continue; fi + RX_OP_PHASES=$(cat "$d/phases") RX_OP_FAILFAST=1 bash "$HERE/tests/runtime/rx_operator_host.sh" host "$d/prog" "$CLI" > "$d/run.log" 2>&1; rc=$? + nf=$(grep -c '^\[-\]' "$d/run.log" 2>/dev/null); nf=${nf:-0} + first=$(grep -m1 '^\[-\]' "$d/run.log" | cut -c1-110) + if [ $rc != 0 ] && [ "$nf" -gt 0 ]; then echo "ok $name: killed by: ${first#\[-\] }" + elif grep -q '^\[SKIPPED\]' "$d/run.log"; then echo "SKIPPED $name: the test could not run the case that kills it"; skipped=$((skipped + 1)) + else echo "FAIL $name: SURVIVED (exit $rc)"; fails=$((fails + 1)); fi +done +echo "RX_OPERATOR_MUTANTS: $n_mut mutants, $fails failures, $skipped skipped" +if [ "$fails" = 0 ] && [ "$skipped" = 0 ]; then echo "RX_OPERATOR_MUTANTS: PASS"; exit 0; fi +if [ "$fails" = 0 ]; then echo "RX_OPERATOR_MUTANTS: NOT_RUN (SKIPPED cases)"; exit 3; fi +echo "RX_OPERATOR_MUTANTS: FAIL"; exit 1 diff --git a/tests/runtime/rx_r13_living.c b/tests/runtime/rx_r13_living.c index ad8e2db82..893c298db 100644 --- a/tests/runtime/rx_r13_living.c +++ b/tests/runtime/rx_r13_living.c @@ -2,6 +2,7 @@ #include "runtime/rx_living.h" #include "runtime/rx_resident_gpu.h" #include "runtime/aien_machine_id.h" +#include "runtime/rx_operator.h" /* Lane 32: two programs from this file (docs/r16-production-entry-point.md). * PRODUCTION (default, no flag): no test pieces. ARGUS is linked and observes * (RX_ARGUS=2, authority observer, consumer ingest), pinned by argus.lock; the @@ -23,6 +24,7 @@ #include "sha256.h" #include +#include #include #include #include @@ -32,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -44,6 +47,7 @@ enum { POSITIVE, NO_AIEN, NO_PROMOTION, REVOKED_EXPERIMENT, #define CLASS_A725 0xd87u #define CLASS_X925 0xd85u #define RES_INTENT 0x6130010ull +#define U(x) ((unsigned long long)(x)) typedef struct { AienosCapAdmin *admin; @@ -78,6 +82,15 @@ typedef struct { * composition it runs (home/compose). */ char home_dir[128]; AienMachineId machine; + /* R16 G6 operator control (docs/r16-operator-control.md): the operator's + * credential is handed to its file and wiped; the program keeps no copy. */ + int mode; + RxCallerCred op_cred; + RxCapRef op_cap; + RxOperator *op; + int op_gate_held, op_restored, ready; + atomic_ullong op_halt_since, op_halt_total; /* ns; stopped time is not run time */ + atomic_int op_shutdown, op_teardown; } Rig; static int g_stage; typedef struct { @@ -225,10 +238,170 @@ static int living_identity(Rig *r) { return aien_mid_store(p, &r->machine) == AIEN_MID_OK ? 0 : -1; } +/* ---- R16 G6 operator control (docs/r16-operator-control.md) -------------- + * The program's durable state: /control (the operator's credential + * file and socket) and one generation store per mode, /gen-, + * which is also the world's durable halt directory. */ +enum { OP_SHUTDOWN = 2 }; +static const char *const g_mode_key[] = {"positive", "no-aien", "no-promotion", + "revoked-experiment", "stale-gpu", "failed-verification"}; +static char g_state_dir[192]; +static char g_control_dir[224]; +static uint64_t g_op_stops, g_op_resumes, g_op_restored, g_op_open, g_op_cancelled; + +static int world_halted(Rig *r) { + RxHaltStatus h; + rx_world_halt_status(&r->w, &h); + return h.halted; +} + +/* Run time: wall time minus the time the world spent stopped. Episode + * deadlines count run time, so a stop delays the episode and never fails it. */ +static uint64_t run_clock(Rig *r) { + uint64_t now = now_ns(), since = atomic_load(&r->op_halt_since); + return now - atomic_load(&r->op_halt_total) - (since && since < now ? now - since : 0); +} + +static void op_on_halt(void *ctx, int halted) { + Rig *r = ctx; + uint64_t now = now_ns(), since = atomic_load(&r->op_halt_since); + if (halted && !since) atomic_store(&r->op_halt_since, now); + if (!halted && since) { + atomic_fetch_add(&r->op_halt_total, now - since); + atomic_store(&r->op_halt_since, 0); + } +} + +static atomic_int g_op_shutdown; /* the operator ended this program (FAIL reports it) */ +static void op_on_shutdown(void *ctx) { + atomic_store(&((Rig *)ctx)->op_shutdown, 1); + atomic_store(&g_op_shutdown, 1); +} + +static void op_describe(void *ctx, char *buf, size_t n) { + Rig *r = ctx; + if (!r->ready) { snprintf(buf, n, "world=%s setup=pending", g_mode_key[r->mode]); return; } + uint64_t active = 0, lineage = 0; + rx_gen_active(r->gen, &active, &lineage); + snprintf(buf, n, "world=%s served=%llu production_commits=%llu promotion=%llu inforce=%llu " + "active_generation=%llu", + g_mode_key[r->mode], (unsigned long long)__atomic_load_n(&r->served, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&r->w.reactions[r->omega.r_serve].commits, + __ATOMIC_RELAXED), + (unsigned long long)field(r, r->living.o.promotion, 0), + (unsigned long long)field(r, r->living.o.inforce, 0), (unsigned long long)active); +} + +/* Wait while the world is stopped. -1 when the operator shut the program + * down, the program is tearing the world down, or the production thread + * is told to stop, 0 when the world runs. */ +static __thread int t_producer; /* set on the production request thread */ +static int wait_running(Rig *r) { + while (world_halted(r)) { + if (atomic_load(&r->op_shutdown) || atomic_load(&r->op_teardown) || + (t_producer && atomic_load(&r->producer_stop))) return -1; + pause_us(1000); + } + return atomic_load(&r->op_shutdown) ? -1 : 0; +} + +/* An outside publication refused by an operator stop is published again + * after the resume; any other refusal is an error. */ +static int publish(Rig *r, RxCapRef cap, const RxMutation *m, uint32_t n) { + for (;;) { + int64_t rc = rx_world_publish_external(&r->w, cap, m, n); + if (rc != RX_ERR_HALTED) return rc > 0 ? 0 : -1; + if (wait_running(r) != 0) return 1; /* abandoned under a stop, not an error */ + } +} + +static int operator_open(Rig *r) { + RxOperatorConfig oc = {&r->w, r->admin, g_control_dir, g_mode_key[r->mode], + op_describe, op_on_halt, op_on_shutdown, r}; + if (rx_operator_open(&r->op, &oc, RX_OPERATOR_SUBJ, &r->op_cred, r->op_cap) != 0) return -1; + r->op_gate_held = 1; + return 0; +} +static void operator_release(Rig *r) { + if (r->op && r->op_gate_held) { r->op_gate_held = 0; rx_operator_release(r->op); } +} +static void operator_hold(Rig *r) { + if (r->op && !r->op_gate_held) { rx_operator_hold(r->op); r->op_gate_held = 1; } +} + +/* The canonical evidence of operator control in this world: its crumb log. + * Between an OPERATOR_STOP and its OPERATOR_RESUME (or after a stop never + * resumed) no COMMIT and no EXTERNAL crumb may appear; each RESUME is caused + * by the STOP before it. */ +static int operator_audit(Rig *r) { + uint64_t stops = 0, resumes = 0, commits = 0, externals = 0, cancelled = 0, open = 0; + int order_ok = 1; + for (uint64_t id = 1; id <= r->w.n_crumbs; id++) { + const RxCrumb *c = rx_world_crumb(&r->w, id); + if (!c) continue; + if (c->kind == RX_CRUMB_OPERATOR_STOP) { + if (open) order_ok = 0; + stops++; + open = id; + } else if (c->kind == RX_CRUMB_OPERATOR_RESUME) { + if (!open || c->n_parents < 1 || c->parents[0] != open) order_ok = 0; + resumes++; + open = 0; + } else if (open) { + if (c->kind == RX_CRUMB_COMMIT) commits++; + if (c->kind == RX_CRUMB_EXTERNAL) externals++; + if (c->kind == RX_CRUMB_CANCELLED && c->reason == RX_ERR_HALTED) cancelled++; + } + } + g_op_stops += stops; g_op_resumes += resumes; g_op_cancelled += cancelled; + g_op_restored += (uint64_t)r->op_restored; g_op_open += open ? 1 : 0; + printf("R13 operator %s: stops %llu resumes %llu restored %d open %d; under stop: commits %llu " + "externals %llu cancelled %llu; order %s\n", g_mode_key[r->mode], U(stops), U(resumes), + r->op_restored, open ? 1 : 0, U(commits), U(externals), U(cancelled), + order_ok ? "ok" : "BROKEN"); + return commits || externals || !order_ok ? -1 : 0; +} + + +/* The program's state directory: --state-dir, or a fresh 0700 scratch + * directory. Refused (exit 2, before any world starts) unless it and its + * control directory are real directories owned by this uid with no group or + * other permission bits, and the socket path fits a socket address. */ +static int operator_state(const char *dir) { + char why[320]; + if (dir) { + if ((size_t)snprintf(g_state_dir, sizeof g_state_dir, "%s", dir) >= sizeof g_state_dir) { + fprintf(stderr, "R13 operator: state directory refused: path too long\n"); + return -1; + } + } else if (scratch_dir(g_state_dir, sizeof g_state_dir, "r13-state") != 0) { + fprintf(stderr, "R13 operator: no scratch state directory\n"); + return -1; + } + if (rx_operator_dir_check(g_state_dir, 1, why, sizeof why) != 0) { + fprintf(stderr, "R13 operator: state directory refused: %s\n", why); + return -1; + } + if ((size_t)snprintf(g_control_dir, sizeof g_control_dir, "%s/control", g_state_dir) >= + sizeof g_control_dir || + strlen(g_control_dir) + 1 + strlen(RX_OPERATOR_SOCK) >= + sizeof(((struct sockaddr_un *)0)->sun_path)) { + fprintf(stderr, "R13 operator: state directory refused: socket path too long\n"); + return -1; + } + if (rx_operator_dir_check(g_control_dir, 1, why, sizeof why) != 0) { + fprintf(stderr, "R13 operator: control directory refused: %s\n", why); + return -1; + } + printf("R13 operator: state %s, control %s (operator subject %u)\n", g_state_dir, + g_control_dir, (unsigned)RX_OPERATOR_SUBJ); + return 0; +} static int start(Rig *r, int mode) { int with_aien = mode != NO_AIEN; int promotion_authority = mode != NO_PROMOTION; memset(r, 0, sizeof *r); + r->mode = mode; g_stage = 1; if (aienos_cap_start(&r->admin, &r->view) != 0) return -1; if (rx_world_init_native(&r->w, r->view, 4, RX_CRUMBS_LONG_EPISODE) != RX_OK) return -1; @@ -236,6 +409,9 @@ static int start(Rig *r, int mode) { /* R16 C6: every production subject gets a runtime-issued credential, * then the world refuses any registration that does not present one. */ if (rx_living_enroll_callers(&r->w, &r->keys) != RX_OK) return -1; + /* R16 G6: the operator, enrolled like every production subject before + * enrollment closes. It runs no reaction (docs/r16-operator-control.md). */ + if (rx_world_enroll_caller(&r->w, RX_OPERATOR_SUBJ, &r->op_cred) != RX_OK) return -1; /* Test build only: the composition and Fabric phases run inside this * World (rx_compose_attach); their subjects are enrolled here, before * enrollment closes. The production program enrolls no test subject. */ @@ -243,12 +419,36 @@ static int start(Rig *r, int mode) { if (rx_compose_enroll_callers(&r->w, &r->compose_keys) != RX_OK) return -1; #endif if (rx_world_bind_callers(&r->w) != RX_OK) return -1; - if (scratch_dir(r->generation_dir, sizeof r->generation_dir, "r13-living") != 0) return -1; + /* The generation store of this mode lives in the program's validated + * state directory; it is also the world's durable halt directory. */ + char why[320]; + if ((size_t)snprintf(r->generation_dir, sizeof r->generation_dir, "%s/gen-%s", g_state_dir, + g_mode_key[mode]) >= sizeof r->generation_dir || + rx_operator_dir_check(r->generation_dir, 1, why, sizeof why) != 0) { + fprintf(stderr, "R13 operator: generation directory refused: %s\n", why); + return -1; + } if (scratch_dir(r->home_dir, sizeof r->home_dir, "r13-home") != 0 || living_identity(r) != 0) return -1; if (rx_gen_open(r->generation_dir, &r->gen) != RX_GEN_OK) return -1; if (rx_gen_bind_authority(r->gen, rx_world_caller_check_fn, &r->w, rx_living_native_authority, r->view) != RX_GEN_OK) return -1; + /* R16 G6: the control capability, the durable halt directory, then the + * entry point, all before any object exists or any work is published. A + * stop that outlived the last start is in force from here; the program + * then serves the operator and does nothing else until it is resumed. */ + r->op_cap = mint(r, RX_OPERATOR_SUBJ, RX_WORLD_RES_CONTROL, RX_WORLD_RIGHT_HALT); + int halt_mark = rx_world_set_halt_dir(&r->w, r->generation_dir); + if (operator_open(r) != 0) return -1; + if (world_halted(r)) { + r->op_restored = 1; + atomic_store(&r->op_halt_since, now_ns()); + printf("R13 operator %s: restored STOPPED from %s (mark %d); no work until an operator " + "resume\n", g_mode_key[mode], r->generation_dir, halt_mark); + operator_release(r); + if (wait_running(r) != 0) return OP_SHUTDOWN; + operator_hold(r); + } g_stage = 2; const uint32_t R = RX_RIGHT_READ, RW = RX_RIGHT_READ | RX_RIGHT_WRITE; RxOmegaConfig oc; @@ -458,6 +658,8 @@ static int start(Rig *r, int mode) { if (rx_gpu_seat_begin(&r->w, &r->seat) != 0 || !r->seat) return -1; #endif g_stage = 7; + r->ready = 1; + operator_release(r); /* operator requests are served from here */ return 0; } @@ -487,10 +689,17 @@ static int serve(Rig *r) { RxMutation m[4] = {{r->omega.o.request, 0, seq}, {r->omega.o.request, 1, M}, {r->omega.o.request, 2, N}, {r->omega.o.request, 3, seed}}; - if (rx_world_publish_external(&r->w, r->ext_request, m, 4) <= 0) return -1; - uint64_t t = now_ns(); + int p = publish(r, r->ext_request, m, 4); + if (p != 0) return p; + uint64_t t = run_clock(r); /* a stop pauses this deadline */ while (field(r, r->omega.o.result, 0) != seq) { - if (now_ns() - t > 5000000000ull) return -1; + /* Under a stop (seen through the operator clock, no world lock in this + * spin) the request is refused or queued: it runs again on resume. */ + if (atomic_load(&r->op_halt_since) && world_halted(r)) { + if (wait_running(r) != 0) return 1; + continue; + } + if (run_clock(r) - t > 5000000000ull) return -1; spin_us(5); /* a workload does not nap between requests */ } if (field(r, r->omega.o.result, 1) != expected_digest(seed)) r->wrong++; @@ -506,8 +715,12 @@ static int serve(Rig *r) { static void *producer_main(void *arg) { Rig *r = arg; - while (!atomic_load(&r->producer_stop)) - if (serve(r) != 0) { atomic_store(&r->producer_error, 1); break; } + t_producer = 1; + while (!atomic_load(&r->producer_stop)) { + int s = serve(r); + if (s < 0) { atomic_store(&r->producer_error, 1); break; } + if (s > 0) break; /* told to stop while the world was stopped */ + } return NULL; } @@ -529,14 +742,14 @@ static int publish_placement(Rig *r, uint64_t cls) { RxMutation m[2] = {{r->aien.o.placement, 0, field(r, r->aien.o.placement, 0)+1}, {r->aien.o.placement, 1, cls}}; - return rx_world_publish_external(&r->w, r->ext_placement, m, 2) > 0 ? 0 : -1; + return publish(r, r->ext_placement, m, 2); } static int publish_goal(Rig *r, uint64_t target) { RxMutation m[3] = {{r->aien.o.goal, 0, 1}, {r->aien.o.goal, 1, rx_omega_regime(M, N)}, {r->aien.o.goal, 2, target}}; - return rx_world_publish_external(&r->w, r->ext_goal, m, 3) > 0 ? 0 : -1; + return publish(r, r->ext_goal, m, 3); } /* Is `wanted` a causal ancestor of (or equal to) `node`? Iterative, with a @@ -664,6 +877,12 @@ static int authority_sweep(Rig *r, uint64_t *swept, uint64_t *holders) { if (e.subject == RX_LIVING_PROMOTE_SUBJ && (e.rights & RX_RIGHT_PRIVILEGED & ~RX_RIGHT_PROMOTE)) return -3; + /* R16 G6: only the operator holds the world's control resource, + * with exactly the halt right; the operator holds nothing else. */ + if ((e.resource == RX_WORLD_RES_CONTROL && + (e.subject != RX_OPERATOR_SUBJ || e.rights != RX_WORLD_RIGHT_HALT)) || + (e.subject == RX_OPERATOR_SUBJ && e.resource != RX_WORLD_RES_CONTROL)) + return -5; } return 0; } @@ -764,24 +983,24 @@ static int seat_blocked(Rig *r, uint64_t after) { static uint64_t acts(Rig *r, uint32_t id) { return r->w.reactions[id].activations; } -#define FAIL(...) do { fprintf(stderr, "R13 mode %d: ", mode); \ +#define FAIL(...) do { if (atomic_load(&g_op_shutdown)) return OP_SHUTDOWN; \ + fprintf(stderr, "R13 mode %d: ", mode); \ fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); return -1; } while (0) -#define U(x) ((unsigned long long)(x)) static int run(Rig *r, int mode) { int with_aien = mode != NO_AIEN; cpu_set_t a, x; if (core_sets(&a, &x) != 0 || move_threads(&a) <= 0) FAIL("needs both core classes"); if (publish_placement(r, CLASS_A725) != 0) FAIL("placement"); - uint64_t limit = now_ns() + 60000000000ull; - while (field(r, r->omega.o.selection, 0) < 1 && now_ns() < limit) + uint64_t limit = run_clock(r) + 60000000000ull; + while (field(r, r->omega.o.selection, 0) < 1 && run_clock(r) < limit) if (serve(r) != 0) FAIL("serve"); if (field(r, r->omega.o.selection, 0) != 1) FAIL("no first selection"); uint64_t incumbent = field(r, r->omega.o.selection, 1); uint64_t incumbent_ns = 0; if (with_aien) { while (field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED && - now_ns() < limit) + run_clock(r) < limit) if (serve(r) != 0) FAIL("serve"); if (field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED) FAIL("AIEN never confirmed the incumbent cost"); @@ -818,15 +1037,18 @@ static int run(Rig *r, int mode) { } /* From here production runs on its own thread, like any workload, and * this thread only observes. Nothing below advances a faculty. */ - limit = now_ns() + 90000000000ull; + limit = run_clock(r) + 90000000000ull; int stale_injected = 0; - while (now_ns() < limit) { + while (run_clock(r) < limit) { pause_us(20); if (atomic_load(&r->producer_error)) FAIL("serve"); if (mode == STALE_GPU && !stale_injected && r->w.reactions[r->living.r_seat].state == RX_RUNNING) { /* The object the seat is writing changes generation mid-claim. */ - if (rx_world_retire(&r->w, r->living.o.output) != RX_OK) FAIL("retire"); + int rr; + while ((rr = rx_world_retire(&r->w, r->living.o.output)) == RX_ERR_HALTED) + if (wait_running(r) != 0) FAIL("retire"); + if (rr != RX_OK) FAIL("retire"); stale_injected = 1; } int step = mode == STALE_GPU ? @@ -844,10 +1066,10 @@ static int run(Rig *r, int mode) { /* The organism keeps working. With a promotion, until AIEN has a * confirmed prediction for the promoted record and has assessed the goal * on it. Without one, long enough to see production stay put. */ - uint64_t final_limit = now_ns() + 60000000000ull; + uint64_t final_limit = run_clock(r) + 60000000000ull; if (promoted) { uint64_t epoch = field(r, r->living.o.inforce, 0); - while (now_ns() < final_limit && !atomic_load(&r->producer_error) && + while (run_clock(r) < final_limit && !atomic_load(&r->producer_error) && !(field(r, r->aien.o.prediction, 1) == epoch && field(r, r->aien.o.prediction, 6) == RX_AIEN_PRED_CONFIRMED && field(r, r->aien.o.prediction, 4) == CLASS_X925 && @@ -855,15 +1077,20 @@ static int run(Rig *r, int mode) { pause_us(100); } else { uint64_t until = __atomic_load_n(&r->served, __ATOMIC_RELAXED) + 256; - while (now_ns() < final_limit && !atomic_load(&r->producer_error) && + while (run_clock(r) < final_limit && !atomic_load(&r->producer_error) && __atomic_load_n(&r->served, __ATOMIC_RELAXED) < until) pause_us(100); } stop_producer(r); if (atomic_load(&r->producer_error)) FAIL("serve"); + /* The checks below read a settled world: they wait while it is stopped. */ + if (wait_running(r) != 0) FAIL("operator shutdown"); + int quiet; + while ((quiet = rx_world_wait_quiescent(&r->w, 10000)) != RX_OK && world_halted(r)) + if (wait_running(r) != 0) FAIL("operator shutdown"); uint64_t active = 0, after_lineage = 0; rx_gen_active(r->gen, &active, &after_lineage); - if (rx_world_wait_quiescent(&r->w, 10000) != RX_OK && + if (quiet != RX_OK && mode != REVOKED_EXPERIMENT && mode != STALE_GPU) FAIL("did not quiesce"); uint64_t checked = 0; if (rx_world_verify_crumbs(&r->w, &checked) != 0) FAIL("crumbs do not verify"); @@ -1121,6 +1348,12 @@ static int run(Rig *r, int mode) { } static void stop(Rig *r) { + /* The entry point goes first: no operator request reaches a world being + * torn down. A stop still in force stays in force (and on disk). */ + atomic_store(&r->op_teardown, 1); + operator_release(r); + rx_operator_close(r->op); + r->op = NULL; stop_producer(r); if (r->acceptor_live) { atomic_store(&r->acceptor_stop, 1); @@ -1711,6 +1944,16 @@ static void receipt(int tests_ok) { size_t used = strlen(comp); if (used < sizeof comp) snprintf(comp + used, sizeof comp - used, " \"build\": \"" R13_BUILD "\",\n%s", g_argus_json); + used = strlen(comp); + if (used < sizeof comp) + snprintf(comp + used, sizeof comp - used, + " \"operator\": {\"entry_point\": \"owner-only unix socket, SO_PEERCRED, runtime-issued " + "caller credential plus RX_WORLD_RES_CONTROL halt capability " + "(docs/r16-operator-control.md)\", \"subject\": %u, \"stops\": %llu, " + "\"resumes\": %llu, \"restored_stops\": %llu, \"open_stops\": %llu, " + "\"activations_cancelled_under_stop\": %llu},\n", + (unsigned)RX_OPERATOR_SUBJ, U(g_op_stops), U(g_op_resumes), U(g_op_restored), + U(g_op_open), U(g_op_cancelled)); FILE *f = fopen(path, "w"); if (!f) return; fprintf(f, @@ -1829,10 +2072,14 @@ int main(int argc, char **argv) { #ifndef AIEN_TEST_BUILD if (argc == 2 && strcmp(argv[1], "--argus-probe") == 0) return argus_probe(); #endif - if (argc != 1) { - fprintf(stderr, "usage: %s [--argus-probe (production program only)]\n", argv[0]); + const char *state = NULL; + if (argc == 3 && strcmp(argv[1], "--state-dir") == 0) state = argv[2]; + else if (argc != 1) { + fprintf(stderr, "usage: %s [--state-dir ] [--argus-probe (production program only)]\n", + argv[0]); return 2; } + if (operator_state(state) != 0) return 2; if (seen_fit(1u << 17) != 0) return 1; int result = 0; #ifndef AIEN_TEST_BUILD @@ -1848,7 +2095,8 @@ int main(int argc, char **argv) { Rig *r = calloc(1, sizeof *r); if (!r) return 1; int rc = start(r, mode); - if (rc != 0) fprintf(stderr, "R13 %s: setup failed at stage %d\n", names[mode], g_stage); + if (rc != 0 && rc != OP_SHUTDOWN) + fprintf(stderr, "R13 %s: setup failed at stage %d\n", names[mode], g_stage); if (rc == 0) rc = run(r, mode); #if defined(AIEN_TEST_BUILD) && !defined(R13_SILICON) /* COMPOSITION-2 in the living system (host test build only), after the episode, @@ -1859,7 +2107,13 @@ int main(int argc, char **argv) { /* Fabric F5-0: host and silicon test builds (Lane 17, Lane 32). */ if (rc == 0 && mode == POSITIVE) rc = fabric_phase(r); #endif - if (rc != 0) + /* R16 G6: the crumb log shows what operator control did in this world. */ + if (r->ready && (rc == 0 || rc == OP_SHUTDOWN) && operator_audit(r) != 0 && rc == 0) { + fprintf(stderr, "R13 %s: work committed or published while the operator stop was in force\n", + names[mode]); + rc = -1; + } + if (rc != 0 && rc != OP_SHUTDOWN) fprintf(stderr, "R13 %s FAILED: plan %llu search %llu GPU %llu evidence %llu " "belief %llu selection %llu candidate %llu promotion %llu in force %llu " "result %d prepare refusal %d\n", names[mode], @@ -1871,6 +2125,18 @@ int main(int argc, char **argv) { r->promoter.result, r->living.last_refusal); if (r->admin && r->view) stop(r); free(r); + if (rc == OP_SHUTDOWN) { + /* An operator shutdown of a stopped world: the stop stays on disk, the + * next start of this mode comes up stopped. No receipt is written. */ +#ifndef AIEN_TEST_BUILD + argus_finish(); +#endif + printf("R13 operator: shutdown while stopped in %s; the stop stays in %s/gen-%s; " + "no receipt written\n", g_mode_key[mode], g_state_dir, g_mode_key[mode]); + free(g_seen); + free(g_stack); + return 3; + } if (rc != 0) { result = 1; break; } } #ifndef AIEN_TEST_BUILD diff --git a/tools/r16_qualify.sh b/tools/r16_qualify.sh index 5e9457168..b044c5596 100755 --- a/tools/r16_qualify.sh +++ b/tools/r16_qualify.sh @@ -351,6 +351,18 @@ if [ "${LV[RX_EMERGENCY]}" = PASS ] && ! grep -Fq -- "RX_EMERGENCY_STOP: PASS" " LV[RX_EMERGENCY]=FAIL fi TG[RX_EMERGENCY]=test-rx-emergency; LOGF[RX_EMERGENCY]="$RAW_DIR/rx_emergency.log" +# R16 G6 operator control by execution (docs/r16-operator-control.md section 7): the production +# program driven from outside by the operator client. Host: the integration test plus its +# mutants, both must pass. Silicon: the same test on the resident seat. Labelled apart. +run_target "$RAW_DIR/r16_operator_host.log" test-r16-operator-host +LV[R16_OP_HOST]=$(verdict "$RC" "$RAW_DIR/r16_operator_host.log" "R16 operator gate: R16_G6_OPERATOR=HOST_PASS_NON_SILICON") +TG[R16_OP_HOST]=test-r16-operator-host; LOGF[R16_OP_HOST]="$RAW_DIR/r16_operator_host.log" +run_target "$RAW_DIR/r16_operator_mutants.log" test-r16-operator-mutants +LV[R16_OP_MUTANTS]=$(verdict "$RC" "$RAW_DIR/r16_operator_mutants.log" "RX_OPERATOR_MUTANTS: PASS") +TG[R16_OP_MUTANTS]=test-r16-operator-mutants; LOGF[R16_OP_MUTANTS]="$RAW_DIR/r16_operator_mutants.log" +silicon_run r16op "$RAW_DIR/r16_operator_silicon.log" "R16 operator gate: R16_G6_OPERATOR=PASS" test-r16-operator-silicon +LV[R16_OP_SILICON]=$V +TG[R16_OP_SILICON]=test-r16-operator-silicon; LOGF[R16_OP_SILICON]="$RAW_DIR/r16_operator_silicon.log" # g6_test : status of one exercising test; a skipped or unexercised log is NOT_RUN. g6_test() { local s=${LV[$1]:-NOT_RUN} @@ -368,7 +380,7 @@ r9_crash_recovery_passing|src/runtime/rx_generation.c:rx_gen_recover:f|R9|PROXY: r10_verifier_passing|src/omega_verify.c:omega_verify_v0_structural:f|R10|PROXY: omega_verify_v0_structural is the verifier R10 reaches through rx_omega.c; R10 pass in this run is the evidence. r12_seat_loss_handling_passing|src/runtime/rx_world.c:rx_resident_seat_lost:f|R12_host,R12_silicon|rx_resident_seat_lost is the seat-loss handler (spec/r12-resident-seat.md, Seat loss). R12 host and silicon exercise it; rx_gpu_seat_kill is only the test hook and is not counted here. r14_recovery_paths_passing|src/runtime/rx_living.c:fn_restore:f|R14_host,R14_silicon|PROXY: fn_restore (generation.restore reaction) is one R14 recovery path chosen here; R14 host and silicon exercise the recovery runs. -operator_emergency_controls_passing|src/runtime/rx_world.c:rx_world_emergency_stop:f;src/runtime/rx_world.c:rx_world_emergency_resume:f;src/runtime/rx_generation.c:rx_gen_promote:f;tests/runtime/rx_r13_living.c:rx_world_set_halt_dir:t|RX_EMERGENCY,R12_host|MISSING_IMPLEMENTATION: the runtime control exists (spec/r16-operator-emergency-stop.md: rx_world_emergency_stop / _resume; authority = enrolled caller credential plus an RX_WORLD_RES_CONTROL capability with the privileged RX_RIGHT_EPOCH right, never a reaction subject; a durable sealed OPERATOR_HALT mark that the generation store obeys and a restarted world restores). RX_EMERGENCY (host, real caproot: refusals, in-flight and racing stops, store under a stop, restart, resume, nine guard mutants) and R12_host t_emergency_stop (resident seat stand-in, native AIENOS authority) exercise it. Missing: the production R13 program does not wire it (no rx_world_set_halt_dir, no operator entry point), so no operator can reach it on the candidate; no silicon run exercises a stop. +operator_emergency_controls_passing|src/runtime/rx_world.c:rx_world_emergency_stop:f;src/runtime/rx_world.c:rx_world_emergency_resume:f;src/runtime/rx_world.c:rx_world_operator_authorize:f;src/runtime/rx_generation.c:rx_gen_promote:f;src/runtime/rx_operator.c:rx_operator_open:f;tests/runtime/rx_r13_living.c:operator_open:f;tests/runtime/rx_r13_living.c:operator_audit:f|RX_EMERGENCY,R12_host,R16_OP_HOST,R16_OP_MUTANTS,R16_OP_SILICON|The runtime control (spec/r16-operator-emergency-stop.md: rx_world_emergency_stop / _resume; authority = enrolled caller credential plus an RX_WORLD_RES_CONTROL capability with the privileged RX_RIGHT_EPOCH right, never a reaction subject; a durable sealed OPERATOR_HALT mark that the generation store obeys and a restarted world restores) and its operator entry point in the production R13 program (docs/r16-operator-control.md: owner-only socket rx_operator_open, per-world credential and capability, generation store directory as the durable halt directory, restored stop before any work). Presence of these definitions proves nothing by itself: the item is operated only by execution. RX_EMERGENCY (host, in-process) and R12_host t_emergency_stop cover the runtime; R16_OP_HOST (test-r16-operator-host) starts the production host program and drives stop, status, resume, revoke and shutdown from outside through build/rx_operator, checking replies, the state directory and the crumb-log audit the program prints (no COMMIT or EXTERNAL under a stop); R16_OP_MUTANTS rebuilds the production program from mutated copies (wiring missing, wiring in a comment, unused call, handler disconnected, success reply without a transition, unauthorized resume accepted, and others) and requires the test to fail on each; R16_OP_SILICON is the same test on build/rx_r13_living_silicon (resident GB10 seat, no SIGKILL phase). Host and silicon are separate tests: the item is not PASS without the silicon run. Not covered: effects already outside the world when the stop lands (spec section 7.4), another process of the same uid deleting the mark while no program runs (spec section 7.3). benchmark_reference_paths_seq_passing|src/runtime/rx_seq_reference.c:rx_seq_pulse:f|R15_parity_host,R15_parity_silicon|Spec line 183 names rx_seq_reference as class D reference oracle. R15 parity host and silicon compare the reaction path with it.' declare -A G6S G6LIST=""; G6ALL=""; G6MISSING=0 diff --git a/tools/rx_operator.c b/tools/rx_operator.c new file mode 100644 index 000000000..d5d27e681 --- /dev/null +++ b/tools/rx_operator.c @@ -0,0 +1,107 @@ +/* rx_operator: the operator's client for a running production world + * (docs/r16-operator-control.md). It reads the operator credential file, + * sends one request to the program's owner-only socket and prints the one + * reply line. It decides nothing: the world authority does. + * + * rx_operator --control /control [reason] + * rx_operator --cred [reason] present another credential file + * rx_operator --control --raw '' send a line as is (tests) + * + * : status | stop | resume | revoke-cap | revoke | shutdown + * Exit: 0 reply OK, 1 any other reply, 2 usage, no credential, or no world. */ +#include +#include +#include +#include +#include +#include +#include +#include + +static int usage(void) { + fprintf(stderr, "usage: rx_operator (--control | --cred ) " + "(status|stop [reason]|resume|revoke-cap|revoke|shutdown | --raw )\n"); + return 2; +} + +int main(int argc, char **argv) { + const char *control = NULL, *cred_file = NULL, *raw = NULL, *cmd = NULL, *reason = NULL; + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--control") == 0 && i + 1 < argc) control = argv[++i]; + else if (strcmp(argv[i], "--cred") == 0 && i + 1 < argc) cred_file = argv[++i]; + else if (strcmp(argv[i], "--raw") == 0 && i + 1 < argc) raw = argv[++i]; + else if (!cmd) cmd = argv[i]; + else if (!reason) reason = argv[i]; + else return usage(); + } + if ((!control && !cred_file) || (!raw && !cmd) || (raw && cmd)) return usage(); + char path[512]; + if (cred_file) snprintf(path, sizeof path, "%s", cred_file); + else snprintf(path, sizeof path, "%s/operator.cred", control); + FILE *f = fopen(path, "r"); + if (!f) { fprintf(stderr, "rx_operator: no credential at %s: %s\n", path, strerror(errno)); return 2; } + char line[256], sock[256] = "", secret[80] = ""; + unsigned subject = 0, cap_id = 0; + unsigned long long gen = 0, cap_gen = 0; + int have = 0; + if (!fgets(line, sizeof line, f) || strcmp(line, "aien-operator-credential v1\n") != 0) { + fclose(f); + fprintf(stderr, "rx_operator: %s is not an operator credential file\n", path); + return 2; + } + while (fgets(line, sizeof line, f)) { + if (sscanf(line, "socket %255s", sock) == 1) have |= 1; + else if (sscanf(line, "subject %u", &subject) == 1) have |= 2; + else if (sscanf(line, "cred %llu %79s", &gen, secret) == 2) have |= 4; + else if (sscanf(line, "cap %u %llu", &cap_id, &cap_gen) == 2) have |= 8; + } + fclose(f); + if (have != 15) { fprintf(stderr, "rx_operator: %s is incomplete\n", path); return 2; } + if (control) snprintf(sock, sizeof sock, "%s/operator.sock", control); + char req[1024]; + int n; + if (raw) n = snprintf(req, sizeof req, "%s\n", raw); + else if (reason) + n = snprintf(req, sizeof req, "aien-operator v1 %s subject=%u gen=%llu secret=%s cap=%u:%llu " + "reason=%s\n", cmd, subject, gen, secret, cap_id, cap_gen, reason); + else + n = snprintf(req, sizeof req, "aien-operator v1 %s subject=%u gen=%llu secret=%s cap=%u:%llu\n", + cmd, subject, gen, secret, cap_id, cap_gen); + memset(secret, 0, sizeof secret); + if (n <= 0 || (size_t)n >= sizeof req) return usage(); + struct sockaddr_un a; + memset(&a, 0, sizeof a); + a.sun_family = AF_UNIX; + if (strlen(sock) >= sizeof a.sun_path) { fprintf(stderr, "rx_operator: socket path too long\n"); return 2; } + memcpy(a.sun_path, sock, strlen(sock) + 1); + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0 || connect(fd, (struct sockaddr *)&a, sizeof a) != 0) { + fprintf(stderr, "rx_operator: no world is serving %s: %s\n", sock, strerror(errno)); + return 2; + } + /* The program answers a request once the world it is setting up is ready. */ + struct timeval tv = {60, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); + for (int off = 0; off < n;) { + ssize_t w = send(fd, req + off, (size_t)(n - off), MSG_NOSIGNAL); + if (w < 0 && errno == EINTR) continue; + if (w <= 0) { fprintf(stderr, "rx_operator: send: %s\n", strerror(errno)); return 2; } + off += (int)w; + } + memset(req, 0, sizeof req); + shutdown(fd, SHUT_WR); + char reply[2048]; + size_t got = 0; + while (got < sizeof reply - 1) { + ssize_t r = read(fd, reply + got, sizeof reply - 1 - got); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + got += (size_t)r; + } + close(fd); + reply[got] = 0; + if (!got) { fprintf(stderr, "rx_operator: no reply\n"); return 2; } + fputs(reply, stdout); + if (reply[got - 1] != '\n') fputc('\n', stdout); + return strncmp(reply, "aien-operator v1 OK", 19) == 0 ? 0 : 1; +} From a99810ade38879a9d7db5dd13353aab935504cbf Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 5 Oct 2026 17:09:57 -0500 Subject: [PATCH 3/6] R16 G6: operator stop holds through the whole episode, counted and stable A stop that catches a seat result now counts it (stats.resident_halted, halt status cancelled=) and the R13 episode check subtracts those re-run claims. A HALTED seat result is not a transport fault; a stop after the episode keeps the world up until the operator resumes it. The host test stops first, checks every refusal while stopped, and cycles until a stop has caught in-flight work. Map rows OM-285/OM-286 classified (B). host-suites-2 declares the operator tests Spark-only (both core classes). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/host-suites-2.yml | 5 ++ docs/r16-operator-control.md | 9 ++- spec/r16-orchestrator-retirement-map.md | 20 +++++++ src/runtime/rx_operator.c | 3 +- src/runtime/rx_world.c | 5 ++ src/runtime/rx_world.h | 2 + tests/runtime/rx_operator_host.sh | 73 +++++++++++++++---------- tests/runtime/rx_r13_living.c | 28 ++++++++-- 8 files changed, 108 insertions(+), 37 deletions(-) diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index 313adae71..30606a2c3 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -51,6 +51,11 @@ name: Host suites 2 # rx-host.yml only builds the R13/R14 hosts. Spark -j1: all three PASS. # rx-host.yml runs R16-G3 checks 1-3 (sources, link map, embedded names) on # the host and silicon builds and declares every Spark/chip-only run SKIP; +# test-r16-operator-host, test-r16-operator-mutants: environment, same reason. +# They start the production R13 host program and drive it through its +# operator socket; every world runs an R13 episode ("needs both core +# classes", tests/runtime/rx_r13_living.c run()). Spark -j1: host 32 s, +# mutants 95 s, both PASS; test-r16-operator-silicon is a chip target; # test-polyglot: environment. mk/polyglot.mk builds its -O3 flavor with # -mcpu=native next to -march=armv8.6-a+...; on the runner (Neoverse N2) gcc # resolves native to a CPU that conflicts with that -march and -Werror stops diff --git a/docs/r16-operator-control.md b/docs/r16-operator-control.md index 5ba2f991e..c7ff83222 100644 --- a/docs/r16-operator-control.md +++ b/docs/r16-operator-control.md @@ -105,7 +105,7 @@ same `halt_authorize` the stop and resume use, under the same locks, added to | command | world call | reply on success | |---|---|---| -| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= crumbs= reactions=` plus program counters `served= production_commits= inforce= active_generation=` | +| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= cancelled= crumbs= reactions=` plus program counters `served= production_commits= inforce= active_generation=` | | `stop [reason]` | `rx_world_emergency_stop` | `OK state=stopped seq= crumb= durable=`; a second stop: `ALREADY` with no new crumb | | `resume` | `rx_world_emergency_resume` | `OK state=running seq=`; a running world: `NOT_STOPPED` | | `revoke-cap` | authorize, then `aienos_cap_revoke` of the presented control capability by the authority's office | `OK revoked=capability`; afterwards every request with that capability is `REFUSED reason=authority` | @@ -159,7 +159,12 @@ earlier world or an earlier program start fails the constant-time caller check published again after resume, and the end-of-mode checks wait while the world is stopped. A durable generation proposal or promotion that the store refuses because of the stop (`RX_GEN_ERR_HALTED`) is not an outcome: the activation waits - and posts it again after the resume (`halted_wait`, `src/runtime/rx_living.c`). A stop therefore delays the episode; it does not fail it. + and posts it again after the resume (`halted_wait`, `src/runtime/rx_living.c`). A world + whose episode is done is not torn down while stopped: the program waits for the resume + (or `shutdown`) before it audits and ends the mode. A seat result caught by a stop is + claimed again after the resume; the world counts those claims (`stats.resident_halted`) + and the episode check subtracts them before it compares claims with trials. + A stop therefore delays the episode and leaves its outcome unchanged. * Evidence: at the end of every mode the program reads its crumb log (the canonical evidence, spec §4) and prints `R13 operator : stops S resumes R restored X open O; under stop: commits 0 externals 0 cancelled C`. Any COMMIT or EXTERNAL crumb diff --git a/spec/r16-orchestrator-retirement-map.md b/spec/r16-orchestrator-retirement-map.md index a3f9845ed..518657502 100644 --- a/spec/r16-orchestrator-retirement-map.md +++ b/spec/r16-orchestrator-retirement-map.md @@ -383,6 +383,8 @@ any production binary); in-file Rust `#[cfg(test)]` modules likewise. | OM-282 | omega | `tools/estimation/est6dev.c` | 251 | `run_g1` | EST v6 development G1 scoring walk | - | N | false | N: walk: scores recorded ticks in order (data ticks, not a scheduler tick), without wait or hand-off; offline development tool, not on the production path | `for (size_t t = 0; t < tk->n; t++) {` | | OM-283 | omega | `tools/estimation/test_est_json.c` | 62,74 | `jvalue` | JSON object/array parse in the strict-JSON test validator | test / reference path | D | false | test of the EST strict-JSON receipt rules: recursive JSON parse without wait or hand-off; not built into any production binary | `else for (;;) {` | | OM-284 | omega | `tools/estimation/test_est_json.c` | 101 | `slurp` | whole-file read in the strict-JSON test validator | test / reference path | D | false | test of the EST strict-JSON receipt rules: file read into a growing buffer until end of file, without wait or hand-off; not built into any production binary | `for (;;) {` | +| OM-285 | omega | `src/runtime/rx_operator.c` | 319 | `listener_main` | operator control socket listener | R16 G6 operator entry point of the production program | B | true | explicit deterministic operator mechanism: waits (poll) for one operator connection on the owner-only socket, answers that one request through the world authority, waits for the next; the operator decides every stop and resume, the loop decides no faculty order (docs/r16-operator-control.md) | `for (;;) {` | +| OM-286 | omega | `tests/runtime/rx_r13_living.c` | 311 | `publish` | production request publication waits out an operator stop | R16 G6 operator stop honoured by the production request stream | B | true | operator emergency stop mechanism: a publication refused with RX_ERR_HALTED waits until the operator resumes (or shuts the program down) and publishes the same request again; any other result returns at once; decides no faculty order | `for (;;) {` | | SC-001 | aien-sovereign-core | `benchmarks/crates/bench_apples_to_apples/src/engine_max.rs` | 55 | `start` | test/benchmark loop (while:body:sleep) | test / reference path | D | false | test, benchmark or example code; not built into any production binary | `while start.elapsed() < timeout {` | | SC-002 | aien-sovereign-core | `benchmarks/crates/bench_apples_to_apples/src/telemetry.rs` | 96 | `start` | test/benchmark loop (while:body:tick) | test / reference path | D | false | test, benchmark or example code; not built into any production binary | `while !stop_clone.load(Ordering::Relaxed) {` | | SC-003 | aien-sovereign-core | `benchmarks/crates/bench_apples_to_apples/src/telemetry.rs` | 168 | `enforce_thermal_cooldown` | test/benchmark loop (while:body:sleep) | test / reference path | D | false | test, benchmark or example code; not built into any production binary | `while start.elapsed() < max_wait {` | @@ -914,3 +916,21 @@ After: `sites=521 unclassified=0 question=0 bad_class=0 a_reachable=0 stale=0 map_errors=0 skipped=0 -> PASS`. (omega code `79a805d`; this map change touches no code, so the CAND-2 omega commit is `79a805d`.) This is the G1/G2 inventory for the CAND-2 code, not an R16 qualification receipt. + +### 8.7 Update 2026-10-05 (cand3 lane ESTOP): operator control of the production program + +The CAND-3 operator-control change (branch `cand3/operator-control`, docs/r16-operator-control.md) +adds two loop sites. Scan set: this omega tree, and clean checkouts of the §8.6 commits for the +other repos (aien-sovereign-core at `286fa9b`, which differs from `2eec75b` only in `.crumb` and +`omega.lock`; aegis-runtime `f4e8709`; aienos `bbad5e4`; physics `6d7cf0d`). + +Before: `sites=523 unclassified=2 question=0 bad_class=0 a_reachable=0 stale=0 map_errors=0 skipped=0 -> FAIL`. + +Reconciliation, each row from reading the loop (no tool, pattern, threshold or class rule changed): +- OM-285, class B: the operator socket listener (`listener_main`, `src/runtime/rx_operator.c`). +- OM-286, class B: the production request publication waiting out an operator stop (`publish`, + `tests/runtime/rx_r13_living.c`). +Neither sequences faculties: each waits for the operator or for the world to run again. + +After: `sites=523 unclassified=0 question=0 bad_class=0 a_reachable=0 stale=0 map_errors=0 skipped=0 -> PASS`. +This is the G1/G2 inventory for the CAND-3 operator-control code, not an R16 qualification receipt. diff --git a/src/runtime/rx_operator.c b/src/runtime/rx_operator.c index b1b79c788..ffaab4d3a 100644 --- a/src/runtime/rx_operator.c +++ b/src/runtime/rx_operator.c @@ -221,9 +221,10 @@ static void handle(RxOperator *op, Req *q, char *out, size_t n) { rx_world_halt_status(w, &h); if (status) { int used = snprintf(out, n, "OK state=%s restored=%d seq=%llu durable=%d refused=%llu " - "crumbs=%llu reactions=%u", + "cancelled=%llu crumbs=%llu reactions=%u", h.halted ? "stopped" : "running", h.restored ? 1 : 0, (unsigned long long)h.seq, h.durable, (unsigned long long)h.refused, + (unsigned long long)h.cancelled, (unsigned long long)__atomic_load_n(&w->n_crumbs, __ATOMIC_RELAXED), (unsigned)__atomic_load_n(&w->n_reactions, __ATOMIC_RELAXED)); if (op->cfg.describe && used > 0 && (size_t)used + 2 < n) { diff --git a/src/runtime/rx_world.c b/src/runtime/rx_world.c index be82545f2..7f95f2520 100644 --- a/src/runtime/rx_world.c +++ b/src/runtime/rx_world.c @@ -1067,6 +1067,7 @@ int rx_world_set_halt_dir(RxWorld *w, const char *dir) { h.restored = true; h.durable = 1; h.refused = w->halt.refused; + h.cancelled = w->halt.cancelled; h.crumb = halt_crumb(w, RX_CRUMB_OPERATOR_STOP, h.cap, h.reason, 0); w->halt = h; w->halted = true; @@ -1096,6 +1097,7 @@ int rx_world_emergency_stop(RxWorld *w, uint32_t subject, const RxCallerCred *cr h.reason = reason; h.t_ns = realtime_ns(); h.refused = w->halt.refused; + h.cancelled = w->halt.cancelled; h.crumb = halt_crumb(w, RX_CRUMB_OPERATOR_STOP, cap, reason, 0); w->halt = h; w->halted = true; /* in force before any disk work */ @@ -1847,6 +1849,7 @@ static void run_one(RxWorld *w, uint32_t rid, uint32_t worker) { k.t_end_ns = now_ns(); crumb_append(w, &k); w->halt.refused++; + w->halt.cancelled++; /* A refused activation is not spent: it must not count toward the * episode budget, or the re-run could be quarantined instead. */ if (r->episode_activations) r->episode_activations--; @@ -2568,7 +2571,9 @@ int rx_resident_accept(RxWorld *w) { crumb_append(w, &k); r->resident_seat = false; w->stats.resident_closed++; + w->stats.resident_halted++; w->halt.refused++; + w->halt.cancelled++; if (r->episode_activations) r->episode_activations--; /* not spent */ r->rearm = true; end_activation(w, (uint32_t)rid); diff --git a/src/runtime/rx_world.h b/src/runtime/rx_world.h index 9b4806eda..66a195354 100644 --- a/src/runtime/rx_world.h +++ b/src/runtime/rx_world.h @@ -444,6 +444,7 @@ typedef struct { uint64_t desc_rejected; uint64_t resident_claims; /* claims posted to a resident seat */ uint64_t resident_closed; /* claims ended: committed, refused, or lost */ + uint64_t resident_halted; /* of those closed, results caught by an operator stop (re-run on resume) */ uint64_t deferrals; /* activations that handed an effect to a durable executor */ uint64_t seat_losses; /* times a seat was declared lost */ /* R15 instrumentation. Counted, never inferred. */ @@ -529,6 +530,7 @@ typedef struct { uint64_t t_ns; /* CLOCK_REALTIME of the stop */ int durable; /* 1 mark on disk; 0 no halt dir; < 0 -errno of the write */ uint64_t refused; /* activations, publications, seat results, creates and retires refused */ + uint64_t cancelled; /* of those, activations and seat results caught by a stop, re-run on resume */ } RxHaltStatus; /* Durable recorder (M20 Cortex). Called with the world mutex held, once per diff --git a/tests/runtime/rx_operator_host.sh b/tests/runtime/rx_operator_host.sh index 99d3a45c8..2e1f398d8 100644 --- a/tests/runtime/rx_operator_host.sh +++ b/tests/runtime/rx_operator_host.sh @@ -68,6 +68,11 @@ finish() { elif [ "$SEAT" = silicon ]; then gate=PASS else gate=HOST_PASS_NON_SILICON; fi receipt "$gate" + if [ "$FAILS" -gt 0 ]; then # keep the program logs of a failed run for diagnosis + local keep="$HERE/build/r16-operator/failed-$SEAT-$(date -u +%Y%m%dT%H%M%SZ)-$$" + mkdir -p "$keep" && cp "$W"/*.log "$keep"/ 2>/dev/null + echo "R16 operator: program logs kept in $keep" + fi echo "R16 operator: $CHECKS checks, $FAILS failures, $SKIPS skipped ($SEAT, phases: $PHASES)" echo "R16 operator gate: R16_G6_OPERATOR=$gate" [ "$FAILS" = 0 ] @@ -170,19 +175,29 @@ if [[ " $PHASES " == *" control "* ]] || [[ " $PHASES " == *" restart "* ]]; the check "control: the positive world opens the operator entry point" 'wait_world "$S" positive' C="$S/control"; cp "$C/operator.cred" "$W/cred-positive" forge "$W/cred-positive" "$W/forged" 's/^\(cred [0-9]* \)\(.\)\(.*\)$/\1\3\2/' # rotated secret: right length, wrong bytes - op --control "$C" status - check "control: authorized status, world running, no stop yet" 'has "OK state=running" && [ "$(kv seq)" = 0 ]' + forge "$W/cred-positive" "$W/wrongcap" 's/^cap \([0-9]*\) /cap 1\1 /' + forge "$W/cred-positive" "$W/wrongsubj" 's/^subject 70$/subject 61/' fi if [[ " $PHASES " == *" control "* ]]; then + # Authorized stop, sent the moment the world exists: the program answers it as soon + # as setup is done, before the episode has done its work, so the promotion is still + # ahead and cannot happen under the stop. + op --control "$C" stop 7 + check "stop: authorized stop accepted, durable, the first stop of this world" 'has "OK state=stopped" && [ "$(kv seq)" = 1 ] && [ "$(kv durable)" = 1 ]' + M="$S/gen-positive/OPERATOR_HALT" + check "stop: sealed mark in the generation store directory" \ + 'head -n 1 "$M" | grep -qx "aien-operator-halt v1" && grep -qx "reason 7" "$M" && grep -qx "subject 70" "$M" && sealed "$M"' + op --control "$C" status + sv1=$(kv served); pc1=$(kv production_commits); ag1=$(kv active_generation); pr1=$(kv promotion); if1=$(kv inforce) + check "stop: status says stopped, the promotion has not happened yet" 'has "state=stopped" && [ "$pr1" = 0 ] && [ "$if1" = 0 ] && [ -n "$sv1" ]' + # Unauthorized requests: each refused, nothing changes, no state revealed. op --cred "$W/forged" --control "$C" stop check "unauthorized: forged secret, stop REFUSED identity" 'has "REFUSED reason=identity" && ! has state=' op --cred "$W/forged" --control "$C" status check "unauthorized: forged secret, status REFUSED identity (no state revealed)" 'has "REFUSED reason=identity" && ! has state=' - forge "$W/cred-positive" "$W/wrongcap" 's/^cap \([0-9]*\) /cap 1\1 /' op --cred "$W/wrongcap" --control "$C" stop check "unauthorized: another capability, stop REFUSED authority" 'has "REFUSED reason=authority"' - forge "$W/cred-positive" "$W/wrongsubj" 's/^subject 70$/subject 61/' op --cred "$W/wrongsubj" --control "$C" stop check "unauthorized: a reaction subject (61) with the operator secret, REFUSED identity" 'has "REFUSED reason=identity"' op --control "$C" --raw "aien-operator v1 stop" @@ -195,29 +210,16 @@ if [[ " $PHASES " == *" control "* ]]; then else skip "unauthorized: peer of another uid (needs sudo -n)" fi - op --control "$C" status - check "unauthorized: after every refusal the world still runs, no stop taken, no mark" \ - 'has "OK state=running" && [ "$(kv seq)" = 0 ] && [ ! -e "$S/gen-positive/OPERATOR_HALT" ]' - - # Authorized stop: the world freezes; the promotion cannot happen under it. - op --control "$C" stop 7 - check "stop: authorized stop accepted, durable" 'has "OK state=stopped" && [ "$(kv seq)" = 1 ] && [ "$(kv durable)" = 1 ]' - M="$S/gen-positive/OPERATOR_HALT" - check "stop: sealed mark in the generation store directory" \ - 'head -n 1 "$M" | grep -qx "aien-operator-halt v1" && grep -qx "reason 7" "$M" && grep -qx "subject 70" "$M" && sealed "$M"' - op --control "$C" status; S1=$REPLY_ - sv1=$(kv served); pc1=$(kv production_commits); ag1=$(kv active_generation); pr1=$(kv promotion); if1=$(kv inforce) - check "stop: status says stopped, the promotion has not happened yet" 'has "state=stopped" && [ "$pr1" = 0 ] && [ "$if1" = 0 ] && [ -n "$sv1" ]' - sleep 2 - op --control "$C" status - check "stop: two seconds later nothing was served, committed or promoted" \ - '[ "$(kv served)" = "$sv1" ] && [ "$(kv production_commits)" = "$pc1" ] && [ "$(kv active_generation)" = "$ag1" ] && [ "$(kv promotion)" = 0 ] && [ "$(kv inforce)" = 0 ]' op --cred "$W/forged" --control "$C" resume - check "stop: a forged resume is REFUSED and the world stays stopped" 'has "REFUSED reason=identity"' + check "unauthorized: a forged resume is REFUSED" 'has "REFUSED reason=identity"' op --cred "$W/wrongcap" --control "$C" resume - check "stop: a resume with another capability is REFUSED" 'has "REFUSED reason=authority"' + check "unauthorized: a resume with another capability is REFUSED" 'has "REFUSED reason=authority"' + op --cred "$W/wrongsubj" --control "$C" resume + check "unauthorized: a resume by a reaction subject is REFUSED" 'has "REFUSED reason=identity"' + sleep 2 op --control "$C" status - check "stop: still stopped after the refused resumes" 'has "state=stopped" && [ "$(kv served)" = "$sv1" ]' + check "stop: after every refusal and two seconds, still the same stop; nothing served, committed or promoted" \ + 'has "state=stopped" && [ "$(kv seq)" = 1 ] && [ "$(kv served)" = "$sv1" ] && [ "$(kv production_commits)" = "$pc1" ] && [ "$(kv active_generation)" = "$ag1" ] && [ "$(kv promotion)" = 0 ] && [ "$(kv inforce)" = 0 ] && [ -e "$M" ]' op --control "$C" stop 8 check "repeat: a second stop answers ALREADY, same stop" 'has "ALREADY state=stopped" && [ "$(kv seq)" = 1 ]' op --control "$C" resume @@ -231,16 +233,31 @@ if [[ " $PHASES " == *" control "* ]]; then ok=0 for i in $(seq 1 200); do op --control "$C" status; [ "$(kv served)" != "$sv1" ] && { ok=1; break; }; sleep 0.05; done check "resume: production serves again after the resume" '[ $ok = 1 ]' + op --cred "$W/forged" --control "$C" stop + check "unauthorized: a forged stop of the running world is REFUSED identity" 'has "REFUSED reason=identity"' + op --cred "$W/wrongcap" --control "$C" stop + check "unauthorized: a stop of the running world with another capability is REFUSED authority" 'has "REFUSED reason=authority"' + op --control "$C" status + check "unauthorized: after the refused stops the world still runs, no new stop, no mark" \ + 'has "OK state=running" && [ "$(kv seq)" = 1 ] && [ ! -e "$M" ]' # In-flight work under production load: stop and resume while requests run. - cycles=0 - for i in $(seq 1 12); do - op --control "$C" stop 9 || break + # At least 12 cycles, then on until a stop has caught an activation + # computing (status cancelled=, at most 400 cycles). Every request carries + # the positive world's own credential, so a stop can never land in the next world: + # once the positive world ends, the next request is REFUSED and the loop ends. + cycles=0; inflight=0 + for i in $(seq 1 400); do + op --cred "$W/cred-positive" --control "$C" stop 9 || break has "OK state=stopped" || break sleep 0.05 - op --control "$C" resume || break + op --cred "$W/cred-positive" --control "$C" resume || break has "OK state=running" || break cycles=$((cycles + 1)) + if [ $cycles -ge 12 ]; then + op --cred "$W/cred-positive" --control "$C" status || break + inflight=$(kv cancelled); [ "${inflight:-0}" -ge 1 ] && break + fi done check "in-flight: at least 6 stop/resume cycles while the positive world runs ($cycles)" '[ $cycles -ge 6 ]' check "positive world: the promotion happens after the resume (generation advanced)" 'wait_line "$LA" "R13 positive: generation"' diff --git a/tests/runtime/rx_r13_living.c b/tests/runtime/rx_r13_living.c index 893c298db..23bb60e90 100644 --- a/tests/runtime/rx_r13_living.c +++ b/tests/runtime/rx_r13_living.c @@ -828,14 +828,20 @@ static uint64_t production_between(Rig *r, uint64_t lo, uint64_t hi) { /* Ring transport only: accept the seat's completion notices into the world. * It carries no meaning and decides nothing. */ +/* R16 G6: a seat result refused because an operator stop is in force + * (RX_ERR_HALTED) is not a transport fault: the world re-projected the window + * and runs the activation again on resume (spec section 3). */ static int progress(Rig *r) { #ifdef R13_SILICON int rc = rx_resident_accept(&r->w); - return rc == RX_ERR_NOT_FOUND || rc == RX_OK ? 0 : rc; + return rc == RX_ERR_NOT_FOUND || rc == RX_OK || rc == RX_ERR_HALTED ? 0 : rc; #else int rc = rx_resident_seat_step(&r->w); - if (rc == 1) return rx_resident_accept(&r->w); - return rc < 0 ? rc : 0; + if (rc == 1) { + rc = rx_resident_accept(&r->w); + return rc == RX_ERR_HALTED ? 0 : rc; + } + return rc < 0 && rc != RX_ERR_HALTED ? rc : 0; #endif } @@ -1190,12 +1196,14 @@ static int run(Rig *r, int mode) { field(r, r->aien.o.experiment_belief, 2) != RX_AIEN_EXP_SUPPORTED || field(r, r->aien.o.experiment_belief, 3) != RX_LIVING_TRIALS || field(r, r->living.o.evidence, 4) != RX_LIVING_TRIALS || - r->w.stats.resident_claims != RX_LIVING_TRIALS || + /* A seat result caught by an operator stop is claimed again on resume. */ + r->w.stats.resident_claims - r->w.stats.resident_halted != RX_LIVING_TRIALS || r->w.reactions[r->living.r_seat].commits != RX_LIVING_TRIALS || r->w.reactions[r->living.r_candidate].commits != 1 || r->w.reactions[r->promoter.reaction].commits != 1) - FAIL("episode shape: claims %llu seat commits %llu trials %llu", - U(r->w.stats.resident_claims), U(r->w.reactions[r->living.r_seat].commits), + FAIL("episode shape: claims %llu (%llu caught by a stop) seat commits %llu trials %llu", + U(r->w.stats.resident_claims), U(r->w.stats.resident_halted), + U(r->w.reactions[r->living.r_seat].commits), U(field(r, r->living.o.evidence, 4))); if (after_lineage != lineage + 1 || active == before_generation || field(r, r->living.o.inforce, 7) != active) @@ -2107,6 +2115,14 @@ int main(int argc, char **argv) { /* Fabric F5-0: host and silicon test builds (Lane 17, Lane 32). */ if (rc == 0 && mode == POSITIVE) rc = fabric_phase(r); #endif + /* R16 G6: a world is not torn down under an operator stop. A stop that lands + * after the episode keeps the world up until the operator resumes it (or + * shuts the program down); only then is the mode audited and ended. */ + if (rc == 0 && r->ready && world_halted(r)) { + printf("R13 operator %s: stopped after its episode; waiting for an operator resume\n", + g_mode_key[mode]); + if (wait_running(r) != 0) rc = OP_SHUTDOWN; + } /* R16 G6: the crumb log shows what operator control did in this world. */ if (r->ready && (rc == 0 || rc == OP_SHUTDOWN) && operator_audit(r) != 0 && rc == 0) { fprintf(stderr, "R13 %s: work committed or published while the operator stop was in force\n", From 8ba92a4e37c61b3a281cededce775f3747051557 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 5 Oct 2026 17:51:31 -0500 Subject: [PATCH 4/6] crumb compile: R16 G6 operator control Co-Authored-By: Claude Opus 5.5 --- docs/.crumb | 12 ++++++------ spec/.crumb | 8 ++++---- src/.crumb | 16 ++++++++-------- src/runtime/.crumb | 10 +++++----- tests/runtime/.crumb | 10 +++++----- 5 files changed, 28 insertions(+), 28 deletions(-) diff --git a/docs/.crumb b/docs/.crumb index b1461bf83..fa70e27df 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -76,7 +76,7 @@ }, { "digest": "56a5a999ce726e90d89c1c88b9e20c81857c8e6ee82af8d651ac80ea70e2c46d", - "last_commit": "25311c0", + "last_commit": "38a6a56", "name": "estimation", "purpose": "Directory docs/estimation. Purpose not yet described by a human." }, @@ -118,14 +118,14 @@ } ], "children_root": "sha256:ce53c9c7f75a7d122d6a926bb304b2df1bd0730693b54887b842ad3559bafe83", - "compiled_at": "2026-10-05T15:40:51Z", + "compiled_at": "2026-10-05T22:51:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:01a9aa128e136ecccdaca33b6babef24d4011a95c2ca1a5dd839d84e2841ce3d", + "digest": "sha256:a27037a2239070b399ca6809105a8cc535d5796374e8a41fce3b2803018abfcc", "evidence_files": 34, "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc", - "files": 112, - "generated_at_commit": "25311c0c2aee4eb4991052115d9ad91f5b4d2a1e", - "source_tree": "sha256:cb189c97510cfdc47126abee0105eb8dba61520c3f654644838eba1f08a930ad" + "files": 113, + "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", + "source_tree": "sha256:49c9c5208e007290cf8f3db38a2eead1b0600bd2f13d09e56f0d12293cccb7d4" }, "owner_lane": "", "provenance": { diff --git a/spec/.crumb b/spec/.crumb index eb6e3f7ae..f9c5b9e2f 100644 --- a/spec/.crumb +++ b/spec/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:6834a3241647d3a098283d4eafedbdb1428dfa4d834f9ed5f22025b6d2303093", - "compiled_at": "2026-10-05T17:35:25Z", + "compiled_at": "2026-10-05T22:51:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:4dde878eff597b3669b7dafeb572ba3a560c51ac52d99681524745684c45b258", + "digest": "sha256:f4bca55badfbb82836dfbe4ae2f44ecb57198e4a9ce4a02cbf3e534b23dcecbd", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 56, - "generated_at_commit": "b3f7c97a22a105748d4dc4cf5bd34ca2e912f853", - "source_tree": "sha256:cf38443997fd6250145703f37288a5141786e8d878db262612464e33a5663d17" + "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", + "source_tree": "sha256:23967b4782de139f3ecdd4965c186128817ed700918ff0567b3bbbf77a0bf70f" }, "owner_lane": "", "provenance": { diff --git a/src/.crumb b/src/.crumb index 0eb185b4e..1a044a42d 100644 --- a/src/.crumb +++ b/src/.crumb @@ -133,8 +133,8 @@ "purpose": "Directory src/polyglot. Purpose not yet described by a human." }, { - "digest": "7927099dac3838db8f33a305a185873d9610c7c496fc3763ec9e5dc9e901bb9d", - "last_commit": "bf89cda", + "digest": "76504ddb5dcdf70af8f8ace77bed616398f7550fa4a290bca68fe445ad62aba6", + "last_commit": "def0a0d", "name": "runtime", "purpose": "Directory src/runtime. Purpose not yet described by a human." }, @@ -169,15 +169,15 @@ "purpose": "Directory src/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:100d089dae58ac28d48f3c8e0426a60913380b117fd49f9e54ee33620370ff25", - "compiled_at": "2026-10-05T20:10:00Z", + "children_root": "sha256:babd73b24df0569f6fc6c49d3180b813d919485a8065aa430642eb56be95c568", + "compiled_at": "2026-10-05T22:51:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:216a1cd73e993694a7c2ff9580d2b9ec299ddb0876e29ddcaf23e35844ef73bd", + "digest": "sha256:cab0414a38bfa4deff6e1ef2006ff703d59434440dca34666f432701e9bdfb5c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 406, - "generated_at_commit": "f8ce768210e58d33e675a7bbae2208ccbfc58db7", - "source_tree": "sha256:d2d655d8913f1943c3e771446f0d82a900b32e690527cde887157aef0e74de8d" + "files": 408, + "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", + "source_tree": "sha256:28ed8a6e5e23edd753a754a8da1355cd8363f3c273d139791d6ade655fb55a35" }, "owner_lane": "", "provenance": { diff --git a/src/runtime/.crumb b/src/runtime/.crumb index afd44ab97..8d32fda19 100644 --- a/src/runtime/.crumb +++ b/src/runtime/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-05T20:10:00Z", + "compiled_at": "2026-10-05T22:51:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:7927099dac3838db8f33a305a185873d9610c7c496fc3763ec9e5dc9e901bb9d", + "digest": "sha256:76504ddb5dcdf70af8f8ace77bed616398f7550fa4a290bca68fe445ad62aba6", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 59, - "generated_at_commit": "f8ce768210e58d33e675a7bbae2208ccbfc58db7", - "source_tree": "sha256:6eede518faaae5783b6f84140535af1105d811b5975bffdda56934065ac91687" + "files": 61, + "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", + "source_tree": "sha256:bbbef89c119006e7fdd15bb7375236bc819f40b283095efc71a542a1e9d002b0" }, "owner_lane": "", "provenance": { diff --git a/tests/runtime/.crumb b/tests/runtime/.crumb index 3e48c3c44..723f5b2a3 100644 --- a/tests/runtime/.crumb +++ b/tests/runtime/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-05T20:10:00Z", + "compiled_at": "2026-10-05T22:51:30Z", "compiler": "crumb-compile/1", - "digest": "sha256:71ee11a9ea01b73efaf1c3f4fa3495aa98cc7d610b5570ce591f0718bb25a4d4", + "digest": "sha256:1428e0b1429812fe4465d5b685b92585365c5b70dff66ebcd134246c3447427e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 58, - "generated_at_commit": "f8ce768210e58d33e675a7bbae2208ccbfc58db7", - "source_tree": "sha256:0e2d0c40beb2bbf8d4a9aca98a69a382d6b0501e33f4dab682c4c7f8861b62f9" + "files": 60, + "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", + "source_tree": "sha256:f180d2d6692c9fceb1a6cbdd5b1faff3c5cc4fc77cce81f8d4ca82bce3805bf5" }, "owner_lane": "", "provenance": { From 96748a2078862997c4ee423797ed4d1a99dcf300 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 5 Oct 2026 19:23:54 -0500 Subject: [PATCH 5/6] R16 G6 operator control: review fixes (security S1-S4, gate G1-G8) Security: - S1: one program per state directory. flock on operator.lock (O_CLOEXEC|O_NOFOLLOW) in the state dir, each generation (halt) dir and, per world, the control dir. Socket and credential are created, replaced and removed only under the lock, relative to a held directory descriptor; close removes only what this instance created (dev/inode). - S2: a stop whose mark cannot be written replies STOPPED_NOT_DURABLE with the errno; the client exits 3. - S3: unknown commands with a full credential are refused before any authority call (tested, mutant O22); the epoch-right limit is documented with file:line routing proof and filed as aien-dev/aienos#266 (aienos unchanged). - S4: socket timeouts checked on both sides; every request carries a CLOCK_MONOTONIC deadline; a resume that waited past it answers EXPIRED and is not run; directory checks use O_DIRECTORY|O_NOFOLLOW plus fstat. The listener now reads the client's side to EOF before closing (a refusal sent before the request was read could reset the client: 1 in 300 before, 0 in 1000 after). Gate: - G1: the silicon test requires R13_LIVING_SYSTEM=PASS (the spec allows nothing else). - G2/G3: r16_qualify copies both operator receipts into the raw dir, binds each to the production binary built in the run, the candidate and a clean tree; mutant runs write to their own dirs; the operator silicon run counts toward silicon_observed (6 runs). Tests carry a seat label. - G5/G6: host runs hold threads of the production program under gdb (non-stop): an in-flight seat result (seat_halted=1, exercising the claim subtraction), the end of the positive episode, and the next world's open. Mutants O15 and O16 killed; no retry loop remains. - G7: skipped cases are NOT_RUN with their reasons in the receipt; qualify maps them. - G8: wait_running and the retire and quiescence loops listed by hand (OM-M03..M05, B). Mutants: 25, all killed. Host test 86 checks, 3 of 3 PASS. 90 regression targets PASS. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/host-suites-2.yml | 5 +- docs/.crumb | 8 +- docs/r16-operator-control.md | 106 ++++++++- spec/.crumb | 8 +- spec/r16-orchestrator-retirement-map.md | 18 ++ src/.crumb | 12 +- src/runtime/.crumb | 8 +- src/runtime/rx_operator.c | 238 +++++++++++++++---- src/runtime/rx_operator.h | 28 ++- tests/r16_qualify/run.sh | 89 ++++++- tests/runtime/.crumb | 8 +- tests/runtime/rx_operator_host.sh | 293 ++++++++++++++++++++---- tests/runtime/rx_operator_mutants.sh | 20 +- tests/runtime/rx_r13_living.c | 21 +- tools/r16_qualify.sh | 72 +++++- tools/rx_operator.c | 44 +++- 16 files changed, 823 insertions(+), 155 deletions(-) diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index 30606a2c3..8d983f86a 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -54,8 +54,9 @@ name: Host suites 2 # test-r16-operator-host, test-r16-operator-mutants: environment, same reason. # They start the production R13 host program and drive it through its # operator socket; every world runs an R13 episode ("needs both core -# classes", tests/runtime/rx_r13_living.c run()). Spark -j1: host 32 s, -# mutants 95 s, both PASS; test-r16-operator-silicon is a chip target; +# classes", tests/runtime/rx_r13_living.c run()), and the host test holds +# threads of that program under gdb (non-stop). Spark -j1: host 34 s, +# mutants (25) about 5 min, both PASS; test-r16-operator-silicon is a chip target; # test-polyglot: environment. mk/polyglot.mk builds its -O3 flavor with # -mcpu=native next to -march=armv8.6-a+...; on the runner (Neoverse N2) gcc # resolves native to a CPU that conflicts with that -march and -Werror stops diff --git a/docs/.crumb b/docs/.crumb index fa70e27df..8c941367a 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -118,14 +118,14 @@ } ], "children_root": "sha256:ce53c9c7f75a7d122d6a926bb304b2df1bd0730693b54887b842ad3559bafe83", - "compiled_at": "2026-10-05T22:51:30Z", + "compiled_at": "2026-10-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:a27037a2239070b399ca6809105a8cc535d5796374e8a41fce3b2803018abfcc", + "digest": "sha256:01f9bcaf892355eff231425a96bf8f625fc9d9be4c1480991db92b6fefd6cd49", "evidence_files": 34, "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc", "files": 113, - "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", - "source_tree": "sha256:49c9c5208e007290cf8f3db38a2eead1b0600bd2f13d09e56f0d12293cccb7d4" + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:0a688cde0c483735c8aee62f8ae2162bc7fbc30456961d7fc031b897c64e1587" }, "owner_lane": "", "provenance": { diff --git a/docs/r16-operator-control.md b/docs/r16-operator-control.md index c7ff83222..597a69a9f 100644 --- a/docs/r16-operator-control.md +++ b/docs/r16-operator-control.md @@ -53,12 +53,25 @@ its own world. Every statement below holds for each of those worlds. a stop never lands inside setup; a world restored stopped answers at once (it does no setup until resumed). Between worlds there is no socket: a client gets "connection refused" and the request does nothing. +* **One program per state directory.** At startup the program takes an exclusive + `flock` on `/operator.lock` (opened `O_CLOEXEC|O_NOFOLLOW`, a regular file of its + uid) and, when a world first uses it, on `/gen-/operator.lock`; it holds + both for its whole life. A second program on the same state directory, or one whose + state directory is the first one's generation directory, is refused (exit 2, + `... is in use by another program (pid N)`) before it touches a socket or a + credential. Each world also locks `control/` the same way while its entry point is + open. The control directory is held open as a descriptor: the stale socket is removed, + the socket bound (through `/proc/self/fd//operator.sock`) and the credential + written and renamed relative to that descriptor, never by a path looked up again. + Close removes the socket and the credential only if they are still the files this + instance created (same device and inode), then releases the lock. * Two walls before the credential: the directory is 0700 and owned by the program's user (validated at startup, §5), and every accepted connection is checked with `SO_PEERCRED`: the peer uid must equal the program's effective uid, else the reply is `REFUSED reason=peer` and nothing is read further. Root can pass the directory but not the peer check. -* One request per connection, read with a 2 s receive timeout; at most 511 bytes up to +* One request per connection, read with a 2 s receive and send timeout (if either + cannot be set the connection is closed with no reply); at most 511 bytes up to the first newline. One reply line, then the connection is closed. Requests are served one at a time by one listener thread (`src/runtime/rx_operator.c`); it never holds the world lock across a request. @@ -83,18 +96,31 @@ cap Request (one line): ``` -aien-operator v1 subject= gen= secret=<64 hex> cap=: [reason=] +aien-operator v1 subject= gen= secret=<64 hex> cap=: deadline= [reason=] ``` +`deadline` is required: the `CLOCK_MONOTONIC` time in nanoseconds after which the client +has given up (the client sends now + 55 s and waits 60 s). A deadline more than 120 s +ahead is `BAD_REQUEST`. A request that waited for the world's setup past its deadline is +answered `EXPIRED` and not run, unless it is a `stop`: a late stop is fail-safe and still +runs; a late resume would restart a world nobody is watching. + `` is `status`, `stop`, `resume`, `revoke-cap`, `revoke` or `shutdown`. Any other token, a missing or repeated field, a secret that is not 64 hex digits, a number out of range or extra bytes is `BAD_REQUEST`, decided before any world call. Reply (one line): `aien-operator v1 key=value ...`. RESULT is one of `OK`, +`STOPPED_NOT_DURABLE` (the stop is in force in memory but its mark could not be written: +a restart would NOT come up stopped; carries `durable=<-errno> errno= ()`), `ALREADY` (stop of a stopped world), `NOT_STOPPED` (resume or shutdown of a running world), +`EXPIRED` (the client deadline passed while the request waited; nothing done), `REFUSED reason=peer|identity|authority`, `BAD_REQUEST`, `ERROR rc=`. A refusal says nothing about the world: no state, no counters. +Client exit status: 0 for `OK`, 3 for `STOPPED_NOT_DURABLE`, 1 for any other reply, 2 for +a usage error, no credential file, no world serving the socket, or a reply timeout that +could not be set. + ## 4. Commands Every command except `BAD_REQUEST` cases goes to the world authority first. `status`, @@ -105,8 +131,8 @@ same `halt_authorize` the stop and resume use, under the same locks, added to | command | world call | reply on success | |---|---|---| -| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= cancelled= crumbs= reactions=` plus program counters `served= production_commits= inforce= active_generation=` | -| `stop [reason]` | `rx_world_emergency_stop` | `OK state=stopped seq= crumb= durable=`; a second stop: `ALREADY` with no new crumb | +| `status` | `rx_world_operator_authorize`, `rx_world_halt_status` | `OK state=running\|stopped restored= seq= durable= refused= cancelled= crumbs= reactions=` plus program counters `served= production_commits= promotion= inforce= active_generation= seat_claims= seat_halted=` | +| `stop [reason]` | `rx_world_emergency_stop` | `OK state=stopped seq= crumb= durable=1`; mark not written: `STOPPED_NOT_DURABLE ... errno=` (client exit 3); a second stop: `ALREADY` with no new crumb | | `resume` | `rx_world_emergency_resume` | `OK state=running seq=`; a running world: `NOT_STOPPED` | | `revoke-cap` | authorize, then `aienos_cap_revoke` of the presented control capability by the authority's office | `OK revoked=capability`; afterwards every request with that capability is `REFUSED reason=authority` | | `revoke` | authorize, then `aienos_cap_revoke` (capability) and `rx_world_revoke_caller` (credential); the credential file is removed | `OK revoked=capability,credential`; afterwards `REFUSED reason=identity` | @@ -131,7 +157,8 @@ earlier world or an earlier program start fails the constant-time caller check `/gen-/` (`positive`, `no-aien`, `no-promotion`, `revoked-experiment`, `stale-gpu`, `failed-verification`). * **Validated at startup, refuse if wrong.** `` and each subdirectory must be a real - directory (checked with `lstat`, a symlink is refused), owned by the effective uid, with + directory (opened `O_DIRECTORY|O_NOFOLLOW` and checked with `fstat` on that descriptor, + so a symlink is refused and nothing can be swapped in between), owned by the effective uid, with no group or other permission bits (`mode & 077 == 0`). A missing subdirectory is created 0700. A path too long for a socket address is refused. On any refusal the program prints the reason and exits 2 before any world starts. @@ -179,6 +206,48 @@ earlier world or an earlier program start fails the constant-time caller check does not stop the process, its threads, ARGUS observation or the authority; it is not a kill switch and not a rollback. +### 6.1 Known limit: the halt right is the epoch right + +The spec gives the stop the privileged epoch right (`spec/r16-operator-emergency-stop.md` +§2 lines 44-45: "The right is `RX_RIGHT_EPOCH` ... The right that may void every +capability may also pause the world"). ADR 0016 (aien-architecture main 014159e) is +silent on a halt or pause right: neither word occurs in it. Its capability section +(lines 367-382) lists the resource among what a capability binds, and line 1475 asks +that a wrong-resource attack fail. + +The locked native authority does not check the resource when a capability is used: +`auth_use` (aienos `native/capability/aienos_capability.c` lines 205-218 at aienos.lock +bbad5e4) checks delivery, generation, state, epoch, expiry, the delegation chain and +the rights, not the entry's resource. So the operator's control capability +(`RX_WORLD_RES_CONTROL` with `RX_RIGHT_EPOCH`) would also pass `aienos_cap_bump_epoch` +(same file, line 555, through `auth_use(..., AIENOS_CAP_RIGHT_EPOCH, ...)` at line 369) +if anything handed it there. omega does not change the locked authority; the request +is aien-dev/aienos#266 (a resource check in `auth_use`, or a dedicated halt right). + +What keeps it closed today is omega's own code, shown here and tested: + +* The capability is minted once per world (`tests/runtime/rx_r13_living.c` 449, + `mint(r, RX_OPERATOR_SUBJ, RX_WORLD_RES_CONTROL, RX_WORLD_RIGHT_HALT)`) and passed only + to `rx_operator_open` (line 327), which writes it to the operator's credential file + and keeps no other use of it. +* A presented capability (`q->cap`, parsed at `src/runtime/rx_operator.c` 262) reaches + exactly four calls: `rx_world_emergency_stop` (291), `rx_world_emergency_resume` + (312), `rx_world_operator_authorize` (328, for status, shutdown, revoke-cap and + revoke) and, as the *target* of a revocation authorized by the authority's office, + `aienos_cap_revoke` (360). The first three validate it with + `rx_world_validate_cap(..., RX_WORLD_RES_CONTROL, RX_WORLD_RIGHT_HALT, ...)` inside + `halt_authorize` (`src/runtime/rx_world.c` 914). +* Every other command, with a full valid credential, is `BAD_REQUEST` before any + authority call (`rx_operator.c` 327). The host test sends `explode`, `bump-epoch`, + `bump_epoch`, `mint`, `grant`, `epoch`, `STOP`, `Stop`, `stop2`, `resume2` and `halt` + and requires `BAD_REQUEST` for each; mutant O22 removes that refusal and the test fails. +* `aienos_cap_bump_epoch` has no caller in omega's production sources (`git grep`: the + declaration in `src/runtime/aienos_cap.h` 56 and the R7 oracle test + `tests/runtime/rx_r7_native.c` 217 only). + +A future omega change that hands the control capability to any other authority entry +point reopens this; it stays a known limit until aienos#266 is closed. + ## 7. Proof (G6 by execution) `make test-r16-operator-host` (`tests/runtime/rx_operator_host.sh`) starts the production @@ -190,13 +259,36 @@ credential (earlier world, earlier program start); `revoke-cap` and `revoke`; re stop and resume; repeated stop and resume cycles under production load (in-flight work refused and re-run); promotion blocked while stopped and completed after resume; restart while stopped after `shutdown` and after `SIGKILL`; recovery to a passing R13 episode; -startup refusal of a group-readable, foreign-owned or symlinked state directory. +startup refusal of a group-readable, foreign-owned or symlinked state directory; a +second program on the same state directory or on the first one's generation directory +refused while the first keeps its socket and credential; a stop whose mark cannot be +written (generation directory made 0500) answering `STOPPED_NOT_DURABLE errno=13` with +client exit 3; eleven unknown commands with a full credential refused; an expired +resume answering `EXPIRED` and doing nothing, a missing or too-distant deadline refused. +On host three checks are made deterministic by holding one thread of the production +program under gdb in non-stop mode (the socket keeps serving): the seat acceptor held +with a computed seat result while a stop is accepted, then released, must end that claim +halted (`seat_halted` in status, so the episode's claim subtraction is exercised on +host); the positive world held after its episode's work, stopped, then released, must +stay up and stopped and print that it waits for a resume; the next world's open held +after the positive world closed must find a credential file planted by someone else +still in place. Without gdb those checks are SKIPPED (gate NOT_RUN). Silicon runs +without gdb; its in-flight count is reported, not checked. A host run whose only gap is a +missing `sudo -n` or gdb is NOT_RUN with the reason in the receipt, never FAIL. `tests/runtime/rx_operator_mutants.sh` rebuilds the production program from mutated copies and requires the test to fail against each (wiring missing, handler disconnected, success reply without a state transition, unauthorized resume accepted, wiring present only in a comment, wiring present only as an unused call, and the others it lists). `make test-r16-operator-silicon` runs the same test on `build/rx_r13_living_silicon` (resident GB10 seat) without the SIGKILL phase (a chip program is never killed). The -receipt labels host and silicon results separately. The G6 item +receipt labels host and silicon results separately. The silicon test requires the +program's own gate `R13_LIVING_SYSTEM=PASS` (bound to the candidate commit on a clean +tree): the spec allows no `SILICON_PASS_UNBOUND`. Each run writes +`operator__receipt.json` to `RX_OP_OUT` (default `build/r16-operator`); the mutant +script gives every mutant its own directory, so a mutant never overwrites the real receipt. +`tools/r16_qualify.sh` copies both receipts into its raw directory (covered by the raw +digest) and refuses PASS unless each names its seat, the candidate commit on a clean tree, +no failure or skip, the seat's gate, and the SHA-256 of the production binary built in that +run; the silicon run counts toward `silicon_observed`. The G6 item `operator_emergency_controls_passing` is PASS only when both ran and passed in the same qualification run on the candidate. diff --git a/spec/.crumb b/spec/.crumb index f9c5b9e2f..497aafead 100644 --- a/spec/.crumb +++ b/spec/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:6834a3241647d3a098283d4eafedbdb1428dfa4d834f9ed5f22025b6d2303093", - "compiled_at": "2026-10-05T22:51:30Z", + "compiled_at": "2026-10-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:f4bca55badfbb82836dfbe4ae2f44ecb57198e4a9ce4a02cbf3e534b23dcecbd", + "digest": "sha256:a208771d61d51324273b06beab565036bbc61f3218dfb6cba76d853ec3515073", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 56, - "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", - "source_tree": "sha256:23967b4782de139f3ecdd4965c186128817ed700918ff0567b3bbbf77a0bf70f" + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:7dd1a87e6835f7a9c18cd979acbcfa96f53a8fa6ac309fccbb015470b024823f" }, "owner_lane": "", "provenance": { diff --git a/spec/r16-orchestrator-retirement-map.md b/spec/r16-orchestrator-retirement-map.md index 518657502..15fc89faf 100644 --- a/spec/r16-orchestrator-retirement-map.md +++ b/spec/r16-orchestrator-retirement-map.md @@ -654,6 +654,9 @@ exists in the file (symbol not verified) and applies the same class rules. | OM-M01 | omega | `tools/omegatool.c` | manual (2642) | `legacy_oracle_run_demonstration_living_matvec` | body of the hand-sequenced living-matvec demonstration | retire with `--demonstrate-living-matvec` (W5) | A | false | the function the class-A dispatcher row calls; moved behind a `legacy_oracle` name (W5) | `static void legacy_oracle_run_demonstration_living_matvec(void) {` | | OM-103 | omega | `tools/omegatool.c` | manual (3749) | `legacy_oracle_demonstrate_living_matvec` | hand-sequenced living matvec demonstration (spec -> machine -> kernel -> benchmark -> select) | retire: legacy oracle only, under the explicit mode `--legacy-oracle-living-matvec` (R16-G5); the old `--demonstrate-living-matvec` mode is gone | A | false | spec 3.1 / 4: the omega hand-sequenced tool path replaced by the R13 living system; retired behind legacy_oracle symbol names (W5) and, for G5, an explicit legacy mode name; moved to the manual rows because the renamed mode no longer matches the cli-mode pattern | `if (strcmp(arg, "--legacy-oracle-living-matvec") == 0) {` | | OM-M02 | omega | `tools/omegatool.c` | manual (3821) | `main` | hand-sequenced milestone demonstrations (16 modes: arithmetic, physics, realization, self-host, verify, program, synthesis, library, discovery, machine, realization-synthesis, accelerator, accelerator-world, blackwell-matmul, blackwell-codegen, blackwell-vector) | reference oracle (legacy orchestrated runtime) | D | false | historical milestone demonstrations; migration map: omegatool = Oracle; not a production entry point; G5: kept only under `--reference-demonstrate-`, dispatched from the one `reference_modes` table that also prints usage; replaces the 16 per-mode cli-mode rows, which the table-driven dispatch no longer shows to the pattern | `int ref_rc = reference_demonstrate(argv[1], 0);` | +| OM-M03 | omega | `tests/runtime/rx_r13_living.c` | manual (306) | `wait_running` | wait while the world is under an operator stop | R16 G6 operator stop honoured by the production program | B | true | operator emergency stop mechanism: polls the world's halt state (1 ms) until the operator resumes, shuts the program down or the world is torn down; sequences no faculty; listed by hand (the loop pattern does not see a `while` on a call) | `while (world_halted(r)) {` | +| OM-M04 | omega | `tests/runtime/rx_r13_living.c` | manual (1064) | `run` | stale-GPU retire waits out an operator stop | R16 G6 operator stop honoured by the stale-GPU injection | B | true | operator emergency stop mechanism: a retire refused with RX_ERR_HALTED waits for the resume (`wait_running`) and is tried again; sequences no faculty; listed by hand | `while ((rr = rx_world_retire(&r->w, r->living.o.output)) == RX_ERR_HALTED)` | +| OM-M05 | omega | `tests/runtime/rx_r13_living.c` | manual (1104) | `run` | end-of-episode quiescence wait under an operator stop | R16 G6 operator stop honoured before the episode checks | B | true | operator emergency stop mechanism: the settled-world wait is repeated only while the world is stopped, each time after waiting for the resume; sequences no faculty; listed by hand | `while ((quiet = rx_world_wait_quiescent(&r->w, 10000)) != RX_OK && world_halted(r))` | ## 5. Structural findings (non-greppable §4 terms) @@ -934,3 +937,18 @@ Neither sequences faculties: each waits for the operator or for the world to run After: `sites=523 unclassified=0 question=0 bad_class=0 a_reachable=0 stale=0 map_errors=0 skipped=0 -> PASS`. This is the G1/G2 inventory for the CAND-3 operator-control code, not an R16 qualification receipt. + +### 8.8 Update 2026-10-05 (cand3 lane ESTOP, review fixes): operator wait loops listed by hand + +Review of omega#309 (gate integrity, G8) asked that the operator-stop wait loops the +pattern scan does not count be listed by hand with a class. Three manual rows (§4.1), +each from reading the loop: +- OM-M03, class B: `wait_running` (`tests/runtime/rx_r13_living.c`), the 1 ms poll while the + world is under an operator stop. +- OM-M04, class B: the stale-GPU retire in `run` that waits out a stop and tries again. +- OM-M05, class B: the settled-world wait in `run`, repeated only while the world is stopped. +None sequences faculties: each waits for the operator. The tool checks that each evidence +line still exists (a changed evidence line was shown to give `stale=1 -> FAIL`). + +After: `sites=523 unclassified=0 question=0 bad_class=0 a_reachable=0 stale=0 map_errors=0 skipped=0 -> PASS` +(same scan set as §8.7). Not an R16 qualification receipt. diff --git a/src/.crumb b/src/.crumb index 1a044a42d..d0e514468 100644 --- a/src/.crumb +++ b/src/.crumb @@ -133,7 +133,7 @@ "purpose": "Directory src/polyglot. Purpose not yet described by a human." }, { - "digest": "76504ddb5dcdf70af8f8ace77bed616398f7550fa4a290bca68fe445ad62aba6", + "digest": "63f3df62adf0a29ee2fdfdc4e170409de18f8a2a33c5644ab8d4009cf1c5246f", "last_commit": "def0a0d", "name": "runtime", "purpose": "Directory src/runtime. Purpose not yet described by a human." @@ -169,15 +169,15 @@ "purpose": "Directory src/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:babd73b24df0569f6fc6c49d3180b813d919485a8065aa430642eb56be95c568", - "compiled_at": "2026-10-05T22:51:30Z", + "children_root": "sha256:920218d42490379078986bd65f6d50e8ef9064df20da67bfc0ca50ea0de4b4c0", + "compiled_at": "2026-10-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:cab0414a38bfa4deff6e1ef2006ff703d59434440dca34666f432701e9bdfb5c", + "digest": "sha256:bf667679bc7c3494f148e83e9d8f56193a3768c2f7145a614a21e701e3bddabd", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 408, - "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", - "source_tree": "sha256:28ed8a6e5e23edd753a754a8da1355cd8363f3c273d139791d6ade655fb55a35" + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:d171d30065cacc0d402c1013b920ad3cf4392e78ed56d71fd0fa4669a2ac865b" }, "owner_lane": "", "provenance": { diff --git a/src/runtime/.crumb b/src/runtime/.crumb index 8d32fda19..b30b38677 100644 --- a/src/runtime/.crumb +++ b/src/runtime/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-05T22:51:30Z", + "compiled_at": "2026-10-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:76504ddb5dcdf70af8f8ace77bed616398f7550fa4a290bca68fe445ad62aba6", + "digest": "sha256:63f3df62adf0a29ee2fdfdc4e170409de18f8a2a33c5644ab8d4009cf1c5246f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 61, - "generated_at_commit": "def0a0dc8f417feeed1f29c974855a8b5754183a", - "source_tree": "sha256:bbbef89c119006e7fdd15bb7375236bc819f40b283095efc71a542a1e9d002b0" + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:d6c5fe7ac0396ceedc2c666adae44e38d9c03553974f120898eea988cbc033a4" }, "owner_lane": "", "provenance": { diff --git a/src/runtime/rx_operator.c b/src/runtime/rx_operator.c index ffaab4d3a..8cbd3aef8 100644 --- a/src/runtime/rx_operator.c +++ b/src/runtime/rx_operator.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -17,7 +18,10 @@ struct RxOperator { RxOperatorConfig cfg; char sock_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; - char cred_path[512]; + int dir_fd; /* the validated control directory, held open */ + int lock_fd; /* flock on RX_OPERATOR_LOCK in it, held until close */ + struct stat sock_st, cred_st;/* what this instance created (device, inode) */ + int sock_made, cred_made; int listen_fd; int wake[2]; /* a byte on wake[1] ends the listener */ pthread_t thread; @@ -25,17 +29,11 @@ struct RxOperator { pthread_mutex_t gate; /* held by the program while it sets the world up */ }; -int rx_operator_dir_check(const char *dir, int create, char *why, size_t n) { +/* Validate an open directory descriptor: a directory owned by this uid with no + * group or other bits. Checks the descriptor itself, not a path. */ +static int dir_fd_ok(int fd, const char *dir, char *why, size_t n) { struct stat st; - if (!dir || !dir[0]) { snprintf(why, n, "no directory"); return -1; } - if (lstat(dir, &st) != 0) { - if (errno != ENOENT || !create) { snprintf(why, n, "%s: %s", dir, strerror(errno)); return -1; } - if (mkdir(dir, 0700) != 0 || lstat(dir, &st) != 0) { - snprintf(why, n, "%s: cannot create: %s", dir, strerror(errno)); - return -1; - } - } - if (S_ISLNK(st.st_mode)) { snprintf(why, n, "%s is a symlink", dir); return -1; } + if (fstat(fd, &st) != 0) { snprintf(why, n, "%s: %s", dir, strerror(errno)); return -1; } if (!S_ISDIR(st.st_mode)) { snprintf(why, n, "%s is not a directory", dir); return -1; } if (st.st_uid != geteuid()) { snprintf(why, n, "%s is owned by uid %u, not by this program's uid %u", dir, @@ -50,6 +48,85 @@ int rx_operator_dir_check(const char *dir, int create, char *why, size_t n) { return 0; } +int rx_operator_dir_open(const char *dir, int create, int *fd_out, char *why, size_t n) { + *fd_out = -1; + if (!dir || !dir[0]) { snprintf(why, n, "no directory"); return -1; } + int fd = open(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0 && errno == ENOENT && create) { + if (mkdir(dir, 0700) != 0 && errno != EEXIST) { + snprintf(why, n, "%s: cannot create: %s", dir, strerror(errno)); + return -1; + } + fd = open(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + } + if (fd < 0) { + int e = errno; + struct stat st; /* only to name the refusal; the decision is the failed open */ + int l = lstat(dir, &st) == 0; + if (l && S_ISLNK(st.st_mode)) snprintf(why, n, "%s is a symlink", dir); + else if (l && st.st_uid != geteuid()) + snprintf(why, n, "%s is owned by uid %u, not by this program's uid %u (%s)", dir, + (unsigned)st.st_uid, (unsigned)geteuid(), strerror(e)); + else if (e == ENOTDIR) snprintf(why, n, "%s is not a directory", dir); + else snprintf(why, n, "%s: %s", dir, strerror(e)); + return -1; + } + if (dir_fd_ok(fd, dir, why, n) != 0) { close(fd); return -1; } + *fd_out = fd; + return 0; +} + +int rx_operator_dir_check(const char *dir, int create, char *why, size_t n) { + int fd; + if (rx_operator_dir_open(dir, create, &fd, why, n) != 0) return -1; + close(fd); + return 0; +} + +/* flock on RX_OPERATOR_LOCK inside the held directory `dfd`. */ +static int lock_at(int dfd, const char *dir, int *lock_fd, char *why, size_t n) { + *lock_fd = -1; + int fd = openat(dfd, RX_OPERATOR_LOCK, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { snprintf(why, n, "%s/%s: %s", dir, RX_OPERATOR_LOCK, strerror(errno)); return -1; } + struct stat st; + if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_uid != geteuid()) { + snprintf(why, n, "%s/%s is not a regular file of this uid", dir, RX_OPERATOR_LOCK); + close(fd); + return -1; + } + if (flock(fd, LOCK_EX | LOCK_NB) != 0) { + int e = errno; + char held[32] = ""; + ssize_t r = pread(fd, held, sizeof held - 1, 0); + held[r > 0 ? r : 0] = 0; + held[strcspn(held, "\n")] = 0; + if (e == EWOULDBLOCK) + snprintf(why, n, "%s is in use by another program (pid %s)", dir, held[0] ? held : "?"); + else + snprintf(why, n, "%s/%s: lock: %s", dir, RX_OPERATOR_LOCK, strerror(e)); + close(fd); + return -1; + } + char pid[32]; + int len = snprintf(pid, sizeof pid, "%ld\n", (long)getpid()); + if (ftruncate(fd, 0) != 0 || pwrite(fd, pid, (size_t)len, 0) != len) { + snprintf(why, n, "%s/%s: %s", dir, RX_OPERATOR_LOCK, strerror(errno)); + close(fd); + return -1; + } + *lock_fd = fd; + return 0; +} + +int rx_operator_lock_dir(const char *dir, int create, int *lock_fd, char *why, size_t n) { + int dfd; + *lock_fd = -1; + if (rx_operator_dir_open(dir, create, &dfd, why, n) != 0) return -1; + int rc = lock_at(dfd, dir, lock_fd, why, n); + close(dfd); + return rc; +} + static void hex32(const uint8_t *b, char out[65]) { for (int i = 0; i < 32; i++) snprintf(out + 2 * i, 3, "%02x", b[i]); } @@ -60,9 +137,17 @@ static uint64_t realtime_ns(void) { return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; } -/* The operator's copy of its credential: 0600, written whole or not at all. */ +static uint64_t monotonic_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; +} + +/* The operator's copy of its credential: 0600, written whole or not at all, + * every name relative to the held control directory. */ static int write_cred(RxOperator *op, uint32_t subject, const RxCallerCred *cred, RxCapRef cap) { - char tmp[600], secret[65], buf[1024]; + static const char tmp[] = RX_OPERATOR_CRED ".partial"; + char secret[65], buf[1024]; hex32(cred->secret, secret); int len = snprintf(buf, sizeof buf, "aien-operator-credential v1\nworld %s %ld %llu\nsocket %s\nsubject %u\n" @@ -73,8 +158,7 @@ static int write_cred(RxOperator *op, uint32_t subject, const RxCallerCred *cred (unsigned long long)cap.generation); for (size_t i = 0; i < sizeof secret; i++) ((volatile char *)secret)[i] = 0; if (len <= 0 || (size_t)len >= sizeof buf) return -1; - if ((size_t)snprintf(tmp, sizeof tmp, "%s.partial", op->cred_path) >= sizeof tmp) return -1; - int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); + int fd = openat(op->dir_fd, tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); int rc = fd < 0 ? -1 : 0; if (rc == 0 && fchmod(fd, 0600) != 0) rc = -1; for (int off = 0; rc == 0 && off < len;) { @@ -83,13 +167,27 @@ static int write_cred(RxOperator *op, uint32_t subject, const RxCallerCred *cred if (w <= 0) rc = -1; else off += (int)w; } if (rc == 0 && fsync(fd) != 0) rc = -1; + if (rc == 0 && fstat(fd, &op->cred_st) != 0) rc = -1; if (fd >= 0) close(fd); for (size_t i = 0; i < sizeof buf; i++) ((volatile char *)buf)[i] = 0; - if (rc == 0 && rename(tmp, op->cred_path) != 0) rc = -1; - if (rc != 0) unlink(tmp); + if (rc == 0 && renameat(op->dir_fd, tmp, op->dir_fd, RX_OPERATOR_CRED) != 0) rc = -1; + if (rc == 0 && fsync(op->dir_fd) != 0) rc = -1; + if (rc != 0) unlinkat(op->dir_fd, tmp, 0); + else op->cred_made = 1; return rc; } +/* Remove `name` from the held directory only if it is still the file this + * instance made (same device and inode). */ +static void unlink_own(RxOperator *op, const char *name, const struct stat *made, int *flag) { + struct stat st; + if (!*flag || op->dir_fd < 0) return; + if (fstatat(op->dir_fd, name, &st, AT_SYMLINK_NOFOLLOW) == 0 && + st.st_dev == made->st_dev && st.st_ino == made->st_ino) + unlinkat(op->dir_fd, name, 0); + *flag = 0; +} + /* ---- one request ---------------------------------------------------------- */ typedef struct { @@ -98,9 +196,13 @@ typedef struct { RxCallerCred cred; RxCapRef cap; int32_t reason; - int have_subject, have_gen, have_secret, have_cap, have_reason; + uint64_t deadline_ns; /* CLOCK_MONOTONIC: the client has given up after this */ + int have_subject, have_gen, have_secret, have_cap, have_reason, have_deadline; } Req; +/* A request deadline further ahead than this is refused (the client waits 60 s). */ +#define RX_OPERATOR_DEADLINE_MAX_NS 120000000000ull + static int hexval(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; @@ -161,11 +263,16 @@ static int parse(char *line, Req *q) { } else if (strcmp(k, "reason") == 0 && !q->have_reason) { if (udec(v, INT32_MAX, &x) != 0) return -1; q->reason = (int32_t)x; q->have_reason = 1; + } else if (strcmp(k, "deadline") == 0 && !q->have_deadline) { + if (udec(v, UINT64_MAX, &x) != 0) return -1; + q->deadline_ns = x; q->have_deadline = 1; } else { return -1; } } - if (!q->have_subject || !q->have_gen || !q->have_secret || !q->have_cap) return -1; + if (!q->have_subject || !q->have_gen || !q->have_secret || !q->have_cap || !q->have_deadline) + return -1; + if (q->deadline_ns > monotonic_ns() + RX_OPERATOR_DEADLINE_MAX_NS) return -1; if (q->have_reason && strcmp(q->cmd, "stop") != 0) return -1; return 0; } @@ -184,8 +291,14 @@ static void handle(RxOperator *op, Req *q, char *out, size_t n) { rc = rx_world_emergency_stop(w, q->subject, &q->cred, q->cap, q->reason, &h); if (rc == RX_OK) { if (op->cfg.on_halt) op->cfg.on_halt(op->cfg.ctx, 1); - snprintf(out, n, "OK state=stopped seq=%llu crumb=%llu durable=%d", - (unsigned long long)h.seq, (unsigned long long)h.crumb, h.durable); + if (h.durable == 1) + snprintf(out, n, "OK state=stopped seq=%llu crumb=%llu durable=1", + (unsigned long long)h.seq, (unsigned long long)h.crumb); + else /* in force in memory; a restart would NOT come up stopped */ + snprintf(out, n, "STOPPED_NOT_DURABLE state=stopped seq=%llu crumb=%llu durable=%d " + "errno=%d (%s)", (unsigned long long)h.seq, (unsigned long long)h.crumb, + h.durable, h.durable < 0 ? -h.durable : 0, + h.durable < 0 ? strerror(-h.durable) : "no durable halt directory"); } else if (rc == RX_HALT_ALREADY) { snprintf(out, n, "ALREADY state=stopped seq=%llu", (unsigned long long)h.seq); } else if (refusal(rc)) { @@ -252,7 +365,7 @@ static void handle(RxOperator *op, Req *q, char *out, size_t n) { if (revoke) { rc = rx_world_revoke_caller(w, q->subject, &q->cred); if (rc != RX_CALLER_OK) { snprintf(out, n, "ERROR rc=revoke-credential %d", rc); return; } - unlink(op->cred_path); + unlink_own(op, RX_OPERATOR_CRED, &op->cred_st, &op->cred_made); snprintf(out, n, "OK revoked=capability,credential"); return; } @@ -264,8 +377,10 @@ static void serve_one(RxOperator *op, int fd) { struct ucred pc; socklen_t pl = sizeof pc; struct timeval tv = {2, 0}; - setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); - setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv); + /* Without both timeouts one client could hold the listener: refused, no reply. */ + if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) != 0 || + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv) != 0) + return; if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &pc, &pl) != 0 || pl != sizeof pc || pc.uid != geteuid()) { snprintf(body, sizeof body, "REFUSED reason=peer"); @@ -293,7 +408,14 @@ static void serve_one(RxOperator *op, int fd) { snprintf(body, sizeof body, "BAD_REQUEST"); } else { pthread_mutex_lock(&op->gate); - handle(op, &q, body, sizeof body); + /* A request waits here while the program sets a world up. Once its + * client has given up (deadline passed) it is dropped, never run late: + * a late resume would restart a world nobody is watching. A late stop + * is fail-safe and still runs. */ + if (strcmp(q.cmd, "stop") != 0 && monotonic_ns() > q.deadline_ns) + snprintf(body, sizeof body, "EXPIRED (the client deadline passed; nothing done)"); + else + handle(op, &q, body, sizeof body); pthread_mutex_unlock(&op->gate); } for (size_t i = 0; i < sizeof q; i++) ((volatile uint8_t *)&q)[i] = 0; @@ -310,6 +432,17 @@ reply:; sent += (size_t)s; } } + /* Read what the client still sends (a refusal is answered before its request is + * read) until it closes its side, so closing here never resets a client that is + * still writing. Bounded: a few reads, each under the 2 s receive timeout. */ + shutdown(fd, SHUT_WR); + char sink[RX_OPERATOR_LINE]; + for (int i = 0; i < 4;) { + ssize_t r = read(fd, sink, sizeof sink); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + i++; + } } /* The listener: one connection at a time until the wake pipe fires. It @@ -334,37 +467,51 @@ int rx_operator_open(RxOperator **out, const RxOperatorConfig *cfg, uint32_t sub RxCallerCred *cred, RxCapRef cap) { if (!out || !cfg || !cfg->world || !cfg->admin || !cfg->control_dir || !cred) return -1; *out = NULL; - char why[256]; - if (rx_operator_dir_check(cfg->control_dir, 0, why, sizeof why) != 0) { - fprintf(stderr, "R13 operator: control directory refused: %s\n", why); - return -1; - } + char why[320]; RxOperator *op = calloc(1, sizeof *op); if (!op) return -1; op->cfg = *cfg; - op->listen_fd = -1; + op->dir_fd = op->lock_fd = op->listen_fd = -1; op->wake[0] = op->wake[1] = -1; + pthread_mutex_init(&op->gate, NULL); + pthread_mutex_lock(&op->gate); /* held until rx_operator_release */ + /* The control directory is held open and locked: from here every name in + * it is resolved against this descriptor, and no other program can be + * serving or replacing the socket and the credential. */ + if (rx_operator_dir_open(cfg->control_dir, 0, &op->dir_fd, why, sizeof why) != 0 || + lock_at(op->dir_fd, cfg->control_dir, &op->lock_fd, why, sizeof why) != 0) { + fprintf(stderr, "R13 operator: control directory refused: %s\n", why); + goto fail; + } + char bind_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; if ((size_t)snprintf(op->sock_path, sizeof op->sock_path, "%s/%s", cfg->control_dir, RX_OPERATOR_SOCK) >= sizeof op->sock_path || - (size_t)snprintf(op->cred_path, sizeof op->cred_path, "%s/%s", cfg->control_dir, - RX_OPERATOR_CRED) >= sizeof op->cred_path) { + (size_t)snprintf(bind_path, sizeof bind_path, "/proc/self/fd/%d/%s", op->dir_fd, + RX_OPERATOR_SOCK) >= sizeof bind_path) { fprintf(stderr, "R13 operator: control path too long for a socket address\n"); - free(op); - return -1; + goto fail; + } + /* A socket left by an earlier start of this program (the lock is ours). */ + if (unlinkat(op->dir_fd, RX_OPERATOR_SOCK, 0) != 0 && errno != ENOENT) { + fprintf(stderr, "R13 operator: stale socket: %s\n", strerror(errno)); + goto fail; } - pthread_mutex_init(&op->gate, NULL); - pthread_mutex_lock(&op->gate); /* held until rx_operator_release */ - unlink(op->sock_path); /* a socket left by an earlier start */ struct sockaddr_un a; memset(&a, 0, sizeof a); a.sun_family = AF_UNIX; - memcpy(a.sun_path, op->sock_path, strlen(op->sock_path) + 1); + memcpy(a.sun_path, bind_path, strlen(bind_path) + 1); /* lands in the held directory */ op->listen_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); mode_t old = umask(077); int ok = op->listen_fd >= 0 && bind(op->listen_fd, (struct sockaddr *)&a, sizeof a) == 0; umask(old); - ok = ok && chmod(op->sock_path, 0600) == 0 && listen(op->listen_fd, 8) == 0 && - pipe2(op->wake, O_CLOEXEC) == 0 && write_cred(op, subject, cred, cap) == 0; + if (ok && fstatat(op->dir_fd, RX_OPERATOR_SOCK, &op->sock_st, AT_SYMLINK_NOFOLLOW) == 0 && + S_ISSOCK(op->sock_st.st_mode)) + op->sock_made = 1; + else + ok = 0; + ok = ok && fchmodat(op->dir_fd, RX_OPERATOR_SOCK, 0600, 0) == 0 && + listen(op->listen_fd, 8) == 0 && pipe2(op->wake, O_CLOEXEC) == 0 && + write_cred(op, subject, cred, cap) == 0; for (size_t i = 0; i < sizeof *cred; i++) ((volatile uint8_t *)cred)[i] = 0; if (ok && pthread_create(&op->thread, NULL, listener_main, op) == 0) { op->thread_live = 1; @@ -372,6 +519,8 @@ int rx_operator_open(RxOperator **out, const RxOperatorConfig *cfg, uint32_t sub return 0; } fprintf(stderr, "R13 operator: entry point could not start: %s\n", strerror(errno)); +fail: + for (size_t i = 0; i < sizeof *cred; i++) ((volatile uint8_t *)cred)[i] = 0; pthread_mutex_unlock(&op->gate); rx_operator_close(op); return -1; @@ -390,8 +539,11 @@ void rx_operator_close(RxOperator *op) { if (op->listen_fd >= 0) close(op->listen_fd); if (op->wake[0] >= 0) close(op->wake[0]); if (op->wake[1] >= 0) close(op->wake[1]); - unlink(op->sock_path); - unlink(op->cred_path); + /* Only what this instance created, while its lock is still held. */ + unlink_own(op, RX_OPERATOR_SOCK, &op->sock_st, &op->sock_made); + unlink_own(op, RX_OPERATOR_CRED, &op->cred_st, &op->cred_made); + if (op->lock_fd >= 0) close(op->lock_fd); /* releases the flock */ + if (op->dir_fd >= 0) close(op->dir_fd); pthread_mutex_destroy(&op->gate); free(op); } diff --git a/src/runtime/rx_operator.h b/src/runtime/rx_operator.h index 5f35b5919..5140f3bd8 100644 --- a/src/runtime/rx_operator.h +++ b/src/runtime/rx_operator.h @@ -34,21 +34,35 @@ typedef struct { void *ctx; } RxOperatorConfig; -/* `dir` must be a real directory (lstat; no symlink), owned by the effective - * uid, with no group or other permission bits. With `create`, a missing - * directory is made 0700 first. 0 ok; -1 refused, with the reason in `why`. */ +/* `dir` must be a real directory (opened O_DIRECTORY|O_NOFOLLOW, then + * fstat on that descriptor: no symlink, no path re-resolution), owned by the + * effective uid, with no group or other permission bits. With `create`, a + * missing directory is made 0700 first. 0 ok; -1 refused, with the reason in + * `why`. rx_operator_dir_open also hands back the held descriptor. */ int rx_operator_dir_check(const char *dir, int create, char *why, size_t n); +int rx_operator_dir_open(const char *dir, int create, int *fd_out, char *why, size_t n); -/* Write the credential file (0600, temporary file, fsync, rename), wipe - * `cred`, bind the socket and start the listener. The request gate starts +/* Exclusive lock on `dir` (validated as above): flock(LOCK_EX|LOCK_NB) on + * RX_OPERATOR_LOCK, opened with openat(O_CLOEXEC|O_NOFOLLOW) in the held + * directory. Held until the returned descriptor is closed (or the process + * ends). -1 refused (held by another program: its pid is in `why`). */ +#define RX_OPERATOR_LOCK "operator.lock" +int rx_operator_lock_dir(const char *dir, int create, int *lock_fd, char *why, size_t n); + +/* Lock the control directory (refused if another program holds it), write + * the credential file (0600, temporary file, fsync, rename, all relative to + * the held directory descriptor), wipe `cred`, bind the socket inside the + * held directory and start the listener. The request gate starts * HELD by the caller: no request is served until rx_operator_release. */ int rx_operator_open(RxOperator **out, const RxOperatorConfig *cfg, uint32_t subject, RxCallerCred *cred, RxCapRef cap); /* The request gate: while the program holds it (world setup), requests wait. */ void rx_operator_hold(RxOperator *op); void rx_operator_release(RxOperator *op); -/* Stop the listener, remove the socket and the credential file. The gate - * must not be held by the caller. */ +/* Stop the listener and remove the socket and the credential file, each only + * if it is still the file this instance created (same device and inode), + * then release the control directory lock. The gate must not be held by the + * caller. */ void rx_operator_close(RxOperator *op); #endif diff --git a/tests/r16_qualify/run.sh b/tests/r16_qualify/run.sh index 2a728bf37..dc475488f 100755 --- a/tests/r16_qualify/run.sh +++ b/tests/r16_qualify/run.sh @@ -215,6 +215,29 @@ git -C "$LK" init -q && git -C "$LK" add -A && git -C "$LK" -c user.name=r16 -c git -C "$LK" rev-parse HEAD > "$W/aienos.lock" g add -A; g commit -qm "lock file" export AIENOS_LOCK_REPO=$LK +# Operator receipts (G2): each seat's test writes one; the script copies it into the raw +# directory and checks it against the production binary of the run. Fixture binaries in +# build/ (git-ignored); templates filled with the current HEAD and binary digest by G6Q. +mkdir -p "$W/build" +printf 'host production binary fixture\n' > "$W/build/rx_r13_living_host" +printf 'silicon production binary fixture\n' > "$W/build/rx_r13_living_silicon" +# op_tmpl [sed expression...]: the receipt template of one seat, then edits. +op_tmpl() { + local seat=$1 gate=HOST_PASS_NON_SILICON e; shift + [ "$seat" = silicon ] && gate=PASS + printf '{\n "schema": "AIEN_R16_G6_OPERATOR_CONTROL_V1",\n "seat": "%s",\n "candidate_commit": "@HEAD@",\n "tree_dirty": false,\n "binary": "rx_r13_living_%s",\n "binary_sha256": "@SHA@",\n "checks": 90,\n "failures": 0,\n "skipped": 0,\n "skip_reasons": [],\n "gate": {"R16_G6_OPERATOR": "%s"}\n}\n' \ + "$seat" "$seat" "$gate" > "$G/op_$seat.tmpl" + for e in "$@"; do sed -i "$e" "$G/op_$seat.tmpl"; done +} +op_render() { + local s + for s in host silicon; do + rm -f "$G/operator_${s}_receipt.json" + [ -f "$G/op_$s.tmpl" ] || continue + sed -e "s/@HEAD@/$(g rev-parse HEAD)/" -e "s/@SHA@/$(sha256sum < "$W/build/rx_r13_living_$s" | cut -d' ' -f1)/" \ + "$G/op_$s.tmpl" > "$G/operator_${s}_receipt.json" + done +} # g6log [rc]: fixture log + exit status for one exercising test g6log() { printf '%s\n' "$2" > "$G/$1"; echo "${3:-0}" > "$G/$1.rc"; } g6_good_logs() { @@ -238,8 +261,9 @@ R16 operator gate: R16_G6_OPERATOR=HOST_PASS_NON_SILICON" RX_OPERATOR_MUTANTS: PASS" g6log r16_operator_silicon.log "R16 operator: 100 checks, 0 failures, 0 skipped (silicon, phases: startup control restart kill) R16 operator gate: R16_G6_OPERATOR=PASS" + op_tmpl host; op_tmpl silicon } -G6Q() { Q R16_RUN_ID=g6 2>&1; } +G6Q() { op_render; Q R16_RUN_ID=g6 2>&1; } R=$G/DRY-RUN-receipt.json g6_item() { sed -n 's/^.*"item": "'"$1"'", "status": "\([A-Z_]*\)".*$/\1/p' "$R"; } g6_good_logs @@ -249,7 +273,7 @@ check "G6 all good: twelve items PASS, operator emergency controls among them" ' check "G6 all good: protected_surfaces_kept six presence flags true" '[ "$(grep -c "_present\": true" "$R")" = 6 ]' check "G6 all good: no FAIL anywhere and G6 alone does not make the run pass (exit 3)" '[ $rc = 3 ] && ! echo "$out" | grep -q "G6=FAIL"' check "G6 all good: receipt names file and symbol per item" 'grep -q "\"file\": \"src/runtime/rx_generation.c\", \"symbol\": \"rx_gen_recover\", \"source\": \"omega_tree\", \"defined\": true" "$R"' -check "G6 operated checks cite the test and its status" 'grep -q "{\"name\": \"R9\", \"target\": \"test-r9\", \"status\": \"PASS\"}" "$R"' +check "G6 operated checks cite the test and its status" 'grep -q "{\"name\": \"R9\", \"target\": \"test-r9\", \"seat\": \"host\", \"status\": \"PASS\"}" "$R"' # presence without operation: symbols all defined, tests never ran -> NOT_RUN, never PASS rm -f "$G"/*.log "$G"/*.rc @@ -334,6 +358,67 @@ check "G6 operator: production wiring present only in a comment (string still in g6_unmut out=$(G6Q) check "G6 operator: reverted, all logs passing: PASS" '[ "$(g6_item operator_emergency_controls_passing)" = PASS ]' +# G2: the operator receipt. Good receipts first, then one broken field at a time. +op_item() { g6_item operator_emergency_controls_passing; } +op_test() { jq -r ".g6_items[] | select(.item==\"operator_emergency_controls_passing\") | .tests[] | select(.name==\"$1\") | .$2" "$R"; } +check "G6 operator receipts: both copied into the raw directory and covered by its digest" \ + 'grep -q " operator_host_receipt.json$" "$G/SHA256SUMS" && grep -q " operator_silicon_receipt.json$" "$G/SHA256SUMS" && [ "$(op_item)" = PASS ]' +check "G6 operator: tests labelled by seat (host test host, silicon test silicon)" \ + '[ "$(op_test R16_OP_HOST seat)" = host ] && [ "$(op_test R16_OP_MUTANTS seat)" = host ] && [ "$(op_test R16_OP_SILICON seat)" = silicon ] && [ "$(jq -r .operator_control.silicon.seat "$R")" = silicon ]' +op_bad() { # op_bad