Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/patches/f34b5e62bdf3f5c3 # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#449 (code only) closed derived `f34b5e62bdf3f5c3` #449 Imported from GitHub aien-dev/omega-mv#449 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `b62738d8599b8ec422ad554a100e171df212d851` · Head `132d3f5d056996ccb7e4d5b173733ba5bbd37500` ### Fetch it A git bundle of the pull request's head, 33890 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/f34b5e62bdf3f5c3.bundle -o f34b5e62bdf3f5c3.bundle git fetch f34b5e62bdf3f5c3.bundle refs/pull/449/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-mv 449 132d3f5d056996ccb7e4d5b173733ba5bbd37500 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":449,"url":"https://github.com/aien-dev/omega-mv/pull/449","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:55Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 3375e0ef5..411fc0e88 100644 --- a/.crumb +++ b/.crumb @@ -63,8 +63,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "86b4fb84e2781bcceddb615fdd1a80eb2e428ab18f6dd4478aa058dd56c99fa0", - "last_commit": "eb140d2a", + "digest": "c6e66e6c62824d71b6b469316281c774dca08241921cefc18d31495f554cfcc7", + "last_commit": "d8273d6f", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -81,20 +81,20 @@ "purpose": "Directory research. Purpose not yet described by a human." }, { - "digest": "f655e5afb5df3eb5e0f3cc607e3bc129121cefd31bcba3790f16ce9204379f23", - "last_commit": "5901baa5", + "digest": "6f273bd316d4a2a8b932ef7d92ea3596b93be2fc0736a055acb111d94e44a8f2", + "last_commit": "e9943ed2", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "dbcd8678fc48b25073ce3a9c773de759d0782a3f9ee1aa051a09acddbf8da4a0", - "last_commit": "dd67f6bd", + "digest": "56899f232feaddd4ada1458f06aa49f3034d5fa6d52a1fa77f7ecde3cb3c23a2", + "last_commit": "d8273d6f", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "9763d58150ea11264f10fccc753eed24d3d9644a57be24aa043a3a2f098c38cf", - "last_commit": "eb140d2a", + "digest": "e678609e8a172112a41f3e6a204f6f5adf29aac13bc99fb7413fc89daf40ce6f", + "last_commit": "d8273d6f", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, @@ -105,15 +105,15 @@ "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:c78063a6db92ebe0b91628551350dd911e85a7b3a709800d7381dc364d6672cd", - "compiled_at": "2026-10-14T17:41:11Z", + "children_root": "sha256:c518c455c3e7cdeff242226266bd2483237361ab4b7c067dc2d620f2d994744d", + "compiled_at": "2026-10-14T17:50:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:fee825a4a4afc344e669ba86193b3125407494157bd24326cfeecf2bbe738cfc", + "digest": "sha256:7755287f1df197b1ac1cbe651253b19d48bcd962f41341a6a60ddaadd76e6893", "evidence_files": 7338, "evidence_root": "sha256:35fd4dcec251643bc8056425a6b03acdae66c10a6e44d7eaa91761a260358a33", - "files": 9936, - "generated_at_commit": "eb140d2abf43e7f7bc03be8a4c9088f3bca1fea7", - "source_tree": "sha256:56d86462d12c6106e5bf0976f15cf01ab77cedd378a78fb70c7fc9d765dae7cc" + "files": 9938, + "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", + "source_tree": "sha256:450f69ba47b39f2a65ad2b86e67e53605adec21690fd2da27547c313acd79715" }, "owner_lane": "", "provenance": { diff --git a/mk/.crumb b/mk/.crumb index 25c472f50..4018a9094 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-14T17:41:11Z", + "compiled_at": "2026-10-14T17:50:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:86b4fb84e2781bcceddb615fdd1a80eb2e428ab18f6dd4478aa058dd56c99fa0", + "digest": "sha256:c6e66e6c62824d71b6b469316281c774dca08241921cefc18d31495f554cfcc7", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 69, - "generated_at_commit": "eb140d2abf43e7f7bc03be8a4c9088f3bca1fea7", - "source_tree": "sha256:07716825ee63b9cf5cca52e56a59ab9bf8d51af0b76fb95b05e62b1eac5ab13e" + "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", + "source_tree": "sha256:cfdf2847f618856866730d8a3e70103ab7844e5e6ecce577f0d14b1241cee0ca" }, "owner_lane": "", "provenance": { diff --git a/mk/compiler.mk b/mk/compiler.mk index c78095a6d..701957663 100644 --- a/mk/compiler.mk +++ b/mk/compiler.mk @@ -7,6 +7,8 @@ # # test-compiler-quick smoke (< 60 s single core): same programs, small sweeps; CI on every change # test-compiler-full = test-compiler (receipts and src/compiler CI use it) +# test-osc-ir-decode strict OSC IR decoder (omega#444): full counts, ASan/UBSan, decoder mutants +# (part of test-compiler; test-osc-ir-decode-quick is part of test-compiler-quick) # test-compiler model sweep (10^6) + back end + compiler golden/negative/model # agreement + cross-process determinism, plain and ASan/UBSan # + legacy AArch64 writer differential/refusal + frozen-caller check @@ -75,13 +77,62 @@ $(OSC_DIR)/test_legacy_a64_asan: tests/compiler/test_legacy_a64.c $(OSC_LEGACY_A @mkdir -p $(OSC_DIR) $(CC) $(OSC_CFLAGS) $(OSC_ASAN) -o $@ tests/compiler/test_legacy_a64.c $(OSC_LEGACY_A64) +# omega#444 (one-layer stage 2): the strict OSC IR decoder osc_ir_decode against +# spec/one-layer-format.md. test_osc_ir_decode quick|full|asan (counts in its output). +# Decoder mutants: OSC_IR_DECODE_MUTANT=k switches off exactly one refusal in +# src/compiler/osc_ir.c; each must make the test report a FAIL (negative controls). +# ASan legs run with detect_stack_use_after_return=0: with the fake stack on, every +# osc_ir_validate call (a 6 KB frame) ran about 50x slower on the Spark (measured +# 0.012 ms vs 2.6 ms per encode); use-after-return is not what this test probes. +OSC_DEC_MUTANTS = 1 2 3 4 5 6 7 8 +OSC_DEC_ASAN_ENV = ASAN_OPTIONS=detect_stack_use_after_return=0 +.PHONY: test-osc-ir-decode test-osc-ir-decode-quick test-osc-ir-decode-mutants + +$(OSC_DIR)/test_osc_ir_decode: tests/compiler/test_osc_ir_decode.c $(OSC_LIB) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) -o $@ tests/compiler/test_osc_ir_decode.c $(OSC_LIB) + +$(OSC_DIR)/test_osc_ir_decode_asan: tests/compiler/test_osc_ir_decode.c $(OSC_LIB) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) $(OSC_ASAN) -o $@ tests/compiler/test_osc_ir_decode.c $(OSC_LIB) + +$(OSC_DIR)/test_osc_ir_decode_mutant%: tests/compiler/test_osc_ir_decode.c $(OSC_LIB) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) -DOSC_IR_DECODE_MUTANT=$* -o $@ tests/compiler/test_osc_ir_decode.c $(OSC_LIB) + +test-osc-ir-decode-mutants: $(foreach k,$(OSC_DEC_MUTANTS),$(OSC_DIR)/test_osc_ir_decode_mutant$(k)) + @for k in $(OSC_DEC_MUTANTS); do \ + out=$(OSC_DIR)/ir_decode_mutant$$k.out; \ + if $(abspath $(OSC_DIR))/test_osc_ir_decode_mutant$$k quick > $$out 2>&1; then echo "decoder mutant $$k NOT caught"; exit 1; fi; \ + grep -q '^FAIL: ' $$out || { echo "decoder mutant $$k stopped without a test FAIL line"; exit 1; }; \ + echo "decoder mutant $$k caught: $$(grep -m1 '^FAIL: ' $$out | cut -c1-110)"; \ + done + @echo "test-osc-ir-decode-mutants: PASS ($(words $(OSC_DEC_MUTANTS)) of $(words $(OSC_DEC_MUTANTS)) caught)" + +test-osc-ir-decode: $(OSC_DIR)/test_osc_ir_decode $(OSC_DIR)/test_osc_ir_decode_asan test-osc-ir-decode-mutants + $(abspath $(OSC_DIR)/test_osc_ir_decode) full > $(OSC_DIR)/ir_decode.out + @tail -1 $(OSC_DIR)/ir_decode.out; grep -q '^OSC_IR_DECODE_PASS$$' $(OSC_DIR)/ir_decode.out + @grep -E "^(corpus|valid objects|malformed|refusal classes):" $(OSC_DIR)/ir_decode.out | cut -c1-160 + $(OSC_DEC_ASAN_ENV) $(abspath $(OSC_DIR)/test_osc_ir_decode_asan) asan > $(OSC_DIR)/ir_decode_asan.out + @tail -1 $(OSC_DIR)/ir_decode_asan.out; grep -q '^OSC_IR_DECODE_PASS$$' $(OSC_DIR)/ir_decode_asan.out + @echo "test-osc-ir-decode: PASS (strict decoder, plain full + ASan/UBSan + mutants)" + +test-osc-ir-decode-quick: $(OSC_DIR)/test_osc_ir_decode $(OSC_DIR)/test_osc_ir_decode_asan test-osc-ir-decode-mutants + @mkdir -p $(OSC_DIR)/quick + $(abspath $(OSC_DIR)/test_osc_ir_decode) quick > $(OSC_DIR)/quick/ir_decode.out + @tail -1 $(OSC_DIR)/quick/ir_decode.out; grep -q '^OSC_IR_DECODE_PASS$$' $(OSC_DIR)/quick/ir_decode.out + $(OSC_DEC_ASAN_ENV) $(abspath $(OSC_DIR)/test_osc_ir_decode_asan) quick > $(OSC_DIR)/quick/ir_decode_asan.out + @tail -1 $(OSC_DIR)/quick/ir_decode_asan.out; grep -q '^OSC_IR_DECODE_PASS$$' $(OSC_DIR)/quick/ir_decode_asan.out + @echo "test-osc-ir-decode-quick: PASS (smoke counts; not gate evidence)" + # The ASan legs use smaller sweeps (stated in each test's output) to stay inside # the 3-minute single-core budget; the plain legs run the full counts. test-compiler: $(OSC_DIR)/test_osc_model $(OSC_DIR)/test_osc_model_asan \ $(OSC_DIR)/test_osc_backend $(OSC_DIR)/test_osc_backend_asan \ $(OSC_DIR)/test_osc_alloc $(OSC_DIR)/test_osc_alloc_asan \ $(OSC_DIR)/test_osc_compiler $(OSC_DIR)/test_osc_compiler_asan $(OSC_DIR)/oscc \ - $(OSC_DIR)/test_legacy_a64 $(OSC_DIR)/test_legacy_a64_asan + $(OSC_DIR)/test_legacy_a64 $(OSC_DIR)/test_legacy_a64_asan \ + test-osc-ir-decode $(abspath $(OSC_DIR)/test_osc_model) > $(OSC_DIR)/model.out @tail -1 $(OSC_DIR)/model.out; grep -q '^OSC0B_MODEL_PASS$$' $(OSC_DIR)/model.out $(abspath $(OSC_DIR)/test_osc_model_asan) 05c0b5eed0010001 100000 > $(OSC_DIR)/model_asan.out @@ -135,7 +186,8 @@ test-compiler-full: test-compiler test-compiler-quick: $(OSC_DIR)/test_osc_model $(OSC_DIR)/test_osc_backend $(OSC_DIR)/test_osc_backend_asan \ $(OSC_DIR)/test_osc_alloc $(OSC_DIR)/test_osc_alloc_asan \ $(OSC_DIR)/test_osc_compiler $(OSC_DIR)/test_osc_compiler_asan $(OSC_DIR)/oscc \ - $(OSC_DIR)/test_legacy_a64 $(OSC_DIR)/test_legacy_a64_asan + $(OSC_DIR)/test_legacy_a64 $(OSC_DIR)/test_legacy_a64_asan \ + test-osc-ir-decode-quick @mkdir -p $(OSC_QDIR) $(abspath $(OSC_DIR)/test_osc_model) 05c0b5eed0010001 $(OSC_QUICK_MODEL_SEQ) > $(OSC_QDIR)/model.out @tail -1 $(OSC_QDIR)/model.out; grep -Eq '^OSC0B_MODEL_(SMOKE_)?PASS$$' $(OSC_QDIR)/model.out diff --git a/spec/.crumb b/spec/.crumb index dacf3cd29..b1933c2b0 100644 --- a/spec/.crumb +++ b/spec/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:6834a3241647d3a098283d4eafedbdb1428dfa4d834f9ed5f22025b6d2303093", - "compiled_at": "2026-10-14T01:16:48Z", + "compiled_at": "2026-10-14T17:37:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:f655e5afb5df3eb5e0f3cc607e3bc129121cefd31bcba3790f16ce9204379f23", + "digest": "sha256:6f273bd316d4a2a8b932ef7d92ea3596b93be2fc0736a055acb111d94e44a8f2", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 56, - "generated_at_commit": "e0abd0b524f5bf8e3ba6960b53868980bdd41b4e", - "source_tree": "sha256:65aae2eccf55aac8d2bbe28e80c80b7ed864fa3dd51125ef309375745ff792a7" + "files": 57, + "generated_at_commit": "e9943ed23f0712a7dd1f7248a7d6bb00eabf5ea5", + "source_tree": "sha256:ab760dc10a179ca9d6cc4ec94648609e54d9026c6d6c42d50026b0a941357cb6" }, "owner_lane": "", "provenance": { diff --git a/spec/one-layer-format.md b/spec/one-layer-format.md new file mode 100644 index 000000000..6946161ee --- /dev/null +++ b/spec/one-layer-format.md @@ -0,0 +1,231 @@ +# Specification: OSC binary IR, canonical format and strict reader + +```text +Document ID: SPEC-ONE-LAYER-FORMAT +Issue: aien-spark/omega#444 (one-layer plan, stage 2 "Open the binary front door") +Status: IMPLEMENTED for format versions 1..5 (reader + writer); version 6 items OPEN (section 9) +Code: src/compiler/osc_ir.h (osc_ir_encode, osc_ir_decode, OscIrRefusal) + src/compiler/osc_ir.c (encode_unit, unit_version, decode_unit) +Tests: tests/compiler/test_osc_ir_decode.c; make test-osc-ir-decode(-quick) +Data layout: src/compiler/osc_ir.h is normative for OscUnit; meaning: docs/osc/OSC-1-DESIGN.md +``` + +## 1. What this format is + +A compiled OSC unit (`OscUnit`, `src/compiler/osc_ir.h`) has one canonical byte form, written by +`osc_ir_encode`. Its SHA-256 is the unit's identity (`osc_ir_digest`; docs/osc/OSC-1-DESIGN.md +section 4). Until this change the bytes could only be written; `osc_ir_decode` now reads them back +without the text front end, so a machine can hand Omega executable meaning as bytes. + +## 2. Canonical law + +The canonical set is exactly + + { osc_ir_encode(u) : osc_ir_validate(u) == 0 } + +`osc_ir_decode(buf, len, out)` returns `OSC_IR_OK` only when `buf[0..len)` is in that set, and then +fills `out` with the unit `u` that encodes to it. Every other input is refused with one named class +(section 7) and `out` is left all zero. The reader never repairs, skips, pads, truncates or guesses. + +Consequences, each checked by `tests/compiler/test_osc_ir_decode.c`: + +- encode -> decode -> encode is byte-identical for every admitted input; +- an admitted input re-encodes to exactly itself (no second spelling of a unit exists); +- the decoded unit passes `osc_ir_validate`, so the interpreter and back ends accept it. + +## 3. Wire layout + +All integers little-endian, no padding, no alignment, no pointers. + +### 3.1 Header + +| bytes | field | +|---|---| +| 7 | magic `4F 53 43 31 49 52 00` ("OSC1IR\0") | +| 1 | version, 1..5 (section 4) | +| versions 2..5 only: 1 | `nstructs` 0..16, then `nstructs` struct records (3.2) | +| 2 | `nfuncs` 0..32, then `nfuncs` function records (3.3) | + +Nothing may follow the last function record. + +### 3.2 Struct record (versions 2..5) + +| bytes | field | +|---|---| +| 1 + n | name: length n 0..63, then n bytes, no NUL | +| 1 | `nfields` 0..16 (validation requires 1..16) | +| 2 | `ncells` | +| per field: 1 + n | field name (as struct name) | +| per field: 1 | scalar tag (3.4) | +| per field: 2 | `alen` (0 = scalar field) | +| per field: 2 | `off` | + +### 3.3 Function record + +| bytes | field | +|---|---| +| 1 + n | name: length n 0..63, then n bytes, no NUL | +| 1 | `nparams` | +| type | return type (3.4) | +| 2 | `nvregs` 0..480, then `nvregs` types (3.4) | +| 2 | `nblocks` 0..512, then per block: 4 `first`, 4 `count` | +| 4 | `ninsns` 0..4096, then `ninsns` instructions (3.5) | +| 2 + n | `requires` text: length n 0..255, then n bytes, no NUL | +| 2 + n | `ensures` text: as `requires` | + +### 3.4 Type + +One byte scalar tag: 0 void, 1 bool, 2 u8, 3 u16, 4 u32, 5 u64, 6 i8, 7 i16, 8 i32, 9 i64, +10 ref, 11 bytes, 12 cells. Tags above 12 are refused. For every tag except 10 that byte is the +whole type (the decoded `ref`, `elem`, `len`, `sid` are 0). Tag 10 (ref) continues: + +| bytes | field | +|---|---| +| 1 | ref kind: 0 none, 1 own, 2 shared, 3 mut (above 3 refused) | +| 1 | element scalar tag | +| 2 | `len` | +| 1, only when the element tag is 0 (void) | `sid`: struct reference to `structs[sid-1]` | + +An array reference always has a value element type and `sid` 0; a struct reference always has +element void and `sid` >= 1 (`type_is_ref`, `src/compiler/osc_ir.c`). The element byte therefore +decides, without ambiguity, whether the `sid` byte is present. + +### 3.5 Instruction + +One opcode byte, then the opcode's fields in this order. `r` is a 2-byte register, block or callee +field: 0x0000..0x7FFF, or 0xFFFF for "none" (-1); 0x8000..0xFFFE are refused (RANGE). + +| op | name | fields after the opcode | +|---|---|---| +| 1 | CONST | r dst, 8 imm | +| 2 | MOV | r dst, r a | +| 3 | BIN | 1 sub, r dst, r a, r b | +| 4 | UN | 1 sub, r dst, r a | +| 5 | CMP | 1 sub, r dst, r a, r b | +| 6 | CAST | r dst, r a | +| 7 | ALLOC | r dst, r a | +| 8 | RELEASE | r a | +| 9 | LOAD | r dst, r a, r b | +| 10 | STORE | r a, r b, r c | +| 11 | CALL | r dst, r callee, 1 nargs (0..6; above 6 refused OVERSIZED), nargs x r arg | +| 12 | TRAP | 1 imm (trap code) | +| 13 | BR | r blk_t | +| 14 | CBR | r a, r blk_t, r blk_f | +| 15 | RET | r a | +| 16 | FLOAD | r dst, r a, r b, 1 imm (field index) | +| 17 | FSTORE | r a, r b, r c, 1 imm (field index) | +| 18 | AOPEN | r dst, 1 imm (cells) | +| 19 | AALLOC | r dst, r a, r b | +| 20 | ADESTROY | r a | +| 21 | POPEN | r dst, 1 sub (element tag), 1 nargs (slots), 8 imm (generation) | +| 22 | PCLOSE | r a | +| 23 | HALLOC | r dst, r a, r b | +| 24 | HGEN | r dst, r a, r b | +| 25 | HFREE | r a, r b, r c | +| 26 | HLOAD | r dst, r a, r b, r c | +| 27 | HSTORE | r a, r b, r c, r args[0] | +| 28 | SLOAD | r dst, r a, r b | +| 29 | SSTORE | r a, r b, r c | + +Opcode 0 and opcodes above 29 are refused (RANGE): their length is unknown. The numbers are pinned +by `_Static_assert`s in the test. The meaning of every field and every value range that +`osc_ir_validate` enforces (types agree, registers in range, blocks partition the instructions, +calls only to earlier functions, trap codes 1..14, and the rest) is in `osc_ir.h` and +docs/osc/OSC-1-DESIGN.md. + +### 3.6 Fields the format does not carry + +`OscInsn.line` (debug information; source layout never reaches identity), and per opcode every +field not listed in 3.5. The reader sets them as the front end's emitter does +(`emit`, `src/compiler/osc_lower.c`): `line` 0; `dst`, `a`, `b`, `c`, `blk_t`, `blk_f`, `callee` +-1; everything else 0; HSTORE `nargs` 1. All array entries past a count are 0. The test compares +each decoded unit with the unit the compiler produced on every carried field. + +## 4. Versions and historical readers + +The version byte is a function of the content (`unit_version`, `src/compiler/osc_ir.c`): 5 if any +register is a byte slice (bytes/cells), else 4 if any pool instruction (POPEN..HSTORE) occurs, +else 3 if any arena instruction (AOPEN, AALLOC, ADESTROY) occurs, else 2 if the unit has structs, +else 1. Versions 2..5 share one layout (struct table present, possibly empty); version 1 has no +struct table. Every version 1..5 is read. A version byte that is not the one the content requires +is refused (VERSION_MISMATCH), so one unit never has two encodings. Versions are only ever added; +an existing version's bytes are never reinterpreted. + +## 5. Limits + +Counts are checked before anything under them is read: `nstructs` <= 16, `nfields` <= 16, +`nfuncs` <= 32, `nvregs` <= 480, `nblocks` <= 512, `ninsns` <= 4096, CALL `nargs` <= 6, names +<= 63 bytes, contract texts <= 255 bytes (the `OSC_MAX_*`, `OSC_NAME_MAX`, `OSC_CLAUSE_MAX` +constants of `osc_ir.h`). Input longer than `OSC_IR_ENCODED_MAX` (2,620,251 bytes: every count at +its maximum, every instruction at the widest form, CALL with six arguments, 18 bytes) is refused +before parsing. + +## 6. Identity + +`identity = SHA-256(canonical bytes)`. The magic and version byte are inside the hashed bytes, so +they act as the domain tag that spec/program-identity.md section 2 requires of an identity law: a +reader that sees the bytes knows which layout produced them, and two versions can never share a +preimage. Function names and the `requires` / `ensures` texts are inside the hashed bytes, so a +change to a requirement changes the identity (tested: 514 one-character changes over the corpus, +each a new digest, each round-trips). OSC unit identity is separate from Omega program identity v2 +(`omega.program.v2`, spec/program-identity.md); this change does not alter either law. + +## 7. Refusal classes + +`osc_ir_decode` returns the first defect met while reading front to back; the checks after parsing +run in the order listed. `osc_ir_refusal_name` gives the names. + +| code | class | meaning | counterexample in the test | +|---|---|---|---| +| -1 | ARG | NULL input or output pointer | `osc_ir_decode(NULL, 8, u)` | +| -2 | MAGIC | first 7 bytes are not the magic | "OSC2IR..." | +| -3 | UNKNOWN_VERSION | version byte 0 or above 5 | versions 0 and 6 | +| -4 | TRUNCATED | input ends inside a field | empty input; last byte missing; magic only | +| -5 | OVERSIZED | input over `OSC_IR_ENCODED_MAX`, or a count or length over section 5 | 64-byte name; 481 registers; 256-byte requires text; 2,620,252-byte input | +| -6 | TRAILING | bytes after the last function | one extra byte | +| -7 | RANGE | unknown opcode, scalar tag or ref kind; a register/block/callee field 0x8000..0xFFFE | opcodes 0 and 30; tag 13; register 0x8000 | +| -8 | TEXT | a NUL byte inside a name or contract text (it would read back shorter: ambiguous) | name "f\0g" | +| -9 | INVALID | well-formed, but `osc_ir_validate` refuses the unit | u8 constant 256; register out of range | +| -10 | VERSION_MISMATCH | version byte differs from the one the content requires (section 4) | version 2 or 5 for a plain unit | +| -11 | NONCANONICAL | the unit re-encodes to different bytes | none: unreachable (below) | + +NONCANONICAL is a backstop. Given the checks above it, every field read back writes back to the +same bytes, so no input reaches it; the sweeps assert it is never returned. It is reached only when +a check above it is removed: decoder mutants 1, 2, 5 and 8 (section 8) fall through to it. + +## 8. Qualification + +`make test-osc-ir-decode` (part of `test-compiler`, the full CI leg) and +`make test-osc-ir-decode-quick` (part of `test-compiler-quick`, run on every compiler-path change) +build `tests/compiler/test_osc_ir_decode.c` plain and with ASan/UBSan. Measured on the Spark, +2026-10-14, full mode: + +- corpus: all 59 units the front end compiles from `tests/compiler/progs`, `tests/compiler/slices`, + `src/osh`, `tests/physics0/osc` (32 v1, 7 v2, 6 v3, 3 v4, 11 v5) round-trip byte-exactly and + equal the compiled unit on every carried field; +- 10,000 distinct valid objects (seeded variants of the corpus: constants, names, contract text, + operators, trap codes) round-trip byte-exactly (2,000 under ASan); +- 202,675 malformed inputs (every byte of every unit up to 2,000 bytes flipped three ways, every + truncation, trailing bytes, seeded multi-byte edits; larger units sampled at an even stride): + 177,013 refused with a named class and a zeroed unit, 25,662 decoded to a different valid unit + that re-encodes to exactly those bytes (for example a changed constant), none admitted otherwise, + no crash. The ASan/UBSan build runs the same number of cases (177,177 refused, 25,498 admitted; + the random edits differ because it draws fewer valid variants first) with no sanitizer report; +- one counterexample per reachable class (section 7), built by an independent writer in the test, + whose canonical case is byte-identical to `osc_ir_encode`; +- negative controls: 5 planted defects caught by the test's own checks, and 8 decoder mutants + (`OSC_IR_DECODE_MUTANT` = 1 no trailing check, 2 no version check, 3 no zeroing on refusal, + 4 no validation, 5 no NUL check, 6 no register range check, 7 no total size check, 8 truncation + read as zeros) each make the test fail. + +## 9. Open (asked by #444, not in this change) + +- **Numeric identifiers.** Versions 1..5 still carry function, struct and field names as text, and + names are part of identity. A version 6 that identifies functions, structs and fields by index + only (calls and field accesses already do) is not specified here. +- **Structured requirement objects.** `requires` / `ensures` are carried as source text; their + checks are lowered into the instruction stream by the front end. A structured, machine-readable + requirement object (and its place in identity) needs a design decision first. +- **Domain tag string.** Identity is versioned by the magic and version byte inside the hashed + bytes (section 6), not by a separate `omega.osc.vN` tag string in the style of + spec/program-identity.md. Adopting such a tag would change every existing OSC unit identity. diff --git a/src/.crumb b/src/.crumb index 29ce16c7d..5cdfd73d1 100644 --- a/src/.crumb +++ b/src/.crumb @@ -79,8 +79,8 @@ "purpose": "M21 OMEGA_AUTODIFF: reverse-mode tape over M20 tensor CPU ops, caller-owned nodes and scratch, p" }, { - "digest": "436bd3a2666c7573fe572fc3078a75748d06255b4e64168877dad1adb6de3420", - "last_commit": "18531691", + "digest": "bdc017bf3baddb9034478651fb3f170f045ce8aa27187481d15ac5da7fbfd18c", + "last_commit": "f77bfef7", "name": "compiler", "purpose": "Directory src/compiler. Purpose not yet described by a human." }, @@ -140,7 +140,7 @@ }, { "digest": "4785d8df268c31047589c5dff4ebc1f9a12a0fa4d5c94ce6dee156a841cf9502", - "last_commit": "2ec9e45f", + "last_commit": "dd67f6bd", "name": "reservoir", "purpose": "Ionic-droplet reservoir simulator (omega#440): binary32 fixed-step RK4 of the authors' droplet m" }, @@ -181,15 +181,15 @@ "purpose": "Directory src/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:87462381f6c71959138a51d0a795c5b5510ec9cc3753d73caa8662497290c996", - "compiled_at": "2026-10-14T17:30:45Z", + "children_root": "sha256:93f32e91c5b498226d6ef4a040e3fbd2873dfb1f8b2405c26ea63b3a63df5f22", + "compiled_at": "2026-10-14T17:50:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:dbcd8678fc48b25073ce3a9c773de759d0782a3f9ee1aa051a09acddbf8da4a0", + "digest": "sha256:56899f232feaddd4ada1458f06aa49f3034d5fa6d52a1fa77f7ecde3cb3c23a2", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 463, - "generated_at_commit": "2ec9e45fbc14d6838cceffe5c164f2af43b61a31", - "source_tree": "sha256:a5af764ff217fc67d32ab9189c4f0b5af07735b840490b865c51b8a10f50e376" + "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", + "source_tree": "sha256:0d9c3cd9dd847013894fb41a508baf5827bd9e3b8019390b6ec5bf51110ee702" }, "owner_lane": "", "provenance": { diff --git a/src/compiler/.crumb b/src/compiler/.crumb index 774470655..9f069fc78 100644 --- a/src/compiler/.crumb +++ b/src/compiler/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:4067665ff5aaacc482c82c65d5074409c044890a046868d11fdb4faa38bbb95c", - "compiled_at": "2026-10-13T04:53:55Z", + "compiled_at": "2026-10-14T17:37:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:436bd3a2666c7573fe572fc3078a75748d06255b4e64168877dad1adb6de3420", + "digest": "sha256:bdc017bf3baddb9034478651fb3f170f045ce8aa27187481d15ac5da7fbfd18c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 31, - "generated_at_commit": "3490958276cb23111f7ef17eef30ee4f3a7cfe10", - "source_tree": "sha256:03a4ac220661d07e3145a19d8aaad375d2d86f62cec231cf13f90b056402987f" + "generated_at_commit": "e9943ed23f0712a7dd1f7248a7d6bb00eabf5ea5", + "source_tree": "sha256:cf6e1630b5ccc657c6356142356038413cf7ec5420d675667111b7e366d3f4e7" }, "owner_lane": "", "provenance": { diff --git a/src/compiler/osc_ir.c b/src/compiler/osc_ir.c index c565a4654..da7dcf82c 100644 --- a/src/compiler/osc_ir.c +++ b/src/compiler/osc_ir.c @@ -540,10 +540,15 @@ typedef struct { uint8_t *buf; size_t cap, len; sha256_ctx *sha; + const uint8_t *expect; /* osc_ir_decode: compare against these bytes instead of writing */ + size_t expect_len; + bool differs; /* set once any written byte differs from expect (or overruns it) */ } W; static void wbytes(W *w, const void *p, size_t k) { if (w->sha) sha256_update(w->sha, (const uint8_t *)p, k); + if (w->expect && !w->differs && (w->len + k > w->expect_len || memcmp(w->expect + w->len, p, k) != 0)) + w->differs = true; if (w->buf && w->len + k <= w->cap) memcpy(w->buf + w->len, p, k); w->len += k; } @@ -601,22 +606,26 @@ static bool unit_has_slice(const OscUnit *u) { return false; } +/* The format version a unit encodes as: the highest feature it uses decides. + * 5 = external byte slices, 4 = pools (OSC-3 item 2), 3 = arenas, 2 = structs, + * 1 = none of these. Versions 2..5 share one layout (struct table after the magic). */ +static uint8_t unit_version(const OscUnit *u) { + if (unit_has_slice(u)) return 5; + if (unit_has_pool(u)) return 4; + if (unit_has_arena(u)) return 3; + if (u->nstructs) return 2; + return 1; +} + static void encode_unit(const OscUnit *u, W *w) { /* format version 1 (OSC-1, no structs) / 2 (OSC-2 structs: struct table * after the magic) / 3 (OSC-2 arenas: AOPEN/AALLOC/ADESTROY present; the * struct count byte and table always follow the magic, even when 0). * A unit without structs or arenas encodes exactly as version 1; one with * structs but no arenas exactly as version 2. */ - uint8_t magic[8] = {'O', 'S', 'C', '1', 'I', 'R', 0, 1}; - bool arena = unit_has_arena(u); - if (u->nstructs) magic[7] = 2; - if (arena) magic[7] = 3; - bool pool = unit_has_pool(u); /* OSC-3 item 2: version 4, same layout as 3 */ - if (pool) magic[7] = 4; - bool slice = unit_has_slice(u); /* external byte slices: version 5, same layout as 3/4 */ - if (slice) magic[7] = 5; + uint8_t magic[8] = {'O', 'S', 'C', '1', 'I', 'R', 0, unit_version(u)}; wbytes(w, magic, sizeof magic); - if (u->nstructs || arena || pool || slice) { + if (magic[7] >= 2) { /* struct table present (possibly empty) */ w8(w, u->nstructs); for (int k = 0; k < u->nstructs; k++) { const OscStruct *s = &u->structs[k]; @@ -711,7 +720,7 @@ int osc_ir_slice_args_ok(const OscFunc *f, const uint64_t *args, unsigned nargs) int osc_ir_encode(const OscUnit *u, uint8_t *buf, size_t cap, size_t *len) { if (osc_ir_validate(u, NULL, 0)) return -1; - W w = {buf, buf ? cap : 0, 0, NULL}; + W w = {buf, buf ? cap : 0, 0, NULL, NULL, 0, false}; encode_unit(u, &w); if (len) *len = w.len; if (buf && w.len > cap) return -1; @@ -722,8 +731,199 @@ int osc_ir_digest(const OscUnit *u, uint8_t out[32]) { if (osc_ir_validate(u, NULL, 0)) return -1; sha256_ctx c; sha256_init(&c); - W w = {NULL, 0, 0, &c}; + W w = {NULL, 0, 0, &c, NULL, 0, false}; encode_unit(u, &w); sha256_final(&c, out); return 0; } + +/* ---- strict decoder (omega#444, spec/one-layer-format.md) -------------- */ +/* Negative controls: tests/compiler builds this file with OSC_IR_DECODE_MUTANT = k + * (k >= 1) to switch off exactly one refusal; the decoder tests must then fail. + * The default build has no mutant and every check is live. */ +#ifndef OSC_IR_DECODE_MUTANT +#define OSC_IR_DECODE_MUTANT 0 +#endif +#define MUTANT(k) (OSC_IR_DECODE_MUTANT == (k)) + +typedef struct { + const uint8_t *p; + size_t n, pos; + int rc; /* first refusal met (0 = none yet); later reads are no-ops */ +} R; + +static bool rneed(R *r, size_t k) { + if (r->rc) return false; + if (k > r->n - r->pos) { + if (MUTANT(8)) { r->pos = r->n; return false; } /* mutant: read past the end as zeros, no refusal */ + r->rc = OSC_IR_REFUSE_TRUNCATED; + return false; + } + return true; +} +static uint64_t rle(R *r, unsigned k) { + if (!rneed(r, k)) return 0; + uint64_t v = 0; + for (unsigned i = 0; i < k; i++) v |= (uint64_t)r->p[r->pos + i] << (8 * i); + r->pos += k; + return v; +} +static void rfail(R *r, int rc) { if (!r->rc) r->rc = rc; } +/* a count or length field: refuse OVERSIZED above max (checked before anything is read under it) */ +static uint64_t rcount(R *r, unsigned k, uint64_t max) { + uint64_t v = rle(r, k); + if (!r->rc && v > max) rfail(r, OSC_IR_REFUSE_OVERSIZED); + return r->rc ? 0 : v; +} +/* a register / block / callee field: u16 two's complement; 0..0x7FFF or 0xFFFF (= -1) */ +static int16_t rvr(R *r) { + uint64_t v = rle(r, 2); + if (r->rc) return -1; + if (v == 0xFFFF) return -1; + if (v > 0x7FFF && !MUTANT(6)) { rfail(r, OSC_IR_REFUSE_RANGE); return -1; } + return (int16_t)(uint16_t)v; +} +static OscScalar rscalar(R *r) { + uint64_t v = rle(r, 1); + if (!r->rc && v > OSC_T_CELLS) rfail(r, OSC_IR_REFUSE_RANGE); + return r->rc ? OSC_T_VOID : (OscScalar)v; +} +/* text of at most max bytes into dst (dst has room for max + 1); a NUL inside is ambiguous */ +static void rtext(R *r, unsigned lenbytes, size_t max, char *dst) { + size_t k = (size_t)rcount(r, lenbytes, max); + if (!rneed(r, k)) return; + if (memchr(r->p + r->pos, 0, k) && !MUTANT(5)) { rfail(r, OSC_IR_REFUSE_TEXT); return; } + memcpy(dst, r->p + r->pos, k); + dst[k] = 0; + r->pos += k; +} +static void rtype(R *r, OscType *t) { + t->s = rscalar(r); + if (r->rc || t->s != OSC_T_REF) return; + uint64_t ref = rle(r, 1); + if (!r->rc && ref > OSC_REF_MUT) { rfail(r, OSC_IR_REFUSE_RANGE); return; } + t->ref = (OscRefKind)ref; + t->elem = rscalar(r); + t->len = (uint16_t)rle(r, 2); + if (!r->rc && t->elem == OSC_T_VOID) t->sid = (uint8_t)rle(r, 1); /* struct ref: sid follows */ +} + +static void decode_insn(R *r, OscInsn *in) { + memset(in, 0, sizeof *in); + in->dst = in->a = in->b = in->c = in->blk_t = in->blk_f = in->callee = -1; /* as osc_lower.c emit() */ + in->op = (uint8_t)rle(r, 1); + if (r->rc) return; + switch (in->op) { + case OSC_I_CONST: in->dst = rvr(r); in->imm = rle(r, 8); break; + case OSC_I_MOV: case OSC_I_CAST: case OSC_I_ALLOC: in->dst = rvr(r); in->a = rvr(r); break; + case OSC_I_BIN: case OSC_I_CMP: in->sub = (uint8_t)rle(r, 1); in->dst = rvr(r); in->a = rvr(r); in->b = rvr(r); break; + case OSC_I_UN: in->sub = (uint8_t)rle(r, 1); in->dst = rvr(r); in->a = rvr(r); break; + case OSC_I_RELEASE: in->a = rvr(r); break; + case OSC_I_AOPEN: in->dst = rvr(r); in->imm = rle(r, 1); break; + case OSC_I_AALLOC: in->dst = rvr(r); in->a = rvr(r); in->b = rvr(r); break; + case OSC_I_ADESTROY: in->a = rvr(r); break; + case OSC_I_POPEN: in->dst = rvr(r); in->sub = (uint8_t)rle(r, 1); in->nargs = (uint8_t)rle(r, 1); in->imm = rle(r, 8); break; + case OSC_I_PCLOSE: in->a = rvr(r); break; + case OSC_I_HALLOC: case OSC_I_HGEN: in->dst = rvr(r); in->a = rvr(r); in->b = rvr(r); break; + case OSC_I_HFREE: in->a = rvr(r); in->b = rvr(r); in->c = rvr(r); break; + case OSC_I_HLOAD: in->dst = rvr(r); in->a = rvr(r); in->b = rvr(r); in->c = rvr(r); break; + case OSC_I_HSTORE: in->a = rvr(r); in->b = rvr(r); in->c = rvr(r); in->args[0] = rvr(r); in->nargs = 1; break; + case OSC_I_LOAD: case OSC_I_SLOAD: in->dst = rvr(r); in->a = rvr(r); in->b = rvr(r); break; + case OSC_I_STORE: case OSC_I_SSTORE: in->a = rvr(r); in->b = rvr(r); in->c = rvr(r); break; + case OSC_I_FLOAD: in->dst = rvr(r); in->a = rvr(r); in->b = rvr(r); in->imm = rle(r, 1); break; + case OSC_I_FSTORE: in->a = rvr(r); in->b = rvr(r); in->c = rvr(r); in->imm = rle(r, 1); break; + case OSC_I_CALL: + in->dst = rvr(r); in->callee = rvr(r); + in->nargs = (uint8_t)rcount(r, 1, OSC_MAX_PARAMS); + for (int k = 0; k < in->nargs && !r->rc; k++) in->args[k] = rvr(r); + break; + case OSC_I_TRAP: in->imm = rle(r, 1); break; + case OSC_I_BR: in->blk_t = rvr(r); break; + case OSC_I_CBR: in->a = rvr(r); in->blk_t = rvr(r); in->blk_f = rvr(r); break; + case OSC_I_RET: in->a = rvr(r); break; + default: rfail(r, OSC_IR_REFUSE_RANGE); break; /* unknown opcode: its size is unknown */ + } +} + +static void decode_func(R *r, OscFunc *f) { + rtext(r, 1, OSC_NAME_MAX - 1, f->name); + f->nparams = (uint8_t)rle(r, 1); + rtype(r, &f->ret); + f->nvregs = (uint16_t)rcount(r, 2, OSC_MAX_VREGS); + for (int v = 0; v < f->nvregs && !r->rc; v++) rtype(r, &f->vtype[v]); + f->nblocks = (uint16_t)rcount(r, 2, OSC_MAX_BLOCKS); + for (int b = 0; b < f->nblocks && !r->rc; b++) { + f->blocks[b].first = (uint32_t)rle(r, 4); + f->blocks[b].count = (uint32_t)rle(r, 4); + } + f->ninsns = (uint32_t)rcount(r, 4, OSC_MAX_INSNS); + for (uint32_t i = 0; i < f->ninsns && !r->rc; i++) decode_insn(r, &f->insns[i]); + rtext(r, 2, OSC_CLAUSE_MAX - 1, f->requires_text); + rtext(r, 2, OSC_CLAUSE_MAX - 1, f->ensures_text); +} + +static int decode_unit(const uint8_t *buf, size_t len, OscUnit *u) { + static const uint8_t magic[7] = {'O', 'S', 'C', '1', 'I', 'R', 0}; + if (len > OSC_IR_ENCODED_MAX && !MUTANT(7)) return OSC_IR_REFUSE_OVERSIZED; + R r = {buf, len, 0, 0}; + if (len < sizeof magic) return memcmp(buf, magic, len) ? OSC_IR_REFUSE_MAGIC : OSC_IR_REFUSE_TRUNCATED; + if (memcmp(buf, magic, sizeof magic)) return OSC_IR_REFUSE_MAGIC; + r.pos = sizeof magic; + uint64_t version = rle(&r, 1); + if (r.rc) return r.rc; + if (version < 1 || version > OSC_IR_VERSION_MAX) return OSC_IR_REFUSE_UNKNOWN_VERSION; + if (version >= 2) { + u->nstructs = (uint8_t)rcount(&r, 1, OSC_MAX_STRUCTS); + for (int k = 0; k < u->nstructs && !r.rc; k++) { + OscStruct *s = &u->structs[k]; + rtext(&r, 1, OSC_NAME_MAX - 1, s->name); + s->nfields = (uint8_t)rcount(&r, 1, OSC_MAX_FIELDS); + s->ncells = (uint16_t)rle(&r, 2); + for (int f = 0; f < s->nfields && !r.rc; f++) { + OscField *fd = &s->fields[f]; + rtext(&r, 1, OSC_NAME_MAX - 1, fd->name); + fd->s = rscalar(&r); + fd->alen = (uint16_t)rle(&r, 2); + fd->off = (uint16_t)rle(&r, 2); + } + } + } + u->nfuncs = (uint16_t)rcount(&r, 2, OSC_MAX_FUNCS); + for (int fi = 0; fi < u->nfuncs && !r.rc; fi++) decode_func(&r, &u->funcs[fi]); + if (r.rc) return r.rc; + if (r.pos != len && !MUTANT(1)) return OSC_IR_REFUSE_TRAILING; + if (!MUTANT(4) && osc_ir_validate(u, NULL, 0) != 0) return OSC_IR_REFUSE_INVALID; + if (!MUTANT(2) && unit_version(u) != version) return OSC_IR_REFUSE_VERSION_MISMATCH; + /* backstop: the bytes must be exactly what the encoder writes for this unit */ + W w = {NULL, 0, 0, NULL, buf, len, false}; + encode_unit(u, &w); + if (w.differs || w.len != len) return OSC_IR_REFUSE_NONCANONICAL; + return OSC_IR_OK; +} + +int osc_ir_decode(const uint8_t *buf, size_t len, OscUnit *out) { + if (!out) return OSC_IR_REFUSE_ARG; + memset(out, 0, sizeof *out); + if (!buf) return OSC_IR_REFUSE_ARG; + int rc = decode_unit(buf, len, out); + if (rc != OSC_IR_OK && !MUTANT(3)) memset(out, 0, sizeof *out); /* mutant 3: leave partial output */ + return rc; +} + +const char *osc_ir_refusal_name(int rc) { + switch (rc) { + case OSC_IR_OK: return "OK"; + case OSC_IR_REFUSE_ARG: return "ARG"; + case OSC_IR_REFUSE_MAGIC: return "MAGIC"; + case OSC_IR_REFUSE_UNKNOWN_VERSION: return "UNKNOWN_VERSION"; + case OSC_IR_REFUSE_TRUNCATED: return "TRUNCATED"; + case OSC_IR_REFUSE_OVERSIZED: return "OVERSIZED"; + case OSC_IR_REFUSE_TRAILING: return "TRAILING"; + case OSC_IR_REFUSE_RANGE: return "RANGE"; + case OSC_IR_REFUSE_TEXT: return "TEXT"; + case OSC_IR_REFUSE_INVALID: return "INVALID"; + case OSC_IR_REFUSE_VERSION_MISMATCH: return "VERSION_MISMATCH"; + case OSC_IR_REFUSE_NONCANONICAL: return "NONCANONICAL"; + default: return "?"; + } +} diff --git a/src/compiler/osc_ir.h b/src/compiler/osc_ir.h index 66ea97226..33c23f490 100644 --- a/src/compiler/osc_ir.h +++ b/src/compiler/osc_ir.h @@ -257,6 +257,42 @@ int osc_ir_digest(const OscUnit *u, uint8_t out[32]); #define OSC_IR_VERSION_MAX 5 int osc_ir_encoding_version(const uint8_t *buf, size_t len); +/* Strict decoder (omega#444; format and refusal classes: spec/one-layer-format.md). + * Admits a byte string exactly when it is osc_ir_encode of a unit that passes + * osc_ir_validate, and then fills *out with that unit: every field the encoding + * does not carry gets the value the front end's emitter gives it (line 0; unused + * vreg/block/callee fields -1; everything else 0). Every other input is refused + * with one named class and *out zeroed; nothing is repaired or skipped. Reads + * every historical version 1..OSC_IR_VERSION_MAX. Single-threaded, as + * osc_ir_validate is. Returns OSC_IR_OK (0) or a negative OscIrRefusal. */ +typedef enum { + OSC_IR_OK = 0, + OSC_IR_REFUSE_ARG = -1, /* NULL input or output pointer */ + OSC_IR_REFUSE_MAGIC = -2, /* first 7 bytes are not "OSC1IR\0" */ + OSC_IR_REFUSE_UNKNOWN_VERSION = -3, /* version byte outside 1..OSC_IR_VERSION_MAX */ + OSC_IR_REFUSE_TRUNCATED = -4, /* input ends inside a field */ + OSC_IR_REFUSE_OVERSIZED = -5, /* input or a count/length over the format's limits */ + OSC_IR_REFUSE_TRAILING = -6, /* bytes after the last function */ + OSC_IR_REFUSE_RANGE = -7, /* unknown opcode/type/ref tag, or a register, block */ + /* or callee field that is negative but not -1 */ + OSC_IR_REFUSE_TEXT = -8, /* a NUL byte inside a name or contract text */ + OSC_IR_REFUSE_INVALID = -9, /* well-formed, but the unit fails osc_ir_validate */ + OSC_IR_REFUSE_VERSION_MISMATCH = -10, /* version byte is not the one the content requires */ + OSC_IR_REFUSE_NONCANONICAL = -11 /* valid unit whose encoding differs from the input */ +} OscIrRefusal; +#define OSC_IR_REFUSAL_COUNT 11 + +/* Upper bound on any canonical encoding (every count at its maximum, every + * instruction at its widest, CALL with 6 args = 18 bytes). Longer input is OVERSIZED. */ +#define OSC_IR_ENCODED_MAX \ + (8u + 1u + OSC_MAX_STRUCTS * (1u + 63u + 1u + 2u + OSC_MAX_FIELDS * (1u + 63u + 1u + 2u + 2u)) + 2u + \ + OSC_MAX_FUNCS * (1u + 63u + 1u + 6u + 2u + OSC_MAX_VREGS * 6u + 2u + OSC_MAX_BLOCKS * 8u + 4u + \ + OSC_MAX_INSNS * 18u + 2u * (2u + (OSC_CLAUSE_MAX - 1u)))) + +int osc_ir_decode(const uint8_t *buf, size_t len, OscUnit *out); +/* Stable upper-case name of a refusal class ("TRUNCATED", ...); "OK" for 0; "?" otherwise. */ +const char *osc_ir_refusal_name(int rc); + /* Host entry check for slice parameters of function f called with args[0..nargs) * (registers: pointer, length per slice). 0 ok; -1 refused: a non-empty slice * with a NULL pointer, a range that wraps the address space, or a cells range diff --git a/tests/.crumb b/tests/.crumb index 4cb6c060c..b3dd9b367 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -133,8 +133,8 @@ "purpose": "Directory tests/canonicalization. Purpose not yet described by a human." }, { - "digest": "5446c693d59f25f1871d39f66c5f1fac33cf9e7476101a9b303e8e59079a4516", - "last_commit": "18531691", + "digest": "f041b7daf38c51e8db72834bb764cef7741637981223039d89731a30aa91e224", + "last_commit": "e9943ed2", "name": "compiler", "purpose": "Directory tests/compiler. Purpose not yet described by a human." }, @@ -295,15 +295,15 @@ "purpose": "Directory tests/visor. Purpose not yet described by a human." } ], - "children_root": "sha256:05117e2d294be3c1e110d84e9d3142ccc280a90ef9607760e30a51e0a68efc82", - "compiled_at": "2026-10-14T17:41:11Z", + "children_root": "sha256:007780788467b076e31455e97b09ed7fb861af2e96184fd750995606dac0dc60", + "compiled_at": "2026-10-14T17:50:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:9763d58150ea11264f10fccc753eed24d3d9644a57be24aa043a3a2f098c38cf", + "digest": "sha256:e678609e8a172112a41f3e6a204f6f5adf29aac13bc99fb7413fc89daf40ce6f", "evidence_files": 16, "evidence_root": "sha256:96d08097822ad95f4e562c19e0ba5df5a035774c48632f1832912c40a27bd27a", - "files": 1102, - "generated_at_commit": "eb140d2abf43e7f7bc03be8a4c9088f3bca1fea7", - "source_tree": "sha256:1bd12bc63e0747c0a8f263d14fdf9d80f1b66e1c015620c94bc66bfe0d89362b" + "files": 1103, + "generated_at_commit": "d8273d6f8f933b462b1d0b80a575f71f4f73ee84", + "source_tree": "sha256:2dacede8ba425b11dc4c3fad304426c94b64a16c1327fdaec5e1d08a03bb5451" }, "owner_lane": "", "provenance": { diff --git a/tests/compiler/.crumb b/tests/compiler/.crumb index 67f10856a..f010bfce4 100644 --- a/tests/compiler/.crumb +++ b/tests/compiler/.crumb @@ -30,14 +30,14 @@ } ], "children_root": "sha256:8e71869afa3e9efae551dc468dfd9fae972bd9a404fc7f2cbdabc1684e98fb8e", - "compiled_at": "2026-10-13T04:37:52Z", + "compiled_at": "2026-10-14T17:37:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:5446c693d59f25f1871d39f66c5f1fac33cf9e7476101a9b303e8e59079a4516", + "digest": "sha256:f041b7daf38c51e8db72834bb764cef7741637981223039d89731a30aa91e224", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 205, - "generated_at_commit": "cc3f8584d83571c4d53336742af0ebdda254a0ab", - "source_tree": "sha256:2b0bf6b04b517e2e9d9758878b98212b2491a33c3bc5f880cc7ccb86502f0db6" + "files": 206, + "generated_at_commit": "e9943ed23f0712a7dd1f7248a7d6bb00eabf5ea5", + "source_tree": "sha256:8d2b44ba348917da5af698886fa1226e8562684fbb069d7af91a0d64d158067b" }, "owner_lane": "", "provenance": { diff --git a/tests/compiler/test_osc_ir_decode.c b/tests/compiler/test_osc_ir_decode.c new file mode 100644 index 000000000..9a1145509 --- /dev/null +++ b/tests/compiler/test_osc_ir_decode.c @@ -0,0 +1,606 @@ +/* + * test_osc_ir_decode.c -- omega#444: the strict OSC binary IR decoder + * (osc_ir_decode, src/compiler/osc_ir.c) against the format in + * spec/one-layer-format.md. + * + * 1. corpus every .osc unit under tests/compiler/{progs,slices}, src/osh and + * tests/physics0/osc that the front end compiles: encode -> decode + * -> encode is byte-identical, the decoded unit equals the compiled + * one in every encoded field, digests agree, all five versions seen. + * 2. valid unit-level variants of the corpus (constants, names, contract + * text, operators, trap codes) that pass osc_ir_validate: at least + * VALID_MIN distinct encodings round-trip byte-exactly. + * 3. identity a one-character change to requires/ensures text changes the + * digest and the encoding, and both decode. + * 4. classes one hand-built counterexample per reachable refusal class, built + * by an independent writer in this file (not osc_ir_encode). + * 5. malformed every byte of every corpus encoding flipped three ways, every + * truncation, trailing bytes, and seeded random multi-edits: each + * case is refused with a named class and a zeroed unit, or + * admitted only if it is itself a canonical encoding of a valid + * unit (re-encodes to the same bytes). At least MALFORMED_MIN cases. + * 6. controls the checks above are shown to fail on planted defects. + * + * Usage: test_osc_ir_decode [quick] (run from the repository root) + * Prints OSC_IR_DECODE_PASS on success. Decoder mutants (OSC_IR_DECODE_MUTANT=k) + * must make this program fail; mk/compiler.mk checks that they do. + * No Python; seeded PRNG; deterministic. + */ +#include +#include +#include +#include +#include + +#include "osc_front.h" +#include "osc_ir.h" +#include "sha256.h" + +/* spec/one-layer-format.md section 3 states these numbers; a renumbering must fail here. */ +_Static_assert(OSC_I_CONST == 1 && OSC_I_CALL == 11 && OSC_I_RET == 15 && OSC_I_FLOAD == 16 && OSC_I_AOPEN == 18 && + OSC_I_POPEN == 21 && OSC_I_HSTORE == 27 && OSC_I_SSTORE == 29, "opcode numbers in the spec"); +_Static_assert(OSC_T_BOOL == 1 && OSC_T_U64 == 5 && OSC_T_I64 == 9 && OSC_T_REF == 10 && OSC_T_CELLS == 12, "scalar tags in the spec"); +_Static_assert(OSC_REF_OWN == 1 && OSC_REF_MUT == 3, "ref kinds in the spec"); + +static int g_fail; +static void fail(const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + fprintf(stdout, "FAIL: "); + vfprintf(stdout, fmt, ap); + fprintf(stdout, "\n"); + va_end(ap); + if (++g_fail > 40) { printf("too many failures\n"); exit(1); } +} +#define CHECK(c, ...) do { if (!(c)) fail(__VA_ARGS__); } while (0) + +static uint64_t g_rng = 0x05c0de444d0c0de1ULL; +static uint64_t rnd(void) { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 7; g_rng ^= g_rng << 17; return g_rng; } +static uint64_t rndn(uint64_t n) { return n ? rnd() % n : 0; } + +/* ---- corpus ------------------------------------------------------------ */ +#define MAX_CORPUS 128 +typedef struct { + char name[160]; + OscUnit *u; + uint8_t *enc; + size_t len; +} Entry; +static Entry g_corpus[MAX_CORPUS]; +static int g_ncorpus; + +static char *read_file(const char *path, size_t *n) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + char *b = malloc((size_t)sz + 1); + if (!b || fread(b, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(b); return NULL; } + fclose(f); + b[sz] = 0; + *n = (size_t)sz; + return b; +} + +static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } + +static uint8_t *encode_alloc(const OscUnit *u, size_t *len) { + size_t n = 0; + if (osc_ir_encode(u, NULL, 0, &n)) return NULL; + uint8_t *b = malloc(n ? n : 1); + if (!b || osc_ir_encode(u, b, n, len) || *len != n) { free(b); return NULL; } + return b; +} + +static int g_compile_refused; +static void load_dir(const char *dir) { + DIR *d = opendir(dir); + if (!d) return; + char *names[512]; + int nn = 0; + struct dirent *e; + while ((e = readdir(d)) && nn < 512) { + size_t l = strlen(e->d_name); + if (l > 4 && !strcmp(e->d_name + l - 4, ".osc")) names[nn++] = strdup(e->d_name); + } + closedir(d); + qsort(names, (size_t)nn, sizeof names[0], cmp_str); + for (int i = 0; i < nn; i++) { + char path[400]; + snprintf(path, sizeof path, "%s/%s", dir, names[i]); + free(names[i]); + size_t n; + char *src = read_file(path, &n); + if (!src) { fail("cannot read %s", path); continue; } + OscUnit *u = calloc(1, sizeof *u); + OscDiag dg; + memset(&dg, 0, sizeof dg); + int rc = osc_compile(src, n, u, &dg, NULL); + free(src); + if (rc != 0) { g_compile_refused++; free(u); continue; } /* e.g. units with imports */ + if (g_ncorpus >= MAX_CORPUS) { free(u); fail("corpus over %d units", MAX_CORPUS); continue; } + Entry *c = &g_corpus[g_ncorpus]; + snprintf(c->name, sizeof c->name, "%.150s", path); + c->u = u; + c->enc = encode_alloc(u, &c->len); + if (!c->enc) { fail("%s: compiled unit does not encode", path); free(u); continue; } + g_ncorpus++; + } +} + +/* ---- field equality over every encoded field --------------------------- */ +static const char *type_diff(const OscType *a, const OscType *b) { + if (a->s != b->s || a->ref != b->ref || a->elem != b->elem || a->len != b->len || a->sid != b->sid) return "type"; + return NULL; +} +/* NULL if equal, else what differs. `line` is not encoded and is not compared. */ +static const char *unit_diff(const OscUnit *x, const OscUnit *y, char *buf, size_t n) { + if (x->nfuncs != y->nfuncs) return "nfuncs"; + if (x->nstructs != y->nstructs) return "nstructs"; + for (int k = 0; k < x->nstructs; k++) { + const OscStruct *a = &x->structs[k], *b = &y->structs[k]; + if (strcmp(a->name, b->name) || a->nfields != b->nfields || a->ncells != b->ncells) { snprintf(buf, n, "struct %d", k); return buf; } + for (int f = 0; f < a->nfields; f++) { + const OscField *p = &a->fields[f], *q = &b->fields[f]; + if (strcmp(p->name, q->name) || p->s != q->s || p->alen != q->alen || p->off != q->off) { snprintf(buf, n, "struct %d field %d", k, f); return buf; } + } + } + for (int fi = 0; fi < x->nfuncs; fi++) { + const OscFunc *a = &x->funcs[fi], *b = &y->funcs[fi]; + if (strcmp(a->name, b->name)) { snprintf(buf, n, "func %d name", fi); return buf; } + if (a->nparams != b->nparams || a->nvregs != b->nvregs || a->nblocks != b->nblocks || a->ninsns != b->ninsns) { snprintf(buf, n, "func %d counts", fi); return buf; } + if (type_diff(&a->ret, &b->ret)) { snprintf(buf, n, "func %d ret", fi); return buf; } + for (int v = 0; v < a->nvregs; v++) if (type_diff(&a->vtype[v], &b->vtype[v])) { snprintf(buf, n, "func %d vreg %d type", fi, v); return buf; } + for (int k = 0; k < a->nblocks; k++) + if (a->blocks[k].first != b->blocks[k].first || a->blocks[k].count != b->blocks[k].count) { snprintf(buf, n, "func %d block %d", fi, k); return buf; } + for (uint32_t i = 0; i < a->ninsns; i++) { + const OscInsn *p = &a->insns[i], *q = &b->insns[i]; + const char *w = NULL; + if (p->op != q->op) w = "op"; + else if (p->sub != q->sub) w = "sub"; + else if (p->dst != q->dst || p->a != q->a || p->b != q->b || p->c != q->c) w = "operand"; + else if (p->blk_t != q->blk_t || p->blk_f != q->blk_f) w = "target"; + else if (p->callee != q->callee || p->nargs != q->nargs) w = "call"; + else if (memcmp(p->args, q->args, sizeof p->args)) w = "args"; + else if (p->imm != q->imm) w = "imm"; + if (w) { snprintf(buf, n, "func %d insn %u (op %u) %s", fi, i, p->op, w); return buf; } + } + if (strcmp(a->requires_text, b->requires_text) || strcmp(a->ensures_text, b->ensures_text)) { snprintf(buf, n, "func %d contract text", fi); return buf; } + } + return NULL; +} + +static OscUnit *g_dec, *g_tmp; /* scratch units (large; heap) */ +static uint8_t *g_e1, *g_e2; /* OSC_IR_ENCODED_MAX bytes each: one encode call (one validation) per encoding */ + +/* Copy the part of a unit inside its counts: all that encode, validate and unit_diff read. + * Cheaper than copying the whole 6.7 MB struct for every variant. */ +static void copy_unit(OscUnit *d, const OscUnit *s) { + d->nfuncs = s->nfuncs; + d->nstructs = s->nstructs; + memcpy(d->structs, s->structs, sizeof d->structs); + for (int fi = 0; fi < s->nfuncs; fi++) { + OscFunc *a = &d->funcs[fi]; + const OscFunc *b = &s->funcs[fi]; + memcpy(a->name, b->name, sizeof a->name); + a->nparams = b->nparams; + a->ret = b->ret; + a->nvregs = b->nvregs; + memcpy(a->vtype, b->vtype, b->nvregs * sizeof b->vtype[0]); + a->nblocks = b->nblocks; + memcpy(a->blocks, b->blocks, b->nblocks * sizeof b->blocks[0]); + a->ninsns = b->ninsns; + memcpy(a->insns, b->insns, b->ninsns * sizeof b->insns[0]); + memcpy(a->requires_text, b->requires_text, sizeof a->requires_text); + memcpy(a->ensures_text, b->ensures_text, sizeof a->ensures_text); + } +} + +/* encode u, decode, re-encode: byte-identical, fields equal, digest equal. 0 ok. */ +static int round_trip(const OscUnit *u, const char *what) { + size_t n = 0, n2 = 0; + if (osc_ir_encode(u, g_e1, OSC_IR_ENCODED_MAX, &n)) { fail("%s: does not encode", what); return -1; } + int rc = osc_ir_decode(g_e1, n, g_dec); + if (rc != OSC_IR_OK) { fail("%s: decode refused %s", what, osc_ir_refusal_name(rc)); return -1; } + int bad = osc_ir_encode(g_dec, g_e2, OSC_IR_ENCODED_MAX, &n2) != 0 || n2 != n || memcmp(g_e1, g_e2, n) != 0; + if (bad) fail("%s: re-encoding differs (%zu vs %zu bytes)", what, n, n2); + char buf[128]; + const char *d = unit_diff(u, g_dec, buf, sizeof buf); + if (d) { fail("%s: decoded unit differs: %s", what, d); bad = 1; } + uint8_t g1[32], g2[32]; + sha256_ctx sc; /* identity = SHA-256 of the canonical encoding (osc_ir.h) */ + sha256_init(&sc); + sha256_update(&sc, g_e1, n); + sha256_final(&sc, g1); + if (osc_ir_digest(g_dec, g2) || memcmp(g1, g2, 32)) { fail("%s: digest differs", what); bad = 1; } + return bad ? -1 : 0; +} + +/* ---- 1. corpus --------------------------------------------------------- */ +static void test_corpus(void) { + int seen[OSC_IR_VERSION_MAX + 1] = {0}; + int ok = 0; + for (int i = 0; i < g_ncorpus; i++) { + Entry *c = &g_corpus[i]; + int v = osc_ir_encoding_version(c->enc, c->len); + if (v >= 1 && v <= OSC_IR_VERSION_MAX) seen[v]++; + if (round_trip(c->u, c->name) == 0) ok++; + } + printf("corpus: units=%d round_trip_ok=%d compile_refused=%d versions v1=%d v2=%d v3=%d v4=%d v5=%d\n", g_ncorpus, ok, + g_compile_refused, seen[1], seen[2], seen[3], seen[4], seen[5]); + CHECK(g_ncorpus >= 40, "corpus too small: %d units", g_ncorpus); + CHECK(ok == g_ncorpus, "corpus round trip: %d of %d", ok, g_ncorpus); + for (int v = 1; v <= OSC_IR_VERSION_MAX; v++) CHECK(seen[v] > 0, "corpus has no version %d unit", v); +} + +/* ---- 2. valid variants -------------------------------------------------- */ +static uint64_t canon_rand(OscScalar s) { + uint64_t x = rnd(); + unsigned w = osc_scalar_width(s); + if (s == OSC_T_BOOL) return x & 1; + if (w == 64 || w == 0) return x; + if (osc_scalar_signed(s)) { + int64_t v = (int64_t)(x << (64 - w)) >> (64 - w); + return (uint64_t)v; + } + return x & ((1ULL << w) - 1); +} +static void rand_ident(char *d, size_t maxlen) { + static const char al[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; + size_t n = 1 + rndn(maxlen); + d[0] = al[rndn(52)]; + for (size_t i = 1; i < n; i++) d[i] = al[rndn(sizeof al - 1)]; + d[n] = 0; +} +static void rand_text(char *d, size_t maxlen) { + size_t n = rndn(maxlen + 1); + for (size_t i = 0; i < n; i++) d[i] = (char)(0x20 + rndn(95)); + d[n] = 0; +} +static int find_insn(const OscFunc *f, uint8_t op) { + if (!f->ninsns) return -1; + uint32_t start = (uint32_t)rndn(f->ninsns); + for (uint32_t k = 0; k < f->ninsns; k++) { + uint32_t i = (start + k) % f->ninsns; + if (f->insns[i].op == op) return (int)i; + } + return -1; +} +static void mutate_unit(OscUnit *u) { + if (!u->nfuncs) return; + OscFunc *f = &u->funcs[rndn(u->nfuncs)]; + int i; + switch (rndn(8)) { + case 0: case 1: + if ((i = find_insn(f, OSC_I_CONST)) >= 0) f->insns[i].imm = canon_rand(f->vtype[f->insns[i].dst].s); + break; + case 2: rand_ident(f->name, OSC_NAME_MAX - 1); break; + case 3: rand_text(rndn(2) ? f->requires_text : f->ensures_text, OSC_CLAUSE_MAX - 1); break; + case 4: if ((i = find_insn(f, OSC_I_BIN)) >= 0) f->insns[i].sub = (uint8_t)(OSC_B_ADD + rndn(OSC_B_SHR)); break; + case 5: if ((i = find_insn(f, OSC_I_CMP)) >= 0) f->insns[i].sub = (uint8_t)(OSC_C_EQ + rndn(OSC_C_GE)); break; + case 6: if ((i = find_insn(f, OSC_I_TRAP)) >= 0) f->insns[i].imm = 1 + rndn(OSC_TRAP_MAX); break; + case 7: + if (u->nstructs) { + OscStruct *s = &u->structs[rndn(u->nstructs)]; + if (rndn(2)) rand_ident(s->name, OSC_NAME_MAX - 1); + else rand_ident(s->fields[rndn(s->nfields)].name, OSC_NAME_MAX - 1); + } else rand_ident(f->name, OSC_NAME_MAX - 1); + break; + } +} + +#define DIG_CAP (1u << 16) +static uint8_t (*g_digs)[32]; +static unsigned g_ndigs; +static int digest_insert(const uint8_t d[32]) { /* 1 if new */ + unsigned h = ((unsigned)d[0] | (unsigned)d[1] << 8 | (unsigned)d[2] << 16) & (DIG_CAP - 1); + static const uint8_t zero[32]; + for (;; h = (h + 1) & (DIG_CAP - 1)) { + if (!memcmp(g_digs[h], zero, 32)) { memcpy(g_digs[h], d, 32); g_ndigs++; return 1; } + if (!memcmp(g_digs[h], d, 32)) return 0; + } +} + +static void test_valid_variants(unsigned want) { + unsigned tries = 0, invalid = 0, ok_before = (unsigned)g_fail; + for (int i = 0; i < g_ncorpus; i++) { + uint8_t d[32]; + if (!osc_ir_digest(g_corpus[i].u, d)) digest_insert(d); + } + while (g_ndigs < want && tries < want * 20) { + tries++; + const Entry *c = &g_corpus[rndn((uint64_t)g_ncorpus)]; + copy_unit(g_tmp, c->u); + unsigned k = 1 + (unsigned)rndn(3); + for (unsigned j = 0; j < k; j++) mutate_unit(g_tmp); + if (osc_ir_validate(g_tmp, NULL, 0)) { invalid++; continue; } + uint8_t d[32]; + if (osc_ir_digest(g_tmp, d) || !digest_insert(d)) continue; + char what[64]; + snprintf(what, sizeof what, "variant %u", g_ndigs); + round_trip(g_tmp, what); + if ((unsigned)g_fail > ok_before + 5) break; + } + printf("valid objects: distinct=%u tries=%u invalid_variants_skipped=%u (all round-trip byte-exact)\n", g_ndigs, tries, invalid); + CHECK(g_ndigs >= want, "only %u distinct valid objects (want %u)", g_ndigs, want); +} + +/* ---- 3. requirement changes change identity ----------------------------- */ +static void test_requirement_identity(void) { + int checked = 0; + for (int i = 0; i < g_ncorpus; i++) { + const OscUnit *u = g_corpus[i].u; + for (int fi = 0; fi < u->nfuncs; fi++) { + for (int which = 0; which < 2; which++) { + copy_unit(g_tmp, u); + char *t = which ? g_tmp->funcs[fi].ensures_text : g_tmp->funcs[fi].requires_text; + size_t l = strlen(t); + if (l) t[l - 1] = (char)(t[l - 1] == 'x' ? 'y' : 'x'); + else { t[0] = 'x'; t[1] = 0; } + uint8_t g1[32], g2[32]; + CHECK(osc_ir_digest(u, g1) == 0 && osc_ir_digest(g_tmp, g2) == 0, "requirement identity: digest"); + CHECK(memcmp(g1, g2, 32) != 0, "%s func %d: %s change kept the identity", g_corpus[i].name, fi, which ? "ensures" : "requires"); + round_trip(g_tmp, "requirement-changed unit"); + checked++; + } + } + } + printf("requirement identity: %d single-character requires/ensures changes, each a new identity\n", checked); + CHECK(checked > 0, "no requirement identity cases"); +} + +/* ---- 4. one counterexample per refusal class (independent writer) -------- */ +typedef struct { uint8_t b[2048]; size_t n; } Buf; /* largest case: 481 vregs, about 560 bytes */ +static void p8(Buf *b, unsigned v) { b->b[b->n++] = (uint8_t)v; } +static void p16(Buf *b, unsigned v) { p8(b, v & 0xFF); p8(b, (v >> 8) & 0xFF); } +static void p32(Buf *b, uint32_t v) { for (int i = 0; i < 4; i++) p8(b, (v >> (8 * i)) & 0xFF); } +static void p64(Buf *b, uint64_t v) { for (int i = 0; i < 8; i++) p8(b, (unsigned)(v >> (8 * i)) & 0xFF); } +static void pbytes(Buf *b, const void *p, size_t k) { memcpy(b->b + b->n, p, k); b->n += k; } + +/* Knobs for the hand-built unit: fn f() -> u8 { CONST v0 = imm; RET v0 } */ +typedef struct { + unsigned version; /* magic byte 7 */ + int struct_table; /* write the (empty) struct table byte */ + unsigned name_len; /* function name length byte */ + const char *name; /* name bytes (name_len of them) */ + unsigned nvregs; + unsigned ret_tag; /* scalar tag of the return type */ + unsigned op0; /* opcode of insn 0 */ + unsigned dst; /* CONST dst field (u16) */ + uint64_t imm; + unsigned req_len; /* requires text length field */ +} Knobs; +static Knobs knobs_default(void) { + Knobs k = {1, 0, 1, "f", 1, OSC_T_U8, OSC_I_CONST, 0, 7, 0}; + return k; +} +static void build(Buf *b, const Knobs *k) { + b->n = 0; + static const uint8_t magic[7] = {'O', 'S', 'C', '1', 'I', 'R', 0}; + pbytes(b, magic, 7); + p8(b, k->version); + if (k->struct_table) p8(b, 0); + p16(b, 1); /* nfuncs */ + p8(b, k->name_len); pbytes(b, k->name, k->name_len); + p8(b, 0); /* nparams */ + p8(b, k->ret_tag); /* ret type (scalar: tag only) */ + p16(b, k->nvregs); + for (unsigned v = 0; v < k->nvregs; v++) p8(b, OSC_T_U8); + p16(b, 1); p32(b, 0); p32(b, 2); /* one block: insns 0..1 */ + p32(b, 2); /* ninsns */ + p8(b, k->op0); p16(b, k->dst); p64(b, k->imm); + p8(b, OSC_I_RET); p16(b, 0); + p16(b, k->req_len); for (unsigned i = 0; i < k->req_len && i < 300; i++) p8(b, 'r'); + p16(b, 0); /* ensures text */ +} + +static int expect_class(const uint8_t *buf, size_t len, int want, const char *what) { + int rc = osc_ir_decode(buf, len, g_dec); + CHECK(rc == want, "counterexample %s: got %s, want %s", what, osc_ir_refusal_name(rc), osc_ir_refusal_name(want)); + if (rc != OSC_IR_OK) CHECK(g_dec->nfuncs == 0 && g_dec->nstructs == 0 && g_dec->funcs[0].ninsns == 0 && g_dec->funcs[0].name[0] == 0, + "counterexample %s: refused but output not zeroed", what); + return rc == want; +} + +static void test_classes(void) { + Buf b; + Knobs k = knobs_default(); + int got = 0, total = 0; + uint8_t refused[OSC_IR_REFUSAL_COUNT + 1] = {0}; +#define EXPECT(buf, len, want, what) do { total++; if (expect_class(buf, len, want, what)) { got++; refused[-(want)] = 1; } } while (0) + /* the canonical base case is admitted */ + build(&b, &k); + EXPECT(b.b, b.n, OSC_IR_OK, "hand-built canonical unit"); + CHECK(g_dec->nfuncs == 1 && g_dec->funcs[0].insns[0].imm == 7 && g_dec->funcs[0].ret.s == OSC_T_U8, "hand-built unit fields"); + uint8_t enc[2048]; size_t n = 0; + CHECK(osc_ir_encode(g_dec, enc, sizeof enc, &n) == 0 && n == b.n && !memcmp(enc, b.b, n), "independent writer disagrees with osc_ir_encode"); + + total++; if (osc_ir_decode(NULL, 8, g_dec) == OSC_IR_REFUSE_ARG && osc_ir_decode(b.b, b.n, NULL) == OSC_IR_REFUSE_ARG) { got++; refused[1] = 1; } + else fail("counterexample ARG"); + + Buf m = b; m.b[3] = '2'; + EXPECT(m.b, m.n, OSC_IR_REFUSE_MAGIC, "wrong magic"); + EXPECT((const uint8_t *)"", 0, OSC_IR_REFUSE_TRUNCATED, "empty input"); + k = knobs_default(); k.version = 0; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_UNKNOWN_VERSION, "version 0"); + k.version = OSC_IR_VERSION_MAX + 1; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_UNKNOWN_VERSION, "version 6"); + EXPECT(b.b, b.n - 1, OSC_IR_REFUSE_TRUNCATED, "last byte missing"); + EXPECT(b.b, 7, OSC_IR_REFUSE_TRUNCATED, "magic without version"); + k = knobs_default(); k.name_len = 64; k.name = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl"; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_OVERSIZED, "function name of 64 bytes"); + k = knobs_default(); k.nvregs = OSC_MAX_VREGS + 1; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_OVERSIZED, "481 vregs"); + k = knobs_default(); k.req_len = OSC_CLAUSE_MAX; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_OVERSIZED, "requires text of 256 bytes"); + { + size_t big = (size_t)OSC_IR_ENCODED_MAX + 1; + uint8_t *x = calloc(1, big); + memcpy(x, b.b, b.n); + EXPECT(x, big, OSC_IR_REFUSE_OVERSIZED, "input longer than OSC_IR_ENCODED_MAX"); + free(x); + } + m = b; p8(&m, 0); + EXPECT(m.b, m.n, OSC_IR_REFUSE_TRAILING, "one trailing byte"); + k = knobs_default(); k.op0 = 0; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_RANGE, "opcode 0"); + k.op0 = OSC_I_SSTORE + 1; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_RANGE, "opcode past SSTORE"); + k = knobs_default(); k.ret_tag = OSC_T_CELLS + 1; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_RANGE, "scalar tag 13"); + k = knobs_default(); k.dst = 0x8000; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_RANGE, "register 0x8000"); + k = knobs_default(); k.name_len = 3; k.name = "f\0g"; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_TEXT, "NUL inside a function name"); + k = knobs_default(); k.imm = 256; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_INVALID, "u8 constant 256"); + k = knobs_default(); k.dst = 1; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_INVALID, "register out of range"); + k = knobs_default(); k.version = 2; k.struct_table = 1; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_VERSION_MISMATCH, "version 2 with no structs"); + k.version = 5; build(&m, &k); + EXPECT(m.b, m.n, OSC_IR_REFUSE_VERSION_MISMATCH, "version 5 with no slices"); +#undef EXPECT + int classes = 0; + for (int c = 1; c <= OSC_IR_REFUSAL_COUNT; c++) classes += refused[c]; + printf("refusal classes: %d/%d cases as expected; classes exhibited=%d of %d (NONCANONICAL is the unreachable backstop)\n", got, total, + classes, OSC_IR_REFUSAL_COUNT); + CHECK(got == total, "counterexamples: %d of %d", got, total); + CHECK(classes == OSC_IR_REFUSAL_COUNT - 1 && !refused[-OSC_IR_REFUSE_NONCANONICAL], "refusal class coverage"); +} + +/* ---- 5. malformed sweep ------------------------------------------------- */ +static unsigned long g_cases, g_admitted, g_class[OSC_IR_REFUSAL_COUNT + 1]; + +/* The oracle for one case: NULL if the decoder's answer is allowed, else why not. */ +static const char *judge(const uint8_t *m, size_t mlen, int rc, const OscUnit *out) { + if (rc == OSC_IR_OK) { + size_t n = 0; /* osc_ir_encode validates first: an invalid unit does not encode */ + if (osc_ir_encode(out, g_e2, OSC_IR_ENCODED_MAX, &n)) return "admitted a unit that is invalid (does not encode)"; + if (n != mlen || memcmp(g_e2, m, mlen)) return "admitted bytes that do not re-encode identically"; + return NULL; + } + if (rc < -OSC_IR_REFUSAL_COUNT || rc > OSC_IR_REFUSE_MAGIC) return "refused with no named class"; + if (out->nfuncs || out->nstructs || out->funcs[0].ninsns || out->funcs[0].nvregs || out->funcs[0].name[0] || out->structs[0].name[0]) + return "refused but output not zeroed"; + return NULL; +} + +static void one_case(const uint8_t *m, size_t mlen, const uint8_t *orig, size_t olen, const char *unit, const char *kind, size_t x) { + if (mlen == olen && !memcmp(m, orig, olen)) return; /* not malformed: identical to a valid encoding */ + g_cases++; + int rc = osc_ir_decode(m, mlen, g_dec); + if (rc == OSC_IR_OK) g_admitted++; + else if (rc < 0 && rc >= -OSC_IR_REFUSAL_COUNT) g_class[-rc]++; + const char *why = judge(m, mlen, rc, g_dec); + if (why) fail("%s %s %zu (len %zu, rc %s): %s", unit, kind, x, mlen, osc_ir_refusal_name(rc), why); +} + +static void test_malformed(unsigned long want, unsigned random_per_unit, size_t max_positions) { + uint8_t *m = malloc(1 << 20); + for (int i = 0; i < g_ncorpus && g_fail < 20; i++) { + const Entry *c = &g_corpus[i]; + if (c->len + 64 > (1u << 20)) continue; + size_t stride = (c->len + max_positions - 1) / max_positions; /* every byte when len <= max_positions */ + if (stride < 1) stride = 1; + static const uint8_t masks[3] = {0x01, 0x80, 0xFF}; + for (size_t p = (size_t)rndn(stride); p < c->len; p += stride) + for (int k = 0; k < 3; k++) { + memcpy(m, c->enc, c->len); + m[p] ^= masks[k]; + one_case(m, c->len, c->enc, c->len, c->name, k == 0 ? "byte ^0x01 at" : k == 1 ? "byte ^0x80 at" : "byte ^0xFF at", p); + } + for (size_t l = (size_t)rndn(stride); l < c->len; l += stride) { + one_case(c->enc, l, c->enc, c->len, c->name, "truncated to", l); + } + static const uint8_t tails[3][16] = {{0}, {0xFF}, {0x0E, 0x00, 0x00}}; + for (int t = 0; t < 3; t++) { + memcpy(m, c->enc, c->len); + memcpy(m + c->len, tails[t], 16); + one_case(m, c->len + (t == 0 ? 1 : 16), c->enc, c->len, c->name, "trailing pattern", (size_t)t); + } + for (unsigned r = 0; r < random_per_unit; r++) { + size_t n = c->len; + memcpy(m, c->enc, n); + unsigned edits = 1 + (unsigned)rndn(4); + for (unsigned e = 0; e < edits; e++) { + size_t p = (size_t)rndn(n ? n : 1); + switch (rndn(5)) { + case 0: if (n) m[p] ^= (uint8_t)(1u << rndn(8)); break; + case 1: if (n) m[p] = (uint8_t)rnd(); break; + case 2: if (n) { memmove(m + p, m + p + 1, n - p - 1); n--; } break; + case 3: memmove(m + p + 1, m + p, n - p); m[p] = (uint8_t)rnd(); n++; break; + case 4: if (n > 2) { uint16_t v = (uint16_t)(rndn(2) ? 0xFFFF : rnd()); size_t q = p < n - 2 ? p : n - 2; memcpy(m + q, &v, 2); } break; + } + } + one_case(m, n, c->enc, c->len, c->name, "random edit", r); + } + } + free(m); + printf("malformed: cases=%lu refused=%lu admitted_as_other_canonical_unit=%lu (each re-encodes to its own bytes)", g_cases, g_cases - g_admitted, g_admitted); + for (int c = 1; c <= OSC_IR_REFUSAL_COUNT; c++) printf(" %s=%lu", osc_ir_refusal_name(-c), g_class[c]); + printf("\n"); + CHECK(g_cases - g_admitted >= want, "only %lu refused malformed cases (want %lu)", g_cases - g_admitted, want); + CHECK(g_class[-OSC_IR_REFUSE_NONCANONICAL] == 0, "NONCANONICAL backstop was reached: a structural check is missing"); +} + +/* ---- 6. negative controls: the checks can fail --------------------------- */ +static void test_controls(void) { + int caught = 0; + const Entry *c = &g_corpus[0]; + /* (a) the field comparison sees a planted change in an encoded field */ + copy_unit(g_tmp, c->u); + g_tmp->funcs[0].insns[0].op ^= 0x40; + char buf[128]; + caught += unit_diff(c->u, g_tmp, buf, sizeof buf) != NULL; + /* (b) the oracle rejects a forbidden admission: bytes != the unit's encoding */ + uint8_t *m = malloc(c->len + 1); + memcpy(m, c->enc, c->len); + m[c->len / 2] ^= 1; + caught += osc_ir_decode(c->enc, c->len, g_dec) == OSC_IR_OK && judge(m, c->len, OSC_IR_OK, g_dec) != NULL; + /* (c) the oracle rejects admission of an invalid unit */ + copy_unit(g_tmp, c->u); + g_tmp->funcs[0].nblocks = 0; + caught += judge(c->enc, c->len, OSC_IR_OK, g_tmp) != NULL; + /* (d) the oracle rejects a refusal that left output behind, and an unnamed class */ + caught += osc_ir_decode(c->enc, c->len, g_dec) == OSC_IR_OK && judge(m, c->len, OSC_IR_REFUSE_TRUNCATED, g_dec) != NULL; + caught += judge(m, c->len, -99, g_tmp) != NULL; + free(m); + printf("negative controls: %d/5 planted defects caught by the test's own checks\n", caught); + CHECK(caught == 5, "negative controls: only %d of 5 caught", caught); +} + +int main(int argc, char **argv) { + /* quick: CI smoke counts. full: the gate counts (10,000 valid objects, >= 100,000 malformed + * cases, every byte of every unit up to 2,000 bytes). asan: full malformed counts, fewer valid + * variants (each validation is about 30x slower under the sanitizers). */ + const char *mode = argc > 1 ? argv[1] : "full"; + int quick = !strcmp(mode, "quick"), asan = !strcmp(mode, "asan"); + if (!quick && !asan && strcmp(mode, "full")) { printf("usage: test_osc_ir_decode [quick|full|asan]\n"); return 2; } + setvbuf(stdout, NULL, _IOLBF, 0); + g_dec = calloc(1, sizeof *g_dec); + g_tmp = calloc(1, sizeof *g_tmp); + g_digs = calloc(DIG_CAP, 32); + g_e1 = malloc(OSC_IR_ENCODED_MAX); + g_e2 = malloc(OSC_IR_ENCODED_MAX); + if (!g_dec || !g_tmp || !g_digs || !g_e1 || !g_e2) { printf("out of memory\n"); return 1; } + load_dir("tests/compiler/progs"); + load_dir("tests/compiler/slices"); + load_dir("src/osh"); + load_dir("tests/physics0/osc"); + if (g_ncorpus == 0) { printf("FAIL: no corpus (run from the repository root)\n"); return 1; } + printf("OSC_IR_ENCODED_MAX=%u bytes; mode=%s\n", (unsigned)OSC_IR_ENCODED_MAX, quick ? "quick (smoke counts, not gate evidence)" : mode); + test_corpus(); + test_classes(); + test_controls(); + test_requirement_identity(); + test_valid_variants(quick ? 1000 : asan ? 2000 : 10000); + if (quick) test_malformed(5000, 40, 100); + else test_malformed(100000, 600, 2000); + for (int i = 0; i < g_ncorpus; i++) { free(g_corpus[i].u); free(g_corpus[i].enc); } + free(g_dec); free(g_tmp); free(g_digs); free(g_e1); free(g_e2); + if (g_fail) { printf("OSC_IR_DECODE_FAIL %d\n", g_fail); return 1; } + printf("OSC_IR_DECODE_PASS\n"); + return 0; +} ```