omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
GitHub aien-dev/omega-mv#309 (code only)
Apply it
git checkout -b patch-631220320ffdcdb5 21092e08da5647da63e0ca6e4d7dcc1e26f9e425 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/631220320ffdcdb5.patch | git am
Provenance
github-import 1
aien-dev/omega-mv
309
b2ca115fb925dc0d4c71a40ba4205abe8a42082e
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":309,"url":"https://github.com/aien-dev/omega-mv/pull/309","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:15Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 65be78dd9..f994a392e 100644 --- a/.crumb +++ b/.crumb @@ -51,8 +51,8 @@ "purpose": "Directory calibration. Purpose not yet described by a human." }, { - "digest": "01a9aa128e136ecccdaca33b6babef24d4011a95c2ca1a5dd839d84e2841ce3d", - "last_commit": "38a6a56", + "digest": "01f9bcaf892355eff231425a96bf8f625fc9d9be4c1480991db92b6fefd6cd49", + "last_commit": "96748a2", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -81,39 +81,39 @@ "purpose": "Directory research. Purpose not yet described by a human." }, { - "digest": "4dde878eff597b3669b7dafeb572ba3a560c51ac52d99681524745684c45b258", - "last_commit": "c62f47b", + "digest": "a208771d61d51324273b06beab565036bbc61f3218dfb6cba76d853ec3515073", + "last_commit": "96748a2", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "216a1cd73e993694a7c2ff9580d2b9ec299ddb0876e29ddcaf23e35844ef73bd", - "last_commit": "c2c3073", + "digest": "bf667679bc7c3494f148e83e9d8f56193a3768c2f7145a614a21e701e3bddabd", + "last_commit": "96748a2", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "54875b73cdd1fad056918c0ea3dbadfb1f02ea072a1e2115a8933a202c1d7012", - "last_commit": "6c93c0e", + "digest": "c9825de4f77620c738f1cac290238b55040200959e0938ac03fa41a3c95c488d", + "last_commit": "96748a2", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, { - "digest": "6a6bc2fc769c40efe05fcaaa1bc5169b89e3446d1e427060747b78b43dd729a9", - "last_commit": "6c93c0e", + "digest": "ef22f063312bab17b11019f16b48d0e30d907c7bd1af458b6dbc6923907b517f", + "last_commit": "96748a2", "name": "tools", "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:ec128923135d5c8ffefa1d9295d0046f313f600cd30f09e04b4096ba92e1d7b4", - "compiled_at": "2026-10-05T22:53:19Z", + "children_root": "sha256:51f1e1336815973b126e9f70072b8f3bb765d6088310ab5d70c5787b77e93997", + "compiled_at": "2026-10-06T00:26:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:64c48291581e4edd8e53b866b55e3d4b3217c6f98c5147eee2d1f685c0b3a2f8", + "digest": "sha256:a3e434d50da665e07aec3de6c4c65b3aa19099beb5f41981b7d8119fb6dddab5", "evidence_files": 3304, "evidence_root": "sha256:9594e3e2a05603747e60ab08376dcf98a6857a89e43720f33126d5b68e41f4d1", - "files": 5109, - "generated_at_commit": "120e281a85954a716fc6693a5592759df330f78f", - "source_tree": "sha256:50d7628ab849023c4a45f54a8e11a21480322b2ea458e57d1ee616cdbfc2e767" + "files": 5115, + "generated_at_commit": "96748a2078862997c4ee423797ed4d1a99dcf300", + "source_tree": "sha256:fc575a3688dbd5f8b40cc9933da2ff056ece6af0d601a81e5c4c93d25a99e1b3" }, "owner_lane": "", "provenance": { diff --git a/.github/workflows/host-suites-2.yml b/.github/workflows/host-suites-2.yml index 313adae71..8d983f86a 100644 --- a/.github/workflows/host-suites-2.yml +++ b/.github/workflows/host-suites-2.yml @@ -51,6 +51,12 @@ 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()), 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/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/.crumb b/docs/.crumb index b1461bf83..8c941367a 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-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:01a9aa128e136ecccdaca33b6babef24d4011a95c2ca1a5dd839d84e2841ce3d", + "digest": "sha256:01f9bcaf892355eff231425a96bf8f625fc9d9be4c1480991db92b6fefd6cd49", "evidence_files": 34, "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc", - "files": 112, - "generated_at_commit": "25311c0c2aee4eb4991052115d9ad91f5b4d2a1e", - "source_tree": "sha256:cb189c97510cfdc47126abee0105eb8dba61520c3f654644838eba1f08a930ad" + "files": 113, + "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 new file mode 100644 index 000000000..597a69a9f --- /dev/null +++ b/docs/r16-operator-control.md @@ -0,0 +1,294 @@ +# R16 G6: operator control of the production program (interface contract) + +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 +`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 + `<state>/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 `<state>/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. +* **One program per state directory.** At startup the program takes an exclusive + `flock` on `<dir>/operator.lock` (opened `O_CLOEXEC|O_NOFOLLOW`, a regular file of its + uid) and, when a world first uses it, on `<dir>/gen-<mode-key>/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/<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 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. +* Client: `build/rx_operator` (`tools/rx_operator.c`). It reads the credential file and + sends one request: `rx_operator --control <state>/control <command> [reason]`, or + `--cred <file>` to present another file (used by the tests for stale and forged + credentials), or `--raw <line>` (malformed-request tests). + +## 3. Formats + +Credential file (text): + +``` +aien-operator-credential v1 +world <mode-key> <program pid> <world start CLOCK_REALTIME ns> +socket <absolute socket path> +subject 70 +cred <generation> <64 hex secret> +cap <cap_id> <cap generation> +``` + +Request (one line): + +``` +aien-operator v1 <command> subject=<u32> gen=<u64> secret=<64 hex> cap=<id>:<gen> deadline=<u64> [reason=<int>] +``` + +`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. + +`<command>` 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 <RESULT> 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=<n> (<text>)`), +`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=<n>`. +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`, +`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= 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` | +| `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 <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: `<dir>/control/` (credential file and socket) and one generation store per mode, + `<dir>/gen-<mode-key>/` (`positive`, `no-aien`, `no-promotion`, `revoked-experiment`, + `stale-gpu`, `failed-verification`). +* **Validated at startup, refuse if wrong.** `<dir>` and each subdirectory must be a real + 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. +* **The durable halt directory is the generation store's directory**: + `rx_world_set_halt_dir(w, <dir>/gen-<mode-key>)`, 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.<seq>.<t_ns>` 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 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 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 <mode-key>: 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. + +### 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 +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; 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 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_<seat>_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/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 <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. `<dir>/gen-<mode>/` is each mode's generation store and +also its durable halt directory; `<dir>/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/.crumb b/spec/.crumb index eb6e3f7ae..497aafead 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-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:4dde878eff597b3669b7dafeb572ba3a560c51ac52d99681524745684c45b258", + "digest": "sha256:a208771d61d51324273b06beab565036bbc61f3218dfb6cba76d853ec3515073", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 56, - "generated_at_commit": "b3f7c97a22a105748d4dc4cf5bd34ca2e912f853", - "source_tree": "sha256:cf38443997fd6250145703f37288a5141786e8d878db262612464e33a5663d17" + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:7dd1a87e6835f7a9c18cd979acbcfa96f53a8fa6ac309fccbb015470b024823f" }, "owner_lane": "", "provenance": { 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/spec/r16-orchestrator-retirement-map.md b/spec/r16-orchestrator-retirement-map.md index a3f9845ed..15fc89faf 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 {` | @@ -652,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-<name>`, 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))` | <!-- /r16-inventory:rows --> ## 5. Structural findings (non-greppable §4 terms) @@ -914,3 +919,36 @@ 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. + +### 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 0eb185b4e..d0e514468 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": "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:100d089dae58ac28d48f3c8e0426a60913380b117fd49f9e54ee33620370ff25", - "compiled_at": "2026-10-05T20:10:00Z", + "children_root": "sha256:920218d42490379078986bd65f6d50e8ef9064df20da67bfc0ca50ea0de4b4c0", + "compiled_at": "2026-10-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:216a1cd73e993694a7c2ff9580d2b9ec299ddb0876e29ddcaf23e35844ef73bd", + "digest": "sha256:bf667679bc7c3494f148e83e9d8f56193a3768c2f7145a614a21e701e3bddabd", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 406, - "generated_at_commit": "f8ce768210e58d33e675a7bbae2208ccbfc58db7", - "source_tree": "sha256:d2d655d8913f1943c3e771446f0d82a900b32e690527cde887157aef0e74de8d" + "files": 408, + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:d171d30065cacc0d402c1013b920ad3cf4392e78ed56d71fd0fa4669a2ac865b" }, "owner_lane": "", "provenance": { diff --git a/src/runtime/.crumb b/src/runtime/.crumb index afd44ab97..b30b38677 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-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:7927099dac3838db8f33a305a185873d9610c7c496fc3763ec9e5dc9e901bb9d", + "digest": "sha256:63f3df62adf0a29ee2fdfdc4e170409de18f8a2a33c5644ab8d4009cf1c5246f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 59, - "generated_at_commit": "f8ce768210e58d33e675a7bbae2208ccbfc58db7", - "source_tree": "sha256:6eede518faaae5783b6f84140535af1105d811b5975bffdda56934065ac91687" + "files": 61, + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:d6c5fe7ac0396ceedc2c666adae44e38d9c03553974f120898eea988cbc033a4" }, "owner_lane": "", "provenance": { 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..8cbd3aef8 --- /dev/null +++ b/src/runtime/rx_operator.c @@ -0,0 +1,549 @@ +/* R16 G6 operator entry point (docs/r16-operator-control.md). */ +#include "rx_operator.h" + +#include <errno.h> +#include <fcntl.h> +#include <poll.h> +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/file.h> +#include <sys/socket.h> +#include <sys/stat.h> +#include <sys/un.h> +#include <time.h> +#include <unistd.h> + +struct RxOperator { + RxOperatorConfig cfg; + char sock_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; + 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; + int thread_live; + pthread_mutex_t gate; /* held by the program while it sets the world up */ +}; + +/* 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 (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, + (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; +} + +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]); +} + +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; +} + +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) { + 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" + "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; + 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;) { + 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 (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 && 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 { + char cmd[16]; + uint32_t subject; + RxCallerCred cred; + RxCapRef cap; + int32_t 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; + 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 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 || !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; +} + +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); + 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)) { + 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 " + "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) { + 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_own(op, RX_OPERATOR_CRED, &op->cred_st, &op->cred_made); + 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}; + /* 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"); + 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); + /* 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; + 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; + } + } + /* 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 + * 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[320]; + RxOperator *op = calloc(1, sizeof *op); + if (!op) return -1; + op->cfg = *cfg; + 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(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"); + 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; + } + struct sockaddr_un a; + memset(&a, 0, sizeof a); + a.sun_family = AF_UNIX; + 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); + 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; + *out = op; + 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; +} + +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]); + /* 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 new file mode 100644 index 000000000..5140f3bd8 --- /dev/null +++ b/src/runtime/rx_operator.h @@ -0,0 +1,68 @@ +#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 <stddef.h> +#include <stdint.h> + +#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 (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); + +/* 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 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/src/runtime/rx_world.c b/src/runtime/rx_world.c index d5a711ca1..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 */ @@ -1153,6 +1155,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); @@ -1837,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--; @@ -2558,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 5743a3e22..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 @@ -824,6 +826,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/.crumb b/tests/.crumb index 12349e8ac..0484543a0 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -253,8 +253,8 @@ "purpose": "Directory tests/relations. Purpose not yet described by a human." }, { - "digest": "71ee11a9ea01b73efaf1c3f4fa3495aa98cc7d610b5570ce591f0718bb25a4d4", - "last_commit": "c2c3073", + "digest": "810c8881a76b9617e39a887e006c69f51301e96ebcdda35478a7060fc8788b75", + "last_commit": "96748a2", "name": "runtime", "purpose": "Directory tests/runtime. Purpose not yet described by a human." }, @@ -283,15 +283,15 @@ "purpose": "Directory tests/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:5e49c39abb592f9a527e51b78cbb625925b7c4421476815cdcebe6b394a7ecda", - "compiled_at": "2026-10-05T22:53:19Z", + "children_root": "sha256:cc7551dc7594896ade97e5a5f78205cd93aad4878acd6e114b6b188e02ff10e6", + "compiled_at": "2026-10-06T00:26:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:54875b73cdd1fad056918c0ea3dbadfb1f02ea072a1e2115a8933a202c1d7012", + "digest": "sha256:c9825de4f77620c738f1cac290238b55040200959e0938ac03fa41a3c95c488d", "evidence_files": 11, "evidence_root": "sha256:d5c1bceb4d57ef0eb42797c58801b5926509711614c3e38bb7105b6efa3942f2", - "files": 808, - "generated_at_commit": "120e281a85954a716fc6693a5592759df330f78f", - "source_tree": "sha256:c903806bc7979b01d455ddbe31854fd4385adaf591a3ec46adf07edd35865d82" + "files": 810, + "generated_at_commit": "96748a2078862997c4ee423797ed4d1a99dcf300", + "source_tree": "sha256:7cb4aeb7d1d40a33eb72f6873af832428d8c6c91bcf40b01eb8d231560ad6977" }, "owner_lane": "", "provenance": { diff --git a/tests/r16_qualify/run.sh b/tests/r16_qualify/run.sh index e2b3b0b2b..dc475488f 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" @@ -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 <seat> [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 <file> <pattern> [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() { @@ -232,18 +255,25 @@ 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" + 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 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"' -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 @@ -283,7 +313,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 +321,105 @@ 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 ]' +# 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 <label> <seat> <sed expression>: that receipt broken: item FAIL + OPSEAT=$2; op_tmpl "$2" "$3"; out=$(G6Q) + check "G6 operator receipt $1: item FAIL" '[ "$(op_item)" = FAIL ] && echo "$out" | grep -q "operator $OPSEAT receipt: FAIL"' + op_tmpl "$2" +} +op_bad "binary digest is not the binary built in the run (host)" host 's/@SHA@/0000000000000000000000000000000000000000000000000000000000000000/' +op_bad "binary digest is not the binary built in the run (silicon)" silicon 's/@SHA@/1111111111111111111111111111111111111111111111111111111111111111/' +op_bad "written by a mutant run (binary prog)" host 's/"binary": "rx_r13_living_host"/"binary": "prog"/' +op_bad "another candidate commit" silicon 's/@HEAD@/0123456789abcdef0123456789abcdef01234567/' +op_bad "dirty tree" host 's/"tree_dirty": false/"tree_dirty": true/' +op_bad "a skipped case" silicon 's/"skipped": 0/"skipped": 1/' +op_bad "a failure" host 's/"failures": 0/"failures": 2/' +op_bad "the host gate in the silicon receipt" silicon 's/"R16_G6_OPERATOR": "PASS"/"R16_G6_OPERATOR": "HOST_PASS_NON_SILICON"/' +op_bad "the silicon seat in the host slot" host 's/"seat": "host"/"seat": "silicon"/' +rm -f "$G/op_host.tmpl"; out=$(G6Q) +check "G6 operator: host log passing but no host receipt: item FAIL" '[ "$(op_item)" = FAIL ]' +op_tmpl host +printf 'changed after the test\n' >> "$W/build/rx_r13_living_silicon" +sed -i "s/@SHA@/$(sha256sum < "$W/build/rx_r13_living_silicon" | cut -d' ' -f1)/" "$G/op_silicon.tmpl" +printf 'rebuilt\n' >> "$W/build/rx_r13_living_silicon"; out=$(G6Q) +check "G6 operator: silicon binary rebuilt after its test: item FAIL" '[ "$(op_item)" = FAIL ]' +op_tmpl silicon; out=$(G6Q) +check "G6 operator: receipts restored: PASS" '[ "$(op_item)" = PASS ]' +# G7: a run that only skipped a case (gate NOT_RUN, exit 0) is NOT_RUN, never FAIL. +g6log r16_operator_host.log "[SKIPPED] unauthorized: a peer of another uid needs sudo -n (no passwordless sudo here) +R16 operator: 85 checks, 0 failures, 1 skipped (host, phases: startup control restart kill) +R16 operator gate: R16_G6_OPERATOR=NOT_RUN (1 SKIPPED)" +op_tmpl host 's/"skipped": 0/"skipped": 1/' 's/"HOST_PASS_NON_SILICON"/"NOT_RUN (1 SKIPPED)"/'; out=$(G6Q) +check "G6 operator: host run without sudo (NOT_RUN gate, exit 0): test NOT_RUN, not FAIL" '[ "$(op_test R16_OP_HOST status)" = NOT_RUN ] && [ "$(op_item)" = NOT_RUN ]' +g6log r16_operator_host.log "[SKIPPED] unauthorized: a peer of another uid needs sudo -n (no passwordless sudo here) +R16 operator gate: R16_G6_OPERATOR=NOT_RUN (1 SKIPPED)" 1 +out=$(G6Q) +check "G6 operator: the same NOT_RUN line with exit 1: FAIL" '[ "$(op_test R16_OP_HOST status)" = FAIL ]' +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" +op_tmpl host +g6log r16_operator_mutants.log "SKIPPED O7 peer uid check removed: the test could not run the case that kills it +RX_OPERATOR_MUTANTS: NOT_RUN (SKIPPED cases)" 3 +out=$(G6Q) +check "G6 operator: mutants NOT_RUN (exit 3): test NOT_RUN, not FAIL" '[ "$(op_test R16_OP_MUTANTS status)" = NOT_RUN ]' +g6log r16_operator_mutants.log "RX_OPERATOR_MUTANTS: PASS" +# G3: silicon_observed needs every silicon run, the operator silicon test included. +g6log r16_authpath_host.log "R16 gate: R16_G3_AUTHPATH=HOST_PASS_NON_SILICON" +g6log r16_authpath_silicon.log "R16 gate: R16_G3_AUTHPATH=PASS" +g6log r13_silicon.log "R13 gate: R13_LIVING_SYSTEM=PASS" +out=$(G6Q) +check "G3 silicon_observed: every silicon run passed, the operator silicon run included: true" 'grep -q "\"silicon_observed\": true" "$R"' +rm -f "$G/r16_operator_silicon.log" "$G/r16_operator_silicon.log.rc"; out=$(G6Q) +check "G3 silicon_observed: the five other silicon runs passed, operator silicon not run: false" 'grep -q "\"silicon_observed\": false" "$R"' +g6log r16_operator_silicon.log "R16 operator gate: R16_G6_OPERATOR=PASS" +op_tmpl silicon 's/@SHA@/2222222222222222222222222222222222222222222222222222222222222222/'; out=$(G6Q) +check "G3 silicon_observed: operator silicon log passing but its receipt unbound: false" 'grep -q "\"silicon_observed\": false" "$R"' +op_tmpl silicon +rm -f "$G"/r16_authpath_*.log* "$G/r13_silicon.log" "$G/r13_silicon.log.rc" + # 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 +504,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/.crumb b/tests/runtime/.crumb index 3e48c3c44..a90aa9223 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-06T00:23:42Z", "compiler": "crumb-compile/1", - "digest": "sha256:71ee11a9ea01b73efaf1c3f4fa3495aa98cc7d610b5570ce591f0718bb25a4d4", + "digest": "sha256:810c8881a76b9617e39a887e006c69f51301e96ebcdda35478a7060fc8788b75", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 58, - "generated_at_commit": "f8ce768210e58d33e675a7bbae2208ccbfc58db7", - "source_tree": "sha256:0e2d0c40beb2bbf8d4a9aca98a69a382d6b0501e33f4dab682c4c7f8861b62f9" + "files": 60, + "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", + "source_tree": "sha256:702ddece6dd8b6ca6319e8e6624783ccee2efc24dc7a911b12a9ca47d90449f0" }, "owner_lane": "", "provenance": { diff --git a/tests/runtime/rx_operator_host.sh b/tests/runtime/rx_operator_host.sh new file mode 100644 index 000000000..ad1126cc1 --- /dev/null +++ b/tests/runtime/rx_operator_host.sh @@ -0,0 +1,562 @@ +#!/bin/bash +# R16 G6 operator control by execution (docs/r16-operator-control.md §7). +# +# rx_operator_host.sh <host|silicon> <production R13 binary> <rx_operator client> +# +# 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 with its reason 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). +# +# Host only, deterministic holds: the first program start of the control phase +# runs under gdb in non-stop mode (only the thread at a breakpoint pauses; the +# operator socket keeps serving). Three temporary breakpoints hold one point +# each until the test has sent its request, then the test resumes the thread: +# 1 rx_resident_accept the seat acceptor holding a computed seat result +# (an activation in flight): the stop must cancel it +# 2 rx_world_verify_crumbs the positive episode's work is done, its world is +# not yet torn down: a stop here must keep it up +# 3 rx_operator_open (2nd) the next world's open, after the positive world's +# entry point closed: what close removed is visible +# Without gdb those checks are SKIPPED (gate NOT_RUN). Silicon runs without +# gdb: its in-flight count is reported, not checked. +# +# Environment: RX_OP_PHASES (default "startup control restart kill") runs a +# subset (mutants); RX_OP_FAILFAST=1 stops at the first failed check (host); +# RX_OP_OUT (default build/r16-operator) receives the receipt and the logs of +# a failed run. +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} +OUT=${RX_OP_OUT:-$HERE/build/r16-operator} +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; SKIP_WHY=(); PID=""; GPID="" +SUDO=0; if sudo -n true 2>/dev/null; then SUDO=1; fi +HOLD=0; if [ "$SEAT" = host ] && command -v gdb >/dev/null 2>&1; then HOLD=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 + if [ -n "$GPID" ]; then echo quit 2>/dev/null >&7; sleep 0.2; kill -9 "$GPID" 2>/dev/null; wait "$GPID" 2>/dev/null; fi + [ "$SUDO" = 1 ] && sudo -n rm -rf "$W" 2>/dev/null || rm -rf "$W" +} +trap cleanup EXIT + +receipt() { + local commit dirty sum why="" r + mkdir -p "$OUT" + 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) + for r in "${SKIP_WHY[@]+"${SKIP_WHY[@]}"}"; do why="$why${why:+, }\"$r\""; done + cat > "$OUT/operator_${SEAT}_receipt.json" <<EOF +{ + "schema": "AIEN_R16_G6_OPERATOR_CONTROL_V1", + "seat": "$SEAT", + "seat_description": "$([ "$SEAT" = silicon ] && echo "production GB10 program, resident Blackwell seat" || echo "production host program, R12 processor stand-in (not silicon)")", + "candidate_commit": "$commit", + "candidate_env": "${OMEGA_CANDIDATE_COMMIT:-}", + "tree_dirty": $dirty, + "binary": "$(basename "$BIN")", + "binary_sha256": "$sum", + "phases": "$PHASES", + "held_by_gdb": $([ "$HOLD" = 1 ] && echo true || echo false), + "checks": $CHECKS, + "failures": $FAILS, + "skipped": $SKIPS, + "skip_reasons": [$why], + "gate": {"R16_G6_OPERATOR": "$1"} +} +EOF + echo "R16 operator receipt: $OUT/operator_${SEAT}_receipt.json" +} + +finish() { + local gate + if [ "$FAILS" -gt 0 ]; then gate=FAIL + elif [ "$SKIPS" -gt 0 ]; then gate="NOT_RUN ($SKIPS SKIPPED)" + 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="$OUT/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 ] + exit $? +} + +check() { # check <label> <shell condition> + CHECKS=$((CHECKS + 1)) + if eval "$2"; then echo "[+] $1" + else + echo "[-] $1"; FAILS=$((FAILS + 1)) + echo " last reply (client exit $OPRC): $(printf '%s' "$REPLY_" | head -c 300)" + if [ "$FAILFAST" = 1 ]; then finish; fi + fi +} +skip() { echo "[SKIPPED] $1"; SKIPS=$((SKIPS + 1)); SKIP_WHY+=("$1"); } + +REPLY_=""; OPRC=0 +op() { REPLY_=$("$CLI" "$@" 2>&1); OPRC=$?; return $OPRC; } # op <client args>: sets REPLY_, OPRC +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 <state dir> <log> + "$BIN" --state-dir "$1" > "$2" 2>&1 < /dev/null & + PID=$! +} +# start_held <state dir> <log>: the program under gdb (host), PID = the program itself. +start_held() { + local g="$W/hold.gdb" f="$W/hold.fifo" i=0 + cat > "$g" <<'EOF' +set debuginfod enabled off +set pagination off +set confirm off +set non-stop on +set startup-with-shell off +set print thread-events off +set print inferior-events on +handle SIGPIPE nostop noprint pass +tbreak rx_resident_accept +tbreak rx_world_verify_crumbs +tbreak rx_operator_open +ignore 3 1 +run +EOF + mkfifo -m 600 "$f" && exec 7<>"$f" + gdb -nx -q -x "$g" --args "$BIN" --state-dir "$1" <&7 > "$2" 2>&1 & + GPID=$!; PID="" + while [ $i -lt $((WORLD_WAIT * 20)) ]; do + PID=$(sed -n 's/^R13 operator: state .* pid \([0-9][0-9]*\))$/\1/p' "$2" | head -1) + [ -n "$PID" ] && return 0 + kill -0 "$GPID" 2>/dev/null || return 1 + sleep 0.05; i=$((i + 1)) + done + return 1 +} +held() { # held <n>: the program's thread is paused at temporary breakpoint n + local i=0 + while [ $i -lt $((WORLD_WAIT * 20)) ]; do + grep -Eq "hit Temporary breakpoint $1, " "$LA" && return 0 + alive || return 1 + sleep 0.05; i=$((i + 1)) + done + return 1 +} +release() { echo "continue -a" >&7; } # resume every paused thread +alive() { [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; } +# wait_world <state> <mode-key>: 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 <log> <fixed text> [seconds]: until the program printed it (or exited) + local i=0 lim=$((${3:-$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). +# Under gdb the exit status is the one gdb reports for the program. +wait_exit() { + local i=0 lim=$((EXIT_WAIT * 20)) late=0 code + 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 + if [ -n "$GPID" ]; then + i=0; while [ $i -lt 200 ] && ! grep -Eq '^\[Inferior 1 \(process [0-9]+\) exited|terminated with signal' "$LA"; do sleep 0.05; i=$((i + 1)); done + if grep -Eq '^\[Inferior 1 \(process [0-9]+\) exited normally\]' "$LA"; then RC=0 + else + code=$(sed -n 's/^\[Inferior 1 (process [0-9]*) exited with code \([0-7]*\)\]$/\1/p' "$LA" | head -1) + if [ -n "$code" ]; then RC=$((8#$code)); else RC=137; fi + fi + echo quit >&7; wait "$GPID" 2>/dev/null; exec 7>&-; GPID="" + else + wait "$PID"; RC=$? + fi + PID="" + [ $late = 0 ] || RC=124 +} +# dup_run <state dir> <log>: start a second program and wait up to 20 s for it to exit; +# sets rc (124 if it was still running: the lock did not refuse it). Host: it is then +# killed. Silicon: it is stopped and shut down through its own entry point (a chip +# program is never killed). +dup_run() { + "$BIN" --state-dir "$1" > "$2" 2>&1 < /dev/null & + local d=$! i=0 + while kill -0 "$d" 2>/dev/null && [ $i -lt 400 ]; do sleep 0.05; i=$((i + 1)); done + if kill -0 "$d" 2>/dev/null; then + echo "a second program on $1 is still running after 20 s" + if [ "$SEAT" = host ]; then kill -9 "$d" 2>/dev/null + else "$CLI" --control "$1/control" stop >/dev/null 2>&1; "$CLI" --control "$1/control" shutdown >/dev/null 2>&1; fi + wait "$d" 2>/dev/null; rc=124; return + fi + wait "$d"; rc=$? +} +sealed() { # sealed <file>: last line is "sha256 <64 hex>" + [ -f "$1" ] && tail -n 1 "$1" | grep -Eq '^sha256 [0-9a-f]{64}$' +} +forge() { # forge <cred in> <cred out> <sed expression> + sed -e "$3" "$1" > "$2"; chmod 600 "$2" +} +audit_ok() { # audit_ok <log> <mode-key> <stops> <resumes> <restored> + 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" +} +# raw <cred file> <command> [fields | -]: a request line with that credential and a +# deadline the client fills in (@deadline@), or the given fields, or no field (-). +raw() { + local c=$1 cmd=$2; shift 2 + local f; f=$(sed -n 's/^cred \([0-9]*\) \([0-9a-f]*\)$/gen=\1 secret=\2/p' "$c") + local k; k=$(sed -n 's/^cap \([0-9]*\) \([0-9]*\)$/cap=\1:\2/p' "$c") + local s; s=$(sed -n 's/^subject \([0-9]*\)$/subject=\1/p' "$c") + local x="${*:-deadline=@deadline@}"; [ "$x" = - ] && x="" + echo "aien-operator v1 $cmd $s $f $k${x:+ $x}" +} + +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 (no passwordless sudo here)" + 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"; SEQ=0 +if [[ " $PHASES " == *" control "* ]] || [[ " $PHASES " == *" restart "* ]]; then + if [ "$HOLD" = 1 ] && [[ " $PHASES " == *" control "* ]]; then + check "control: the production program starts under gdb (non-stop holds)" 'start_held "$S" "$LA"' + else + start_prog "$S" "$LA" + fi + 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 + 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 + [ "$SEAT" = host ] && [ "$HOLD" = 0 ] && skip "control: the deterministic in-flight, end-of-episode and close holds need gdb (not installed)" + # 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; SEQ=1 + check "stop: authorized stop accepted, durable, the first stop of this world (client exit 0)" \ + '[ $OPRC = 0 ] && 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" ]' + + # One program per state directory (S1): a second program on the same state, or on + # this program's generation (halt) directory, is refused before it touches the + # socket or the credential, and the first program stays controllable. + ino1=$(stat -c %i "$C/operator.sock"); cr1=$(sha256sum < "$C/operator.cred") + dup_run "$S" "$W/dup1.log" + check "lock: a second program on the same state directory is refused (exit 2, names the holder)" \ + '[ $rc = 2 ] && grep -q "state directory refused: .* is in use by another program (pid $PID)" "$W/dup1.log"' + dup_run "$S/gen-positive" "$W/dup2.log" + check "lock: a second program on the first one's generation directory is refused" \ + '[ $rc = 2 ] && grep -q "in use by another program (pid $PID)" "$W/dup2.log" && [ ! -e "$S/gen-positive/control" ]' + op --control "$C" status + check "lock: the first program keeps its socket and credential and stays controllable" \ + 'has "OK state=stopped" && [ "$(kv seq)" = 1 ] && [ "$(stat -c %i "$C/operator.sock")" = "$ino1" ] && [ "$(sha256sum < "$C/operator.cred")" = "$cr1" ]' + + # 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=' + op --cred "$W/wrongcap" --control "$C" stop + check "unauthorized: another capability, stop REFUSED authority" 'has "REFUSED reason=authority"' + 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"' + # S3: the socket routes the operator capability only to stop, resume and the + # authorized status/shutdown/revoke commands. Anything else, with a full valid + # credential, is refused before any authority call. + bad="" + for c in explode bump-epoch bump_epoch mint grant epoch STOP Stop stop2 resume2 halt; do + op --control "$C" --raw "$(raw "$W/cred-positive" "$c")" + has "aien-operator v1 BAD_REQUEST" || bad="$bad $c" + done + check "unknown commands with a full credential are BAD_REQUEST (11 commands${bad:+, accepted:$bad})" '[ -z "$bad" ]' + op --control "$C" --raw "$(raw "$W/cred-positive" resume reason=1 deadline=@deadline@)" + check "unauthorized: a field the command does not take (resume reason=) 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: a peer of another uid needs sudo -n (no passwordless sudo here)" + fi + op --cred "$W/forged" --control "$C" resume + check "unauthorized: a forged resume is REFUSED" 'has "REFUSED reason=identity"' + op --cred "$W/wrongcap" --control "$C" resume + 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"' + # S4: a request whose client already gave up is never run late (resume), and a + # request without a deadline, or with one beyond the client's wait, is malformed. + op --control "$C" --raw "$(raw "$C/operator.cred" resume deadline=1)" + check "expired: a resume whose client deadline passed answers EXPIRED and does nothing" 'has "aien-operator v1 EXPIRED"' + op --control "$C" --raw "$(raw "$C/operator.cred" resume deadline=18000000000000000000)" + check "expired: a deadline beyond the client's wait is BAD_REQUEST" 'has "BAD_REQUEST"' + op --control "$C" --raw "$(raw "$C/operator.cred" resume -)" + check "expired: a resume without a deadline is BAD_REQUEST" 'has "BAD_REQUEST"' + sleep 2 + op --control "$C" status + 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 + 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"' + + # S2: a stop that cannot be written to disk is in force in memory but would not + # survive a restart. Its reply and the client's exit code say so. + if [ "$(id -u)" != 0 ]; then + chmod 500 "$S/gen-positive" + op --control "$C" stop 12; SEQ=2 + chmod 700 "$S/gen-positive" + check "not durable: a stop whose mark cannot be written answers STOPPED_NOT_DURABLE errno=13, client exit 3" \ + '[ $OPRC = 3 ] && has "STOPPED_NOT_DURABLE state=stopped" && [ "$(kv seq)" = 2 ] && [ "$(kv durable)" = -13 ] && [ "$(kv errno)" = 13 ] && [ ! -e "$M" ]' + op --control "$C" status + check "not durable: the stop is in force (status stopped, durable -13)" 'has "OK state=stopped" && [ "$(kv durable)" = -13 ]' + op --control "$C" resume + check "not durable: resume accepted" 'has "OK state=running" && [ "$(kv seq)" = 2 ]' + else + skip "not durable: an unwritable halt directory cannot be made as root" + fi + STOPS=$SEQ + + # In flight (G6), host: the acceptor thread is paused holding a computed seat + # result, the stop is accepted, then the thread goes on: the result must be + # refused at commit and the seat claim end halted, every run. + if [ "$HOLD" = 1 ]; then + check "in-flight: the seat acceptor is paused holding a computed seat result (breakpoint 1)" 'held 1' + op --cred "$W/cred-positive" --control "$C" stop 9; SEQ=$((SEQ + 1)); STOPS=$SEQ + check "in-flight: the stop is accepted while that activation is in flight" 'has "OK state=stopped" && [ "$(kv seq)" = $SEQ ]' + release + ok=0; i=0 + while [ $i -lt 200 ]; do # waits for the released thread, never repeats the stop + op --cred "$W/cred-positive" --control "$C" status + [ "$(kv seat_halted)" -ge 1 ] 2>/dev/null && { ok=1; break; }; sleep 0.05; i=$((i + 1)) + done + check "in-flight: the held result was refused at commit (cancelled $(kv cancelled), seat_halted $(kv seat_halted))" \ + '[ $ok = 1 ] && [ "$(kv cancelled)" -ge 1 ] && has "state=stopped"' + op --cred "$W/cred-positive" --control "$C" resume + check "in-flight: resume accepted" 'has "OK state=running"' + fi + 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)" = $SEQ ] && [ ! -e "$M" ]' + + # Under production load: 12 stop/resume cycles. Every request carries the positive + # world's own credential, so a stop can never land in the next world. On host the + # positive world cannot end during them (breakpoint 2 holds its end), so all 12 run. + cycles=0 + for i in $(seq 1 12); do + op --cred "$W/cred-positive" --control "$C" stop 9 || break + has "OK state=stopped" || break + sleep 0.05 + op --cred "$W/cred-positive" --control "$C" resume || break + has "OK state=running" || break + cycles=$((cycles + 1)) + done + STOPS=$((STOPS + cycles)) + if [ "$HOLD" = 1 ]; then + check "load: 12 of 12 stop/resume cycles while the positive world runs ($cycles)" '[ $cycles = 12 ]' + else + check "load: at least 6 of 12 stop/resume cycles while the positive world runs ($cycles)" '[ $cycles -ge 6 ]' + fi + + if [ "$HOLD" = 1 ]; then + # End of episode (G5 M-a): the positive episode's work is done and its world is + # paused before teardown. A stop there must keep the world up, stopped, until + # the operator resumes it. + check "end of episode: the positive world's work is done, the world is paused before teardown (breakpoint 2)" 'held 2' + op --cred "$W/cred-positive" --control "$C" stop 10; STOPS=$((STOPS + 1)) + check "end of episode: the stop is accepted" 'has "OK state=stopped"' + release + check "end of episode: the program says it waits for an operator resume" \ + 'wait_line "$LA" "R13 operator positive: stopped after its episode; waiting for an operator resume" 10' + sleep 2 + op --cred "$W/cred-positive" --control "$C" status + check "end of episode: two seconds later the positive world is still up and stopped, not audited, not ended" \ + 'has "OK state=stopped" && has "world=positive" && ! grep -q "^R13 operator positive: stops" "$LA"' + # Close removes only what this instance made: a credential file another program + # put in its place must still be there after the positive world closed. + printf 'aien-operator-credential v1\nforeign %s\n' "$$" > "$C/.plant"; chmod 600 "$C/.plant" + mv -f "$C/.plant" "$C/operator.cred" + op --cred "$W/cred-positive" --control "$C" resume + check "end of episode: resume accepted" 'has "OK state=running"' + check "close: the next world's open is paused after the positive world closed (breakpoint 3)" 'held 3' + check "close: the positive world's close left the credential file it did not create" \ + 'grep -qx "foreign $$" "$C/operator.cred"' + release + fi + check "positive world: the promotion happens after the resume (generation advanced)" 'wait_line "$LA" "R13 positive: generation"' + check "positive world: crumb log shows $STOPS stops, as many resumes, nothing committed or published under a stop" \ + 'audit_ok "$LA" positive $STOPS $STOPS 0' + cancelled=$(sed -n 's/^R13 operator positive: .*cancelled \([0-9]*\);.*$/\1/p' "$LA") + if [ "$HOLD" = 1 ]; then + check "in-flight: the crumb log counts the cancelled activations (${cancelled:-?})" '[ "${cancelled:-0}" -ge 1 ]' + else + echo "in-flight ($SEAT, informational): activations cancelled by a stop: ${cancelled:-?}" + fi + + # 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 + # Host: the stand-in is never silicon. Silicon: only a full PASS (bound to the + # candidate commit, clean tree, silicon observed) counts; the spec allows no other. + if [ "$SEAT" = host ]; then want="R13 gate: R13_LIVING_SYSTEM=HOST_PASS_NON_SILICON"; else want="R13 gate: R13_LIVING_SYSTEM=PASS"; fi + check "recovery: the program completes every mode and its R13 gate is ${want#R13 gate: } (exit 0)" \ + '[ $RC = 0 ] && grep -q "R13 control C:" "$LB" && grep -Eq "^${want}( |$)" "$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 (the dead program's lock is gone with it)" '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..8dbb8a790 --- /dev/null +++ b/tests/runtime/rx_operator_mutants.sh @@ -0,0 +1,93 @@ +#!/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. +# Every run writes its receipt and failed logs under its own directory in the +# scratch area (RX_OP_OUT), never over build/r16-operator. +# +# rx_operator_mutants.sh <rx_operator client> +# 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) {/ +O15 end-of-episode wait turned off (G5 M-a)|tests/runtime/rx_r13_living.c|control|s/if \(rc == 0 && r->ready && world_halted\(r\)\) \{/if (0 \&\& rc == 0 \&\& r->ready \&\& world_halted(r)) {/ +O16 episode shape ignores halted seat claims (G5 M-b)|tests/runtime/rx_r13_living.c|control|s/r->w\.stats\.resident_claims - r->w\.stats\.resident_halted != RX_LIVING_TRIALS/r->w.stats.resident_claims != RX_LIVING_TRIALS/ +O17 control directory lock not taken (S1)|src/runtime/rx_operator.c|control|s/if \(flock\(fd, LOCK_EX \| LOCK_NB\) != 0\) \{/if (0) {/ +O18 state directory not locked (S1)|tests/runtime/rx_r13_living.c|control|s/rx_operator_lock_dir\(g_state_dir, 1, &g_state_lock, why, sizeof why\) != 0/(g_state_lock < -1 || rx_operator_dir_check(g_state_dir, 1, why, sizeof why) != 0)/ +O19 generation directory not locked (S1)|tests/runtime/rx_r13_living.c|control|s/\(g_gen_lock\[mode\] < 0 &&\n\s+rx_operator_lock_dir\(r->generation_dir, 1, &g_gen_lock\[mode\], why, sizeof why\) != 0\)/(g_gen_lock[mode] < -1 || rx_operator_dir_check(r->generation_dir, 1, why, sizeof why) != 0)/ +O20 close removes files it did not create (S1)|src/runtime/rx_operator.c|control|s/ if \(fstatat\(op->dir_fd, name, &st, AT_SYMLINK_NOFOLLOW\) == 0 &&\n st\.st_dev == made->st_dev && st\.st_ino == made->st_ino\)\n unlinkat/ (void)st; (void)made;\n unlinkat/ +O21 a stop that is not durable replies OK (S2)|src/runtime/rx_operator.c|control|s/if \(h\.durable == 1\)\n/if (1)\n/ +O22 unknown commands fall through to the authorized commands (S3)|src/runtime/rx_operator.c|control|s/ if \(!status && !shutdown && !revoke && !revoke_cap\) \{ snprintf\(out, n, "BAD_REQUEST"\); return; \}\n/ (void)revoke_cap;\n/ +O23 an expired resume still runs (S4)|src/runtime/rx_operator.c|control|s/if \(strcmp\(q\.cmd, "stop"\) != 0 && monotonic_ns\(\) > q\.deadline_ns\)/if (0)/ +O24 a request without a deadline accepted (S4)|src/runtime/rx_operator.c|control|s/ \|\| !q->have_deadline\)\n return -1;/)\n return -1;/ +O25 any deadline accepted (S4)|src/runtime/rx_operator.c|control|s/ if \(q->deadline_ns > monotonic_ns\(\) \+ RX_OPERATOR_DEADLINE_MAX_NS\) return -1;\n// +' + +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 $/; <STDIN> }; 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" ] && RX_OP_OUT="$W/base/out" 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_OUT="$d/out" 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..d8a1f2f20 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 <dirent.h> +#include <errno.h> #include <ftw.h> #include <stdatomic.h> #include <sched.h> @@ -32,6 +34,7 @@ #include <string.h> #include <sys/random.h> #include <sys/stat.h> +#include <sys/un.h> #include <sys/utsname.h> #include <time.h> #include <unistd.h> @@ -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,178 @@ 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: <state>/control (the operator's credential + * file and socket) and one generation store per mode, <state>/gen-<key>, + * 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]; +/* flock descriptors held for the program's life (rx_operator_lock_dir): the + * state directory and each generation (halt) directory once a world uses it. */ +static int g_state_lock = -1; +static int g_gen_lock[] = {-1, -1, -1, -1, -1, -1}; +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 seat_claims=%llu seat_halted=%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, + (unsigned long long)__atomic_load_n(&r->w.stats.resident_claims, __ATOMIC_RELAXED), + (unsigned long long)__atomic_load_n(&r->w.stats.resident_halted, __ATOMIC_RELAXED)); +} + +/* 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; + } + /* Held for the program's life: a second program on the same state + * directory is refused here, before it touches a socket or a credential. */ + if (rx_operator_lock_dir(g_state_dir, 1, &g_state_lock, 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, pid %ld)\n", g_state_dir, + g_control_dir, (unsigned)RX_OPERATOR_SUBJ, (long)getpid()); + 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 +417,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 +427,37 @@ 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 || + (g_gen_lock[mode] < 0 && + rx_operator_lock_dir(r->generation_dir, 1, &g_gen_lock[mode], 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 +667,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 +698,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 +724,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 +751,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 @@ -615,14 +837,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 } @@ -664,6 +892,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 +998,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 +1052,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 +1081,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 +1092,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"); @@ -963,12 +1205,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) @@ -1121,6 +1365,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 +1961,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 +2089,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 <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 +2112,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 +2124,21 @@ 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: 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", + 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 +2150,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/.crumb b/tools/.crumb index f2b8b022e..d18dfc02f 100644 --- a/tools/.crumb +++ b/tools/.crumb @@ -56,14 +56,14 @@ } ], "children_root": "sha256:8a042dc49a250f0d1b7ae1358fc70bf7bdc9eff651a5ff7c9ee41fd49d329041", - "compiled_at": "2026-10-05T19:22:53Z", + "compiled_at": "2026-10-06T00:26:33Z", "compiler": "crumb-compile/1", - "digest": "sha256:6a6bc2fc769c40efe05fcaaa1bc5169b89e3446d1e427060747b78b43dd729a9", + "digest": "sha256:ef22f063312bab17b11019f16b48d0e30d907c7bd1af458b6dbc6923907b517f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 134, - "generated_at_commit": "379eb876aee36fbd20de3dd9938ea00f8e03677d", - "source_tree": "sha256:fa5eb73d5b945bc496f81d94e732cb4f87a6468c351fe93318b609d652ec74c6" + "files": 135, + "generated_at_commit": "96748a2078862997c4ee423797ed4d1a99dcf300", + "source_tree": "sha256:e430810a2eee6932f03a14a7e782944d048baf24d877ab95de7aed6ec6e8cfe3" }, "owner_lane": "", "provenance": { diff --git a/tools/r16_qualify.sh b/tools/r16_qualify.sh index 5e9457168..a64a467e0 100755 --- a/tools/r16_qualify.sh +++ b/tools/r16_qualify.sh @@ -244,7 +244,7 @@ R15_parity_host|test-r15-parity-host|r15_parity_host.log|SEQ_SEMANTIC_PARITY=PAS R15_g7_host|test-r15-g7-host|r15_g7_host.log|R15 G7 worker split: 57 checks, 0 failures|0 R15_parity_silicon|test-r15-parity-silicon|r15_parity_silicon.log|SEQ_SEMANTIC_PARITY=PASS|1 R15_receipt|test-r15-receipt|r15_receipt.log|r15 receipt test: 0 failure(s)|0' -declare -A LV TG LOGF +declare -A LV TG LOGF SEATOF # SEATOF: host or silicon, the seat each test ran on SILICON_RAN=0; SILICON_PASS=0 if [ "$G3S" != NOT_RUN ]; then SILICON_RAN=1 @@ -252,6 +252,7 @@ if [ "$G3S" != NOT_RUN ]; then fi while IFS='|' read -r name target log pat sil; do TG[$name]=$target; LOGF[$name]="$RAW_DIR/$log" + if [ "$sil" = 1 ]; then SEATOF[$name]=silicon; else SEATOF[$name]=host; fi if [ "$sil" = 1 ]; then silicon_run "$name" "$RAW_DIR/$log" "$pat" "$target" LV[$name]=$V @@ -336,7 +337,7 @@ g6_defined() { # entry: one silicon run. PASS needs exit 0, no [FAIL] gate line and "N / N M19 GATES PASSED" # with N equal and nonzero. silicon_run m19 "$RAW_DIR/m19_world.log" "M19 GATES PASSED" test-m19 -LV[M19]=$V; TG[M19]=test-m19; LOGF[M19]="$RAW_DIR/m19_world.log" +LV[M19]=$V; TG[M19]=test-m19; LOGF[M19]="$RAW_DIR/m19_world.log"; SEATOF[M19]=silicon if [ "${LV[M19]}" = PASS ]; then if grep -Fq -- "[FAIL]" "$RAW_DIR/m19_world.log" || \ ! grep -Eq -- "PERSISTENT WORLD QUALIFICATION: ([1-9][0-9]*) / \1 M19 GATES PASSED" "$RAW_DIR/m19_world.log"; then @@ -351,6 +352,66 @@ 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. +# Each seat's test writes its receipt to OP_OUT (beside the raw directory, untracked); the +# receipt is copied INTO the raw directory, so the raw digest covers it, and a PASS needs +# the receipt to name this seat, this candidate on a clean tree, no failure or skip, the +# seat's own gate value, and the SHA-256 of the production binary this run built +# (build/rx_r13_living_<seat>, file name included). A test that skipped a case (gate +# NOT_RUN, exit 0) is NOT_RUN, never FAIL and never PASS. +OP_OUT="$OUT_ROOT/$RUN_ID.operator" +export RX_OP_OUT="$OP_OUT" +OPV=NOT_RUN +# op_receipt <seat> <verdict> <gate value>: sets OPV to the verdict after the receipt check. +op_receipt() { + local seat=$1 want=$3 f="$RAW_DIR/operator_$1_receipt.json" bin="$HERE/build/rx_r13_living_$1" why="" + OPV=$2 + if [ "$DRY" != 1 ]; then + rm -f "$f" + if [ -f "$OP_OUT/operator_${seat}_receipt.json" ]; then cp "$OP_OUT/operator_${seat}_receipt.json" "$f"; fi + fi + [ "$OPV" = PASS ] || return 0 + if [ ! -s "$f" ]; then why="no operator receipt" + elif [ "$(jstrv "$f" seat)" != "$seat" ]; then why="receipt seat is not $seat" + elif [ "$(jstrv "$f" binary)" != "rx_r13_living_$seat" ]; then why="receipt binary $(jstrv "$f" binary) is not rx_r13_living_$seat" + elif [ ! -f "$bin" ] || [ "$(jstrv "$f" binary_sha256)" != "$(sha256sum "$bin" | cut -d' ' -f1)" ]; then why="receipt binary digest is not the production binary built in this run" + elif [ "$(jstrv "$f" candidate_commit)" != "$CANDIDATE_COMMIT" ]; then why="receipt candidate commit is not $CANDIDATE_COMMIT" + elif [ "$(sed -n 's/^.*"tree_dirty": *\([a-z]*\).*$/\1/p' "$f")" != false ]; then why="receipt tree not clean" + elif [ "$(jint "$f" failures)" != 0 ] || [ "$(jint "$f" skipped)" != 0 ]; then why="receipt counts failures or skips" + elif [ "$(sed -n 's/^.*"R16_G6_OPERATOR": "\([^"]*\)".*$/\1/p' "$f")" != "$want" ]; then why="receipt gate is not $want" + fi + if [ -n "$why" ]; then OPV=FAIL; echo " operator $seat receipt: FAIL ($why)" + else echo " operator $seat receipt: bound (binary $(jstrv "$f" binary_sha256 | cut -c1-12))"; fi +} +# op_notrun <verdict> <log> <rc> <ok rc...>: a run that exited with an accepted status and +# printed a NOT_RUN gate line is NOT_RUN. +op_notrun() { + local v=$1 log=$2 rc=$3 ok; shift 3 + for ok in "$@"; do + if [ "$rc" = "$ok" ] && [ -s "$log" ] && grep -Eq -- "(R16_G6_OPERATOR|RX_OPERATOR_MUTANTS)(=|: )NOT_RUN" "$log"; then echo NOT_RUN; return; fi + done + echo "$v" +} +rm -f "$OP_OUT/operator_host_receipt.json" "$OP_OUT/operator_silicon_receipt.json" +run_target "$RAW_DIR/r16_operator_host.log" test-r16-operator-host +LV[R16_OP_HOST]=$(op_notrun "$(verdict "$RC" "$RAW_DIR/r16_operator_host.log" "R16 operator gate: R16_G6_OPERATOR=HOST_PASS_NON_SILICON")" "$RAW_DIR/r16_operator_host.log" "$RC" 0) +op_receipt host "${LV[R16_OP_HOST]}" HOST_PASS_NON_SILICON; LV[R16_OP_HOST]=$OPV +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]=$(op_notrun "$(verdict "$RC" "$RAW_DIR/r16_operator_mutants.log" "RX_OPERATOR_MUTANTS: PASS")" "$RAW_DIR/r16_operator_mutants.log" "$RC" 3) +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 +if [ "$V" = FAIL ]; then + V=$(op_notrun "$V" "$RAW_DIR/r16_operator_silicon.log" "$RC" 0) + if [ "$V" = NOT_RUN ]; then SILICON_BROKEN=0; fi # it skipped a case; nothing failed on the chip +fi +op_receipt silicon "$V" PASS; LV[R16_OP_SILICON]=$OPV +if [ "$OPV" != NOT_RUN ]; then SILICON_RAN=$((SILICON_RAN + 1)); fi +if [ "$OPV" = PASS ]; then SILICON_PASS=$((SILICON_PASS + 1)); fi +TG[R16_OP_SILICON]=test-r16-operator-silicon; LOGF[R16_OP_SILICON]="$RAW_DIR/r16_operator_silicon.log"; SEATOF[R16_OP_SILICON]=silicon +unset RX_OP_OUT # g6_test <name>: status of one exercising test; a skipped or unexercised log is NOT_RUN. g6_test() { local s=${LV[$1]:-NOT_RUN} @@ -368,7 +429,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 @@ -391,7 +452,7 @@ while IFS='|' read -r key pairs tests basis; do tj=""; ts=PASS; IFS=',' read -ra TA <<< "$tests" for t in "${TA[@]}"; do s=$(g6_test "$t"); ts=$(combine "$ts" "$s") - tj="$tj{\"name\": \"$t\", \"target\": \"${TG[$t]}\", \"status\": \"$s\"}, " + tj="$tj{\"name\": \"$t\", \"target\": \"${TG[$t]}\", \"seat\": \"${SEATOF[$t]:-host}\", \"status\": \"$s\"}, " done tj=${tj%, } if [ "$present" = false ]; then st=MISSING_IMPLEMENTATION; G6MISSING=$((G6MISSING + 1)) @@ -417,8 +478,9 @@ if [ "$END_COMMIT" = "$CANDIDATE_COMMIT" ] && [ "$RUN_COMMIT" = "$CANDIDATE_COMM else CAND_BOUND=false fi -# silicon_observed: every silicon target (authpath, R12, R13, R14, R15 parity) ran and passed. -if [ "$SILICON_RAN" -ge 5 ] && [ "$SILICON_PASS" = "$SILICON_RAN" ]; then SIL_OBS=true; else SIL_OBS=false; fi +# silicon_observed: every silicon target (authpath, R12, R13, R14, R15 parity, R16 G6 +# operator control on the resident seat) ran and passed. Host results never count here. +if [ "$SILICON_RAN" -ge 6 ] && [ "$SILICON_PASS" = "$SILICON_RAN" ]; then SIL_OBS=true; else SIL_OBS=false; fi # ---- 9. receipt --------------------------------------------------------------------- SC_COMMIT=$(repohead "$INV_JSON" aien-sovereign-core) @@ -490,6 +552,10 @@ cat > "$OUT_RECEIPT_TMP" <<RECOBJ $G6LIST ], "r15_acceptance_still_passing": $(b2j "$R15ACC"), + "operator_control": { + "host": {"seat": "host", "status": "${LV[R16_OP_HOST]}", "mutants": "${LV[R16_OP_MUTANTS]}", "receipt": "operator_host_receipt.json"}, + "silicon": {"seat": "silicon", "status": "${LV[R16_OP_SILICON]}", "receipt": "operator_silicon_receipt.json"} + }, "correctness_reruns": { $(lr R1 R1_R6), $(lr R2 R1_R6), diff --git a/tools/rx_operator.c b/tools/rx_operator.c new file mode 100644 index 000000000..9df70f379 --- /dev/null +++ b/tools/rx_operator.c @@ -0,0 +1,133 @@ +/* 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 <state>/control <command> [reason] + * rx_operator --cred <file> <command> [reason] present another credential file + * rx_operator --control <dir> --raw '<line>' send a line as is (tests) + * + * <command>: status | stop | resume | revoke-cap | revoke | shutdown + * Every request carries deadline=<CLOCK_MONOTONIC ns>, when this client gives + * up (now + 55 s; it waits 60 s); the program drops a late resume unrun. In a + * --raw line the text @deadline@ is replaced by that value. + * Exit: 0 reply OK, 3 STOPPED_NOT_DURABLE (the stop is in force but would not + * survive a restart), 1 any other reply, 2 usage, no credential, no world, or + * the socket timeout could not be set. */ +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/socket.h> +#include <sys/time.h> +#include <sys/un.h> +#include <time.h> +#include <unistd.h> + +static int usage(void) { + fprintf(stderr, "usage: rx_operator (--control <dir> | --cred <file>) " + "(status|stop [reason]|resume|revoke-cap|revoke|shutdown | --raw <line>)\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); + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + unsigned long long deadline = (unsigned long long)ts.tv_sec * 1000000000ull + + (unsigned long long)ts.tv_nsec + 55000000000ull; + char req[1024]; + int n; + if (raw) { + const char *at = strstr(raw, "@deadline@"); + if (at) + n = snprintf(req, sizeof req, "%.*s%llu%s\n", (int)(at - raw), raw, deadline, + at + strlen("@deadline@")); + else + 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 " + "deadline=%llu reason=%s\n", cmd, subject, gen, secret, cap_id, cap_gen, + deadline, reason); + else + n = snprintf(req, sizeof req, "aien-operator v1 %s subject=%u gen=%llu secret=%s cap=%u:%llu " + "deadline=%llu\n", cmd, subject, gen, secret, cap_id, cap_gen, deadline); + 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}; + if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) != 0) { + fprintf(stderr, "rx_operator: cannot set the reply timeout: %s\n", strerror(errno)); + close(fd); + return 2; + } + 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) { /* the program may have answered (a refusal) before reading it all */ + fprintf(stderr, "rx_operator: send: %s (reading any reply)\n", strerror(errno)); + break; + } + 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); + if (strncmp(reply, "aien-operator v1 OK ", 20) == 0) return 0; + if (strncmp(reply, "aien-operator v1 STOPPED_NOT_DURABLE ", 37) == 0) return 3; + return 1; +}