diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3958262..31db148 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: run: docker compose build - name: Configure - run: docker compose run --rm dev cmake --preset docker-debug + run: docker compose run --rm dev cmake --preset docker-debug -DQUARRY_INTEROP_REQUIRE_ALL=ON - name: Build run: docker compose run --rm dev cmake --build --preset docker-debug --parallel @@ -52,6 +52,49 @@ jobs: - name: Test run: docker compose run --rm dev ctest --preset docker-debug --output-on-failure + # The same black-box matrix under Linux Clang 18, including its C runtime + # and generic C++ tooling probe. No second whole-project CTest suite. + - name: Clang 18 interoperability matrix + run: | + docker compose run --rm dev sh -ec ' + clang-18 --version + cmake --preset docker-debug -B build/clang18-matrix \ + -DCMAKE_C_COMPILER=clang-18 -DCMAKE_CXX_COMPILER=clang++-18 \ + -DQUARRY_INTEROP_REQUIRE_ALL=ON + cmake --build build/clang18-matrix --target quarry_runtime_c interop_matrix_generic_cpp --parallel + python3 tests/interop/matrix/run.py \ + --source . \ + --generic-cpp build/clang18-matrix/tests/interop_matrix_generic_cpp \ + --cc clang-18 --cxx clang++-18 \ + --build-dir build/docker-debug \ + --runtime-c build/clang18-matrix/runtime_c/libquarry_runtime_c.a \ + --work build/interop-clang18 --require-all' + + # Docker creates private temporary directories and Go's BRF files are + # mode 0600. Give the host runner ownership before upload-artifact walks + # the evidence; keep the test's normal file permissions intact. + - name: Make interoperability evidence readable + if: always() + run: | + for path in build/docker-debug/interop-matrix build/interop-clang18; do + if [ -d "$path" ]; then + sudo chown -R "$USER":"$USER" "$path" + fi + done + + - name: Upload interoperability matrix evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: quarry-interop-matrix + path: | + build/docker-debug/interop-matrix/report.json + build/docker-debug/interop-matrix/run-*/commands.log + build/docker-debug/interop-matrix/run-*/*.brf + build/interop-clang18/report.json + build/interop-clang18/run-*/commands.log + build/interop-clang18/run-*/*.brf + # Small secondary diagnostic; runtime assertions are still required. - name: GCC LTO generated identity validation run: >- diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 688d18c..14c82f4 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -88,8 +88,33 @@ add_quarry_gtest(backend_python_test backend_python/backend_python_test.cpp target_link_libraries(backend_python_test PRIVATE quarry_compiler_schema_ir) target_link_libraries(backend_python_test PRIVATE quarry_schema_ir_warning_tweaks) +option(QUARRY_INTEROP_REQUIRE_ALL "Require all five A5 matrix toolchains" OFF) + +# Black-box A5 matrix: generated codecs see only public runtime headers; +# the generic tooling probe deliberately links the existing QBS parser API. +add_executable(interop_matrix_generic_cpp interop/matrix/generic_cpp.cpp) +target_link_libraries(interop_matrix_generic_cpp PRIVATE quarry_compiler_qbs quarry_project_options) + find_program(QUARRY_PYTHON3_EXECUTABLE python3) +if(QUARRY_INTEROP_REQUIRE_ALL AND NOT QUARRY_PYTHON3_EXECUTABLE) + message(FATAL_ERROR "A5 matrix requires Python orchestration/runtime") +endif() +set(quarry_interop_required_flags) +if(QUARRY_INTEROP_REQUIRE_ALL) + list(APPEND quarry_interop_required_flags --require-all) +endif() if(QUARRY_PYTHON3_EXECUTABLE) + add_test(NAME interop_matrix + COMMAND ${QUARRY_PYTHON3_EXECUTABLE} + "${CMAKE_CURRENT_SOURCE_DIR}/interop/matrix/run.py" + --source "${CMAKE_SOURCE_DIR}" + --generic-cpp "$" + --build-dir "${CMAKE_BINARY_DIR}" --cmake "${CMAKE_COMMAND}" + --cc "${CMAKE_C_COMPILER}" --cxx "${CMAKE_CXX_COMPILER}" + --runtime-c "$" --coverage "$" + --work "${CMAKE_BINARY_DIR}/interop-matrix" + ${quarry_interop_required_flags}) + set_tests_properties(interop_matrix PROPERTIES LABELS "interop;black-box" TIMEOUT 600) add_test(NAME name_prefix_test COMMAND ${QUARRY_PYTHON3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/tools/name_prefix_test.py" @@ -135,6 +160,10 @@ if(QUARRY_PYTHON3_EXECUTABLE) --script "${CMAKE_SOURCE_DIR}/scripts/quarry-validate" --resolver "${CMAKE_SOURCE_DIR}/cmake/QuarryVersion.cmake" --version-template "${CMAKE_SOURCE_DIR}/include/quarry/version.hpp.in") +else() + add_test(NAME interop_matrix COMMAND ${CMAKE_COMMAND} -E echo + "SKIP: A5 matrix requires Python orchestration/runtime") + set_tests_properties(interop_matrix PROPERTIES SKIP_REGULAR_EXPRESSION "SKIP:") endif() add_quarry_gtest(python_execution_test backend_python/python_execution_test.cpp quarry_compiler_support) diff --git a/tests/fixtures/interop_matrix/enum.brd b/tests/fixtures/interop_matrix/enum.brd new file mode 100644 index 0000000..6be9b3b --- /dev/null +++ b/tests/fixtures/interop_matrix/enum.brd @@ -0,0 +1,14 @@ +# Companion coverage only: the authoritative truck configuration stays unchanged. +namespace: matrix +record: EnumSample +version: 1 +type: data +enums: + Mode: + values: + off: 0 + low: 3 + high: 300 +fields: + mode: + type: Mode diff --git a/tests/interop/matrix/README.md b/tests/interop/matrix/README.md new file mode 100644 index 0000000..fbe603f --- /dev/null +++ b/tests/interop/matrix/README.md @@ -0,0 +1,92 @@ +# A5 black-box interoperability matrix + +`ctest --preset debug -R '^interop_matrix$' --output-on-failure` runs the +five-by-five producer/consumer grid. Each producer writes real binary files; +every consumer verifies populated/default fields and re-encodes to the identical +bytes. The adapters are rendered from one explicit expected-value model, using +only generated binding APIs. No compiler layout or identity implementation is +used as an oracle. + +The authoritative root is `examples/truck/schemas/configuration.brd`. Its eight +records cover signed/unsigned integers, boolean values, bounded strings, fixed +nested records, variable nested records, and two-element record arrays with +distinct values. Empty/default records cover absence independently. GearState → EngineStatus → Timestamp and VehicleSnapshot → +GearState → EngineStatus exercise depth two; arrays add deeper paths. Every +actual nested span, including every record-array element, is extracted using +the public C generic view, compared with a standalone encoding, then exchanged +through the same full grid. The companion `enum.brd` fixture adds enum coverage +without changing the truck root or its pinned schema identity. + +C99 and C++20 adapters compile with `-Wall -Wextra -Wpedantic -Wshadow -Werror`. +C-storage encode/decode calls go through the C++ wrapper. Python and Go use +their public generated codecs. Go builds without network/toolchain downloads. +A missing Go toolchain yields visible SKIP cells; those cells are never passes. +`-DQUARRY_INTEROP_REQUIRE_ALL=ON` makes missing toolchains fatal in Linux CI. +Python is the orchestration host, and the source Python runtime is mandatory +when this CTest is registered. + +The C generic QBS/BRF API checks every populated producer while extracting +nested spans. For the representative C producer it checks populated/default +records in both QBS modes; the inspector checks the same cases and must expose +the expected RPM, temperature and fault values. Every other producer's bytes +must match these streams. Python generic checks the complete populated/default +model for every producer in both modes. A separate C++ QBS tooling probe checks +EngineStatus, timestamps and its two fault records for every producer in both +modes. Repeated CLI launches on identical bytes are avoided. +The C++ +probe links the existing QBS parser/tooling library; it does not suggest that +this source-tree tooling API is an independently installed header-only runtime. +The driver stages an actual CMake installation and uses its CLI tools and +public runtime headers for all native generated adapters, generic C probes and +negative compilation controls. The library comes from the selected build, so +the extended run still exercises a Clang-built C runtime. The separate C++ QBS +tooling probe retains its existing source-tree API boundary. + +The driver compares the complete stored 128-bit truck schema_id from each +binding, CLI queries and both QBS images. Dependency replacement tests reject +incompatible configurations in all five languages. A separate wire-identical +field rename tests native gid guards. Python and Go do not expose the native +per-namespace gid mechanism; this distinction is reported as N/A, not a pass. +The existing `public_examples_test` runs the A4.5 truck revision A/B coexistence +application in all five variants, including EngineStatus's shared ID and rev +B's additional MirrorFold record. It is reused rather than duplicated here. + +Legacy controls replace each expected type's ID with its RC3 local component +below 0x00010000 and require rejection by every available generated consumer +and the inspector. These are mapping-specific checks, not an assertion that +all small numeric IDs are intrinsically invalid. Positive controls use the +unmodified streams in the full grid. + +Mutation controls route an altered header ID, valid differently populated bytes, +and a valid record delivered to the wrong type through the same consumer +entry points and value checks. The changed-value and misrouted streams must also +pass with their correct values/type, proving that the intended assertions fail. +Truncation, trailing bytes, invalid UTF-8, unknown enums and a legacy nested ID +are rejected by generated decoders, generic C/Python and both inspector modes. +Rejections require the expected normal error exit (including inspector exit 6); +signal exits and runtime-fault diagnostics cannot count as success. A fourth +control changes the last nibble of the observed schema_id and requires the same +full-width identity assertion to fail. The separate dependency +mixing checks must fail on the generated configuration guard's diagnostics, +not on missing includes or unrelated application errors. + +Repeated generation, a new output directory, and selected/full generation must +agree on shared source bytes. Reordered root imports, selection and prefixing +must preserve the pinned IDs, schema_id and both complete QBS byte streams. +Source-byte equality after import reordering is deliberately not required +(issue #90). Every populated/default producer fixture is also encoded through prefixed APIs +and compared byte for byte with its original stream. Existing `name_prefix_test` +retains additional native storage-policy coverage. + +Evidence is written to `/interop-matrix/report.json` and retained +`run-*/commands.log` files. Reports include each fixture, producer, consumer, +expected/observed ID, byte comparison and decode result, toolchain versions, +checks, mutation results and elapsed wall time. Linux CI uploads these and +executes all five rows. Its additional Clang 18 run builds the C runtime and +C++ QBS probe with Clang 18, then compiles all native generated adapters with +that toolchain. The existing GCC-built compiler and inspector supply the same +black-box CLI boundary. This is a targeted matrix run, not a claim that the +unrelated full Clang 18 conformance suite (#85) passes. + +No BRF/QBS/IR, record allocation, identity encoding, runtime API or epoch changes +are part of this test stage. The experimental FQN-hash branch is untouched. diff --git a/tests/interop/matrix/adapters.py b/tests/interop/matrix/adapters.py new file mode 100644 index 0000000..8624e2d --- /dev/null +++ b/tests/interop/matrix/adapters.py @@ -0,0 +1,332 @@ +"""Render thin public-API adapters from one shared expected-value model. + +Each adapter creates its own bytes, checks every decoded field, and re-encodes. +The driver exchanges binary files, rather than inferring interoperability from +separate round trips. C storage exercises wrapper encode/decode, not C aliases. +""" +import json +from model import RECORDS, BY_NAME + + +def cpp_type(name): + return name.replace('.', '::') + + +def stem(name): + return name.replace('.', '_') + + +def camel(name): + return ''.join(p[0].upper() + p[1:] for p in name.split('_')) + + +def native(storage): + cpp = storage != 'c' + owning = storage == 'cpp' + headers = sorted({name.rsplit('.', 1)[0].replace('.', '/') for name, _, _ in RECORDS}) + ext = '.generated.hpp' if cpp else '.generated.h' + out = ''.join(f'#include "{h}{ext}"\n' for h in headers) + out += '#include \n#include \n#include \n' + if cpp: + out += '#include \n#include \n#include \n' + out += '#define CHECK(x) do { if (!(x)) { fprintf(stderr,"line %d: %s\\n",__LINE__,#x); exit(1); } } while (0)\n' + for name, _, fields in RECORDS: + typ = cpp_type(name) if owning else stem(name) + '_t' + fun = stem(name) + out += f'static {typ} make_{fun}(int seed) {{\n' + if owning: + out += f' {typ}Builder v; if(seed<0) return v.build();\n' + else: + out += f' {typ} v; {fun}_init(&v); if(seed<0) return v;\n' + for field, kind, value in fields: + if kind.endswith('[]'): + sub = kind[:-2] + if owning: + out += f' CHECK(v.set_{field}({{make_{stem(sub)}(seed),make_{stem(sub)}(seed+1)}}));\n' + else: + out += f' v.{field}_count=2; v.{field}[0]=make_{stem(sub)}(seed); v.{field}[1]=make_{stem(sub)}(seed+1);\n' + elif kind == 'string': + if owning: + out += f' CHECK(v.set_{field}("{value}"+std::to_string(seed)));\n' + else: + out += f' v.{field}_length=(uint32_t)snprintf(v.{field},sizeof(v.{field}),"{value}%d",seed);\n' + else: + if kind in BY_NAME: + expression = f'make_{stem(kind)}(seed)' + elif kind == 'enum': + expression = 'static_cast(3)' if owning else '(matrix_Mode_t)3' + elif kind == 'bool': + expression = 'true' if value else 'false' + else: + expression = f'{value}+seed' + if owning: + out += f' CHECK(v.set_{field}({expression}));\n' + else: + out += f' v.has_{field}=true; v.{field}={expression};\n' + if name == 'matrix.EnumSample': + out += ' (void)seed;\n' + out += ' return v.build();\n}\n' if owning else ' return v;\n}\n' + out += f'static void check_{fun}(const {typ}* v,int seed) {{\n (void)seed;\n' + out += ' if(seed<0) {\n' + for field, kind, _ in fields: + absent = f'!v->has_{field}()' if owning else (f'v->{field}_count==0' if kind.endswith('[]') else f'v->{field}_length==0' if kind == 'string' else f'!v->has_{field}') + out += f' CHECK({absent});\n' + out += ' return; }\n' + for field, kind, value in fields: + access = f'v->{field}()' if owning else f'v->{field}' + if kind.endswith('[]'): + if owning: + out += f' CHECK({access} && {access}->size()==2);\n' + for i in range(2): + out += f' check_{stem(kind[:-2])}(&(*{access})[{i}],seed+{i});\n' + else: + out += f' CHECK(v->{field}_count==2);\n' + for i in range(2): + out += f' check_{stem(kind[:-2])}(&v->{field}[{i}],seed+{i});\n' + elif kind == 'string': + out += f' char expected[32]; (void)snprintf(expected,sizeof(expected),"{value}%d",seed);\n' + if owning: + out += f' CHECK({access} && *{access}==expected);\n' + else: + out += f' CHECK(v->{field}_length==strlen(expected) && strcmp({access},expected)==0);\n' + else: + present = access if owning else f'v->has_{field}' + out += f' CHECK({present});\n' + if kind in BY_NAME: + ptr = access if owning else '&' + access + out += f' check_{stem(kind)}({ptr},seed);\n' + else: + expected = ('static_cast(3)' if owning else '(matrix_Mode_t)3') if kind == 'enum' else ('true' if value else 'false') if kind == 'bool' else f'({"uint" if kind.startswith("u") else "int"}{kind[1:]}_t)({value}+seed)' + out += f' CHECK({"*" if owning else ""}{access}=={expected});\n' + out += '}\n' + out += r''' +static int request(int argc,char** argv) { + CHECK(argc==5); /* encode/decode, type, input/output file, seed */ + int seed=atoi(argv[4]); unsigned char wire[65536]; size_t size=0; + if(strcmp(argv[1],"identity")==0) { +''' + identity = 'truck::kQuarrySchemaId.data()' if owning else 'quarry_ns_truck_schema_id()' + out += f' const uint8_t* id={identity}; for(size_t i=0;i<16;i++) printf("%02x",id[i]); return 0;\n }}\n' + out += ' if(strcmp(argv[1],"decode")==0) { FILE* f=fopen(argv[3],"rb"); CHECK(f); size=fread(wire,1,sizeof(wire),f); CHECK(!ferror(f)); fclose(f); }\n' + for index, (name, _, _) in enumerate(RECORDS): + fun = stem(name) + typ = cpp_type(name) + out += f' {"if" if index == 0 else "else if"}(strcmp(argv[2],"{name}")==0) {{\n' + if owning: + out += f' if(strcmp(argv[1],"encode")==0) {{ auto v=make_{fun}(seed); auto e={typ.rsplit("::",1)[0]}::encode_result(v); CHECK(e); size=e.value->size(); CHECK(size<=sizeof(wire)); memcpy(wire,e.value->data(),size); }}\n' + out += f' else {{ auto d={typ.rsplit("::",1)[0]}::decode_{name.split(".")[-1]}_result(std::span(reinterpret_cast(wire),size)); CHECK(d); check_{fun}(&*d.value,seed); auto e={typ.rsplit("::",1)[0]}::encode_result(*d.value); CHECK(e && e.value->size()==size && memcmp(e.value->data(),wire,size)==0); }}\n' + elif storage == 'cpp-c': + out += f' quarry::cxx::{fun} v; if(strcmp(argv[1],"encode")==0) {{ v.native()=make_{fun}(seed); auto e=v.encode(std::span(reinterpret_cast(wire),sizeof(wire))); CHECK(e.status==QUARRY_C_STATUS_OK); size=e.bytes_written; }}\n' + out += f' else {{ auto d=v.decode(std::span(reinterpret_cast(wire),size)); CHECK(d.status==QUARRY_C_STATUS_OK); check_{fun}(&v.native(),seed); unsigned char again[65536]; auto e=v.encode(std::span(reinterpret_cast(again),sizeof(again))); CHECK(e.status==QUARRY_C_STATUS_OK && e.bytes_written==size && memcmp(again,wire,size)==0); }}\n' + else: + out += f' if(strcmp(argv[1],"encode")==0) {{ {fun}_t v=make_{fun}(seed); {fun}_encode_result_t e={fun}_encode(&v,wire,sizeof(wire)); CHECK(e.status==QUARRY_C_STATUS_OK); size=e.bytes_written; }}\n' + out += f' else {{ {fun}_decode_result_t d={fun}_decode(wire,size); CHECK(d.status==QUARRY_C_STATUS_OK); check_{fun}(&d.value,seed); unsigned char again[65536]; {fun}_encode_result_t e={fun}_encode(&d.value,again,sizeof(again)); CHECK(e.status==QUARRY_C_STATUS_OK && e.bytes_written==size && memcmp(again,wire,size)==0); }}\n' + out += ' }\n' + out += ' else { CHECK(0); }\n if(strcmp(argv[1],"encode")==0) { FILE* f=fopen(argv[3],"wb"); CHECK(f); CHECK(fwrite(wire,1,size,f)==size); CHECK(fclose(f)==0); } return 0;\n}\n' + out += r''' +int main(int argc,char** argv) { + if(argc!=3 || strcmp(argv[1],"--batch")!=0) return request(argc,argv); + FILE* input=fopen(argv[2],"r"); CHECK(input); + char lines[4][4096]; char* args[5]={argv[0],lines[0],lines[1],lines[2],lines[3]}; + while(fgets(lines[0],sizeof(lines[0]),input)) { + for(unsigned i=1;i<4;i++) CHECK(fgets(lines[i],sizeof(lines[i]),input)); + for(unsigned i=0;i<4;i++) lines[i][strcspn(lines[i],"\n")]=0; + CHECK(request(5,args)==0); + } + CHECK(!ferror(input)); CHECK(fclose(input)==0); return 0; +} +''' + return out + + +def python(): + out = 'import sys\nfrom pathlib import Path\n' + for name, _, _ in RECORDS: + ns, typ = name.rsplit('.', 1) + out += f'from {ns}.schema import {typ}\n' + out += 'from truck.schema import QUARRY_SCHEMA_ID\n' + out += 'def make(name, seed):\n' + for name, _, _ in RECORDS: + out += f' if seed<0 and name=="{name}": return {name.split(".")[-1]}()\n' + for name, _, fields in RECORDS: + args = [] + for field, kind, value in fields: + if kind.endswith('[]'): + expr = f'[make("{kind[:-2]}",seed),make("{kind[:-2]}",seed+1)]' + elif kind in BY_NAME: + expr = f'make("{kind}",seed)' + elif kind == 'string': + expr = repr(value) + '+str(seed)' + elif kind in ('bool', 'enum'): + expr = repr(value) + else: + expr = str(value) + '+seed' + args.append(field + '=' + expr) + out += f' if name=="{name}": return {name.split(".")[-1]}({",".join(args)})\n' + out += '''def request(args): + mode,name,path,seed=args + seed=int(seed) + if mode=='identity': print(QUARRY_SCHEMA_ID.hex()); return + expected=make(name,seed) + if mode=='encode': Path(path).write_bytes(expected.encode()) + else: + data=Path(path).read_bytes() + decoded=type(expected).decode(data) + assert decoded==expected, (decoded,expected) + assert decoded.encode()==data +if sys.argv[1]=='--batch': + lines=Path(sys.argv[2]).read_text().splitlines() + assert len(lines)%4==0 + for i in range(0,len(lines),4): request(lines[i:i+4]) +else: request(sys.argv[1:]) +''' + return out + + +def go(): + namespaces = sorted({n.rsplit('.', 1)[0] for n, _, _ in RECORDS}) + aliases = {n: f'ns{i}' for i, n in enumerate(namespaces)} + def typ(name): + ns, short = name.rsplit('.', 1) + return aliases[ns] + '.' + short + out = 'package main\nimport("bytes";"fmt";"os";"strconv";"reflect";"strings"; "github.com/ip332/quarry/runtime/go/brf"\n' + for ns in namespaces: + out += f'{aliases[ns]} "example.com/quarry/matrix/{ns.replace(".","/")}"\n' + out += ')\n' + types = {'u64': 'uint64', 'u32': 'uint32', 'u16': 'uint16', 'u8': 'uint8', 'i16': 'int16', 'i8': 'int8'} + for name, _, fields in RECORDS: + out += f'func make{stem(name)}(seed int) *{typ(name)} {{ if seed<0 {{ return &{typ(name)}{{}} }}; return &{typ(name)}{{' + for field, kind, value in fields: + if kind.endswith('[]'): + expr = f'[]{typ(kind[:-2])}{{*make{stem(kind[:-2])}(seed),*make{stem(kind[:-2])}(seed+1)}}' + elif kind in BY_NAME: + expr = f'make{stem(kind)}(seed)' + elif kind == 'string': + expr = json.dumps(value) + '+strconv.Itoa(seed)' + elif kind == 'enum': + expr = f'brf.Ptr({aliases["matrix"]}.Mode(3))' + elif kind == 'bool': + expr = 'brf.Ptr(true)' if value else 'brf.Ptr(false)' + else: + expr = f'brf.Ptr({types[kind]}({value}+seed))' + out += f'{camel(field)}:{expr},' + out += '} }\n' + out += '''type codec interface { MarshalBRF() ([]byte,error); UnmarshalBRF([]byte) error } +func request(args []string) { mode,name,path:=args[0],args[1],args[2]; seed,err:=strconv.Atoi(args[3]);if err!=nil{panic(err)} +''' + out += f'if mode=="identity"{{fmt.Printf("%x",{aliases["truck"]}.QuarrySchemaID());return}}\n' + out += 'var expected,decoded codec\nswitch name {\n' + for name, _, _ in RECORDS: + out += f'case "{name}":expected=make{stem(name)}(seed);decoded=&{typ(name)}{{}}\n' + out += '''default:panic(name) } +if mode=="encode" { data,e:=expected.MarshalBRF();if e!=nil{panic(e)};if e=os.WriteFile(path,data,0600);e!=nil{panic(e)};return } +data,e:=os.ReadFile(path);if e!=nil{panic(e)};if e=decoded.UnmarshalBRF(data);e!=nil{panic(e)} +if !reflect.DeepEqual(expected,decoded){panic(fmt.Sprintf("values: want %+v got %+v",expected,decoded))} +again,e:=decoded.MarshalBRF();if e!=nil||!bytes.Equal(data,again){panic("re-encode mismatch")} +} +''' + out += '''func main(){ + if os.Args[1]!="--batch" {request(os.Args[1:]);return} + data,err:=os.ReadFile(os.Args[2]);if err!=nil{panic(err)} + lines:=strings.Split(strings.TrimSuffix(string(data),"\\n"),"\\n") + if len(lines)%4!=0{panic("batch protocol")} + for i:=0;i +#include +#include +#define CHECK(x) do { if (!(x)) { fprintf(stderr,"generic C line %d: %s\n",__LINE__,#x); exit(1); } } while(0) +static quarry_qbs_record_view_t records[32]; +static quarry_qbs_field_view_t fields[256]; +static quarry_qbs_type_view_t types[128]; +static quarry_qbs_enum_view_t enums[32]; +static uint64_t enum_values[256]; +static quarry_brf_record_node_t nodes[256]; +static quarry_brf_field_state_t states[2048]; +static uint32_t maps[2048], elements[256]; +static quarry_brf_child_relation_t children[256]; +static quarry_brf_record_array_relation_t arrays[128]; +static quarry_brf_validation_frame_t frames[64]; +static quarry_workspace_t workspace; +static const char* prefix; +static unsigned serial; +static void save(const char* name,const quarry_brf_record_view_t* view,int seed) { + if(strcmp(prefix,"-")==0) return; + char path[4096]; CHECK(snprintf(path,sizeof(path),"%s-%u.brf",prefix,serial++)>0); + FILE* f=fopen(path,"wb"); CHECK(f); CHECK(fwrite(view->bytes,1,view->size,f)==view->size); CHECK(fclose(f)==0); + printf("%s %d %s\n",name,seed,path); +} +''' + for name, identity, fields in RECORDS: + out += f'static void check_{stem(name)}(const quarry_brf_record_view_t* v,int seed) {{\n CHECK(v->schema->record_id=={identity}U); (void)seed;\n' + out += ' if(seed<0) {\n' + for index in range(len(fields)): + out += f' bool present{index}; CHECK(quarry_brf_field_is_present(v,{index},&present{index})==QUARRY_GENERIC_OK && !present{index});\n' + out += ' return; }\n' + for index, (_, kind, value) in enumerate(fields): + out += ' {\n' + if kind in BY_NAME: + out += f' quarry_brf_record_view_t child; CHECK(quarry_brf_get_record(v,{index},&child)==QUARRY_GENERIC_OK); save("{kind}",&child,seed); check_{stem(kind)}(&child,seed);\n' + elif kind.endswith('[]'): + out += f' quarry_brf_array_view_t a; CHECK(quarry_brf_get_record_array(v,{index},&a)==QUARRY_GENERIC_OK && a.count==2);\n' + out += f' for(unsigned i=0;i<2;i++) {{ quarry_brf_record_view_t child; CHECK(quarry_brf_record_array_get(v,&a,i,&child)==QUARRY_GENERIC_OK); save("{kind[:-2]}",&child,seed+(int)i); check_{stem(kind[:-2])}(&child,seed+(int)i); }}\n' + elif kind == 'string': + out += f' quarry_string_view_t s; char expected[32]; (void)snprintf(expected,sizeof(expected),"{value}%d",seed); CHECK(quarry_brf_get_string(v,{index},&s)==QUARRY_GENERIC_OK && s.size==strlen(expected) && memcmp(s.data,expected,s.size)==0);\n' + elif kind == 'bool': + out += f' bool b; CHECK(quarry_brf_get_bool(v,{index},&b)==QUARRY_GENERIC_OK && b=={str(value).lower()});\n' + else: + signed = kind.startswith('i') or kind == 'enum' + out += f' {"int64_t" if signed else "uint64_t"} n; CHECK(quarry_brf_get_{"enum" if kind == "enum" else "int" if signed else "uint"}(v,{index},&n)==QUARRY_GENERIC_OK && n==({"int64_t" if signed else "uint64_t"})({value}+{"0" if kind == "enum" else "seed"}));\n' + out += ' }\n' + out += '}\n' + out += r''' +static size_t load(const char* path,uint8_t* data,size_t capacity) { + FILE* f=fopen(path,"rb"); CHECK(f); size_t size=fread(data,1,capacity,f); CHECK(!ferror(f) && feof(f)); CHECK(fclose(f)==0); return size; +} +int main(int argc,char** argv) { + CHECK(argc==7); int seed=atoi(argv[5]); prefix=argv[6]; + static uint8_t qbs_bytes[65536],brf_bytes[65536]; + size_t qbs_size=load(argv[3],qbs_bytes,sizeof(qbs_bytes)); + size_t brf_size=load(argv[4],brf_bytes,sizeof(brf_bytes)); + workspace.records=records; workspace.record_capacity=32; + workspace.fields=fields; workspace.field_capacity=256; + workspace.types=types; workspace.type_capacity=128; + workspace.enums=enums; workspace.enum_capacity=32; + workspace.enum_values=enum_values; workspace.enum_value_capacity=256; + workspace.nodes=nodes; workspace.node_capacity=256; + workspace.field_states=states; workspace.field_state_capacity=2048; + workspace.field_maps=maps; workspace.field_map_capacity=2048; + workspace.children=children; workspace.child_capacity=256; + workspace.arrays=arrays; workspace.array_capacity=128; + workspace.array_elements=elements; workspace.array_element_capacity=256; + workspace.frames=frames; workspace.frame_capacity=64; + quarry_qbs_view_t qbs; CHECK(quarry_qbs_parse(qbs_bytes,qbs_size,&qbs,&workspace,NULL)==QUARRY_GENERIC_OK); + quarry_schema_id_t id; CHECK(quarry_qbs_schema_id(&qbs,&id)==QUARRY_GENERIC_OK); + const quarry_qbs_record_view_t* record; + CHECK(quarry_qbs_find_record_by_id(&qbs,(uint32_t)strtoul(argv[2],NULL,10),&record)==QUARRY_GENERIC_OK); + quarry_brf_record_view_t view; + CHECK(quarry_brf_validate_with_workspace(&qbs,record,brf_bytes,brf_size,&view,&workspace,NULL)==QUARRY_GENERIC_OK); +''' + for i, (name, _, _) in enumerate(RECORDS): + out += f' {"if" if i == 0 else "else if"}(strcmp(argv[1],"{name}")==0) check_{stem(name)}(&view,seed);\n' + return out + ' else { CHECK(0); } return 0;\n}\n' + + +def prefixed(variant): + """Use the same adapter against rev_a APIs, retaining canonical fixture names.""" + if variant == 'python': + return python().replace('from truck.', 'from rev_a.truck.') + if variant == 'go': + return go().replace('example.com/quarry/matrix/truck', + 'example.com/quarry/matrix/rev_a/truck') + text = native(variant).replace('#include "truck', '#include "rev_a/truck') + if variant == 'cpp': + return text.replace('truck::', 'rev_a::truck::') + return text.replace('truck_', 'revq0a_truck_') diff --git a/tests/interop/matrix/configuration.py b/tests/interop/matrix/configuration.py new file mode 100644 index 0000000..3894d30 --- /dev/null +++ b/tests/interop/matrix/configuration.py @@ -0,0 +1,93 @@ +"""CLI determinism and intentional dependency-mixing controls for A5.""" +import os +import shutil +import sys + +from model import RECORDS, SCHEMA_ID + + +def check(args, source, work, env, run, cli, variants, commands, report): + truck = source / 'examples/truck/schemas/configuration.brd' + copied = work / 'reordered' + shutil.copytree(truck.parent, copied) + root = copied / 'configuration.brd' + text = root.read_text() + lines = text.splitlines() + imports = [line for line in lines if line.startswith(' - ')] + root.write_text('\n'.join([line for line in lines if not line.startswith(' - ')] + list(reversed(imports))) + '\n') + assert cli('--print-schema-id', root) == SCHEMA_ID + description = cli('--describe', root) + for name, identity, _ in RECORDS: + if name.startswith('truck.'): + assert f'0x{identity:08x} {name}' in description + for reflective in (False, True): + flags = ['--qbs-reflective'] if reflective else [] + plain = work / ('reflective.qbs' if reflective else 'minimal.qbs') + for label, schema, extra in ( + ('reordered', root, []), ('prefixed', truck, ['--name-prefix', 'rev_a']), + ('selected', truck, ['--generate', 'truck.engine,truck.common'])): + output = work / f'{label}-{reflective}.qbs' + cli('--emit-qbs', output, *flags, *extra, schema) + assert output.read_bytes() == plain.read_bytes(), (label, reflective) + assert cli('--print-schema-id', *extra, schema) == SCHEMA_ID + report['checks'].append('repeat generation/output directory and selected/full source bytes; reordered imports/prefix/selection preserve IDs, full schema_id, both QBS byte streams') + + revision_b = source / 'examples/truck/multi_configuration/rev_b/configuration.brd' + for variant, flags in variants.items(): + if variant not in commands: + continue + directory = work / variant + other = work / (variant + '-incompatible') + cli(*flags, '-o', other, revision_b) + # Swapping only a dependency exercises the generated guard, not an + # accidental missing include or unrelated application type error. + if variant in ('c', 'cpp', 'cpp-c'): + extension = '.generated.h' if variant == 'c' else '.generated.hpp' + dependency = directory / ('truck/common' + extension) + wrong = other / ('truck/common' + extension) + else: + relative = 'truck/common/schema.py' if variant == 'python' else 'truck/common/schema.quarry.go' + dependency, wrong = directory / relative, other / relative + original = dependency.read_bytes() + dependency.write_bytes(wrong.read_bytes()) + try: + if variant in ('c', 'cpp', 'cpp-c'): + cpp = variant != 'c' + path = work / ('mix-' + variant + ('.cpp' if cpp else '.c')) + path.write_text(f'#include "truck/engine{extension}"\nint main(void) {{ return 0; }}\n') + result = run([args.cxx if cpp else args.cc, + '-std=c++20' if cpp else '-std=c99', '-fsyntax-only', + '-I' + str(directory), '-I' + args.runtime_include, path], ok=False) + assert result.returncode == 1 and 'different Quarry configuration' in result.stderr, result + elif variant == 'python': + result = run([sys.executable, '-c', 'import truck.engine.schema'], + environment=dict(env, PYTHONPATH=str(directory) + os.pathsep + env['PYTHONPATH']), ok=False) + assert result.returncode == 1 and 'different Quarry configuration' in result.stderr, result + else: + result = run(['go', 'build', './truck/engine'], cwd=directory, ok=False) + assert result.returncode == 1 and 'QuarrySchemaID' in result.stderr and 'overflows' in result.stderr, result + report['checks'].append(f'{variant}: incompatible configuration dependency visibly rejected by generated guard') + finally: + dependency.write_bytes(original) + # A wire-identical source-name edit changes gid, not schema_id. Only + # native bindings have per-namespace gid checks; Python/Go deliberately + # guard configuration identity instead. Do not invent a new gid format. + if variant not in ('c', 'cpp', 'cpp-c'): + report['checks'].append(f'{variant}: same-schema_id/different-gid guard N/A (no per-namespace gid API)') + continue + renamed = work / ('renamed-' + variant) + shutil.copytree(truck.parent, renamed) + timestamp = renamed / 'common_time.brd' + timestamp.write_text(timestamp.read_text().replace('unix_ms:', 'utc_ms:')) + assert cli('--print-schema-id', renamed / 'configuration.brd') == SCHEMA_ID + changed = work / (variant + '-changed-gid') + cli(*flags, '-o', changed, renamed / 'configuration.brd') + dependency.write_bytes((changed / ('truck/common' + extension)).read_bytes()) + try: + result = run([args.cxx if cpp else args.cc, + '-std=c++20' if cpp else '-std=c99', '-fsyntax-only', + '-I' + str(directory), '-I' + args.runtime_include, path], ok=False) + assert result.returncode == 1 and ('generated definitions' in result.stderr or 'generated-code identity' in result.stderr), result + report['checks'].append(f'{variant}: same schema_id, different generated definitions rejected separately by gid guard') + finally: + dependency.write_bytes(original) diff --git a/tests/interop/matrix/generic_cpp.cpp b/tests/interop/matrix/generic_cpp.cpp new file mode 100644 index 0000000..7f234bf --- /dev/null +++ b/tests/interop/matrix/generic_cpp.cpp @@ -0,0 +1,71 @@ +// QBS tooling API consumer only: no IR/layout/identity calculation oracle. +#include "compiler/qbs/parser.hpp" +#include "quarry/runtime/qbs_brf_reader.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::vector load(const char* path) { + std::ifstream input(path, std::ios::binary); + if (!input) { + throw std::runtime_error("cannot open input"); + } + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} +void require(bool condition) { + if (!condition) { + throw std::runtime_error("C++ generic interpretation disagrees with truck fixture"); + } +} +template T checked(const std::optional& value) { + if (!value.has_value()) { + throw std::runtime_error("expected QBS/BRF view is absent"); + } + return *value; +} +void timestamp(const quarry::runtime::ValidatedBrfRecordView& value, std::uint64_t seed) { + require(value.schema().record_id == 0x00040001U); + const auto field = checked(value.field(0U)); + require(field.as_unsigned() == 42U + seed); +} +} // namespace + +int main(int argc, char** argv) { + try { + require(argc == 3); + const auto qbs_bytes = load(argv[1]); + const auto brf_bytes = load(argv[2]); + quarry::compiler::diagnostics::DiagnosticCollection diagnostics; + const auto qbs = checked(quarry::compiler::qbs::parse_qbs(qbs_bytes, diagnostics)); + const auto record = checked(qbs.find_record_by_id(0x00050001U)); + const auto engine = checked(quarry::runtime::validate_brf_record(qbs, record, brf_bytes)); + const auto time = checked(engine.field(0U)); + timestamp(checked(time.as_record()), 0U); + const auto rpm = checked(engine.field(1U)); + const auto coolant = checked(engine.field(2U)); + require(rpm.as_unsigned() == 1450U); + require(coolant.as_signed() == -12); + const auto faults = checked(engine.record_array(3U)); + require(faults.size() == 2U); + for (std::size_t index = 0U; index < faults.size(); ++index) { + const auto fault = checked(faults.element(index)); + require(fault.schema().record_id == 0x00050002U); + const auto fault_time = checked(fault.field(0U)); + timestamp(checked(fault_time.as_record()), index); + const auto spn = checked(fault.field(1U)); + const auto fmi = checked(fault.field(2U)); + require(spn.as_unsigned() == 1234U + index); + require(fmi.as_unsigned() == 7U + index); + } + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/interop/matrix/model.py b/tests/interop/matrix/model.py new file mode 100644 index 0000000..69e3a75 --- /dev/null +++ b/tests/interop/matrix/model.py @@ -0,0 +1,43 @@ +"""Explicit public truck contract; no compiler internals or identity algorithm. + +Fields are listed in source order so generic QBS numeric access works in minimal +images too. Distinct array elements detect dropped/reordered nested records. +""" +RECORDS = [ + ('truck.common.Timestamp', 0x40001, [('unix_ms', 'u64', 42)]), + ('truck.engine.FaultCode', 0x50002, [('time', 'truck.common.Timestamp', None), + ('spn', 'u32', 1234), ('fmi', 'u8', 7)]), + ('truck.engine.EngineStatus', 0x50001, [('time', 'truck.common.Timestamp', None), + ('rpm', 'u16', 1450), ('coolant_c', 'i16', -12), + ('faults', 'truck.engine.FaultCode[]', None)]), + ('truck.transmission.GearState', 0x60001, [('time', 'truck.common.Timestamp', None), + ('gear', 'i8', -2), ('engine', 'truck.engine.EngineStatus', None)]), + ('truck.brakes.AbsEvent', 0x20001, [('time', 'truck.common.Timestamp', None), ('wheel', 'u8', 3)]), + ('truck.brakes.BrakeStatus', 0x20002, [('time', 'truck.common.Timestamp', None), + ('air_pressure_kpa', 'u16', 800), ('last_abs_event', 'truck.brakes.AbsEvent', None)]), + ('truck.cms.CameraHealth', 0x30001, [('time', 'truck.common.Timestamp', None), + ('camera', 'string', 'front'), ('ok', 'bool', True)]), + ('truck.VehicleSnapshot', 0x10001, [('time', 'truck.common.Timestamp', None), + ('engine', 'truck.engine.EngineStatus', None), ('gear', 'truck.transmission.GearState', None), + ('brakes', 'truck.brakes.BrakeStatus', None), ('cameras', 'truck.cms.CameraHealth[]', None)]), +] +RECORDS.append(('matrix.EnumSample', 0x10001, [('mode', 'enum', 3)])) +BY_NAME = {name: (identity, fields) for name, identity, fields in RECORDS} +SCHEMA_ID = '9200ca494f010801b830d0857cf66dde' + + +def values(name, seed=0): + if seed < 0: + return {} + result = {} + for field, kind, value in BY_NAME[name][1]: + if kind.endswith('[]'): + value = [values(kind[:-2], seed), values(kind[:-2], seed + 1)] + elif kind in BY_NAME: + value = values(kind, seed) + elif kind == 'string': + value += str(seed) + elif kind not in ('bool', 'enum'): + value += seed + result[field] = value + return result diff --git a/tests/interop/matrix/run.py b/tests/interop/matrix/run.py new file mode 100644 index 0000000..a04d6f9 --- /dev/null +++ b/tests/interop/matrix/run.py @@ -0,0 +1,421 @@ +#!/usr/bin/env python3 +"""Black-box five-language BRF matrix. All assertions use public CLI/runtime APIs.""" +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time +import tempfile + +import adapters +import configuration +from model import RECORDS, BY_NAME, SCHEMA_ID, values + +VARIANTS = {'c': ['--language', 'c'], 'cpp': ['--language', 'cpp'], + 'cpp-c': ['--language', 'cpp', '--cpp-storage', 'c'], + 'python': ['--language', 'python'], + 'go': ['--language', 'go', '--go-import-prefix', 'example.com/quarry/matrix']} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for key in ('source', 'build-dir', 'cc', 'cxx', 'runtime-c', 'work', 'generic-cpp'): + parser.add_argument('--' + key, required=True) + parser.add_argument('--cmake', default='cmake') + parser.add_argument('--coverage', default='OFF') + parser.add_argument('--require-all', action='store_true') + args = parser.parse_args() + for key in ('generic_cpp', 'build_dir', 'runtime_c'): + setattr(args, key, str(Path(getattr(args, key)).resolve())) + start = time.monotonic() + source, work = Path(args.source).resolve(), Path(args.work).resolve() + work.mkdir(parents=True, exist_ok=True) + output_root = work + work = Path(tempfile.mkdtemp(prefix='run-', dir=output_root)) + truck = source / 'examples/truck/schemas/configuration.brd' + env = dict(os.environ, PYTHONDONTWRITEBYTECODE='1', + PYTHONPATH=str(source / 'runtime/python/src'), + GOTOOLCHAIN='local', GOPROXY='off', GOSUMDB='off', GOWORK='off', + GOFLAGS='-buildvcs=false', GOCACHE=str(output_root / 'gocache'), GOPATH=str(output_root / 'gopath')) + report = {'toolchains': {}, 'cells': [], 'checks': [], 'mutations': []} + original_hook = sys.excepthook + + def failure_hook(kind, error, traceback): + report['failure'] = str(error) + report['elapsed_seconds'] = round(time.monotonic() - start, 3) + (output_root / 'report.json').write_text(json.dumps(report, indent=2) + '\n') + original_hook(kind, error, traceback) + + sys.excepthook = failure_hook + + def run(command, *, cwd=work, environment=env, ok=True): + result = subprocess.run(list(map(str, command)), cwd=cwd, env=environment, + text=True, capture_output=True, check=False) + with (work / 'commands.log').open('a') as log: + log.write(json.dumps(list(map(str, command))) + '\n' + result.stdout + result.stderr + '\n') + if ok and result.returncode: + raise AssertionError((command, result.returncode, result.stdout, result.stderr)) + return result + + # Exercise the actual distribution boundary, including generated epoch + # headers. The caller's C library may be Clang-built for the extended run; + # it consumes these same installed public headers. + installed = work / 'installed' + run([args.cmake, '--install', args.build_dir, '--prefix', installed]) + args.compiler = str(installed / 'bin/quarry-schema-compiler') + args.inspector = str(installed / 'bin/quarry-brf-inspect') + args.runtime_include = str(installed / 'include') + report['checks'].append('CLI tools and native public headers consumed from an actual CMake install') + + def cli(*flags): + return run([args.compiler, *flags]).stdout.strip() + + def tree(path): + return {p.relative_to(path).as_posix(): p.read_bytes() for p in path.rglob('*') + if p.is_file() and '__pycache__' not in str(p)} + + def compile_native(variant, directory, output, text=None): + cpp = variant != 'c' + path = output.with_suffix('.cpp' if cpp else '.c') + path.write_text(adapters.native(variant) if text is None else text) + flags = [args.cxx if cpp else args.cc, '-std=c++20' if cpp else '-std=c99', + '-Wall', '-Wextra', '-Wpedantic', '-Wshadow', '-Werror', + '-I' + str(directory), '-I' + args.runtime_include] + if args.coverage.lower() in ('on', '1', 'true'): + flags.append('--coverage') + run([*flags, path, args.runtime_c, '-o', output]) + + commands = {} + for variant, flags in VARIANTS.items(): + directory = work / variant + cli(*flags, '-o', directory, truck) + repeated = work / (variant + '-repeat') + cli(*flags, '-o', repeated, truck) + assert tree(directory) == tree(repeated), ('repeat/output directory', variant) + selected = work / (variant + '-selected') + cli(*flags, '--generate', 'truck.engine,truck.common', '-o', selected, truck) + assert all(tree(directory)[p] == data for p, data in tree(selected).items()), variant + cli(*flags, '-o', directory, source / 'tests/fixtures/interop_matrix/enum.brd') + if variant in ('c', 'cpp', 'cpp-c'): + executable = work / (variant + '-adapter') + compile_native(variant, directory, executable) + commands[variant] = [executable] + report['toolchains'][variant] = run([args.cc if variant == 'c' else args.cxx, '--version']).stdout.splitlines()[0] + elif variant == 'python': + path = work / 'python-adapter.py' + path.write_text(adapters.python()) + commands[variant] = [sys.executable, path] + report['toolchains'][variant] = sys.version + elif shutil.which('go'): + (directory / 'go.mod').write_text('module example.com/quarry/matrix\n\ngo 1.22\n\n' + 'require github.com/ip332/quarry/runtime/go v0.0.0\n' + f'replace github.com/ip332/quarry/runtime/go => {source / "runtime/go"}\n') + path = directory / 'cmd/adapter/main.go' + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(adapters.go()) + executable = work / 'go-adapter' + run(['go', 'build', '-o', executable, './cmd/adapter'], cwd=directory) + commands[variant] = [executable] + report['toolchains'][variant] = run(['go', 'version']).stdout.strip() + else: + report['toolchains'][variant] = 'SKIP: Go toolchain unavailable' + print('SKIP Go: Go toolchain unavailable', flush=True) + report['runtime_availability'] = {variant: variant in commands for variant in VARIANTS} + if args.require_all: + assert len(commands) == 5, report['toolchains'] + + def adapter(variant, mode, name, path, seed=0, ok=True): + environment = dict(env) + environment['PYTHONPATH'] = str(work / 'python') + os.pathsep + env['PYTHONPATH'] + return run([*commands[variant], mode, name, path, seed], environment=environment, ok=ok) + + def reject(variant, name, path, seed=0): + result = adapter(variant, 'decode', name, path, seed, ok=False) + expected_exit = 2 if variant == 'go' else 1 + assert result.returncode == expected_exit, (variant, 'unexpected rejection exit', result) + for fault in ('runtime error:', 'IndexError:', 'MemoryError:', 'AddressSanitizer', + 'UndefinedBehaviorSanitizer', 'Segmentation fault'): + assert fault not in result.stderr, (variant, 'runtime fault instead of rejection', result.stderr) + return result + + def batch(variant, requests, label, *, command=None, ok=True): + path = work / (label + '.requests') + path.write_text(''.join('\n'.join(map(str, request)) + '\n' for request in requests)) + environment = dict(env, PYTHONPATH=str(work / 'python') + os.pathsep + env['PYTHONPATH']) + return run([*(commands[variant] if command is None else command), '--batch', path], + environment=environment, ok=ok) + + assert cli('--print-schema-id', truck) == SCHEMA_ID + assert SCHEMA_ID in cli('--describe', truck) + def verify_identity(variant, observed): + assert observed == SCHEMA_ID, (variant, 'schema_id mismatch', observed, SCHEMA_ID) + + for variant in commands: + observed = adapter(variant, 'identity', '-', '-').stdout.strip() + verify_identity(variant, observed) + try: + verify_identity(variant, observed[:-1] + ('0' if observed[-1] != '0' else '1')) + except AssertionError as error: + assert 'schema_id mismatch' in str(error) + else: + raise AssertionError('identity mutation escaped the matrix assertion') + report['mutations'].append({'mutation': 'incompatible observed configuration identity', + 'result': f'DETECTED by the same full-128-bit metadata comparison for {len(commands)} available bindings'}) + sys.path.insert(0, str(source / 'runtime/python/src')) + from quarry.runtime.generic import QbsSchema, validate_brf, ValidatedRecord, RecordArrayView, BrfError + schemas = [] + enum_schemas = [] + for reflective in (False, True): + qbs = work / ('reflective.qbs' if reflective else 'minimal.qbs') + options = ['--qbs-reflective'] if reflective else [] + cli('--emit-qbs', qbs, *options, truck) + schema = QbsSchema.from_bytes(qbs.read_bytes()) + assert schema.schema_id.hex() == SCHEMA_ID + schemas.append((qbs, schema)) + eqbs = work / ('enum-reflective.qbs' if reflective else 'enum-minimal.qbs') + cli('--emit-qbs', eqbs, *options, source / 'tests/fixtures/interop_matrix/enum.brd') + enum_schemas.append((eqbs, QbsSchema.from_bytes(eqbs.read_bytes()))) + configuration.check(args, source, work, env, run, cli, VARIANTS, commands, report) + report['checks'].append(f'128-bit schema_id: {len(commands)} available generated bindings, CLI, describe, minimal/reflective QBS') + + # Generic numeric field access works identically with minimal/reflective QBS. + def generic(name, view, seed): + assert view.record_schema.record_id == BY_NAME[name][0] + if seed < 0: + assert all(view.field(i) is None for i in range(len(BY_NAME[name][1]))) + return + for index, (field, kind, _) in enumerate(BY_NAME[name][1]): + actual, expected = view.field(index), values(name, seed)[field] + if kind.endswith('[]'): + assert isinstance(actual, RecordArrayView) and len(actual) == 2 + for i, child in enumerate(actual): + generic(kind[:-2], child, seed + i) + elif kind in BY_NAME: + assert isinstance(actual, ValidatedRecord) + generic(kind, actual, seed) + else: + assert actual == expected, (name, field, actual, expected) + + generic_path = work / 'generic.c' + generic_path.write_text(adapters.generic_c()) + generic_exe = work / 'generic-c' + generic_flags = ['--coverage'] if args.coverage.lower() in ('on', '1', 'true') else [] + run([args.cc, '-std=c99', '-Wall', '-Wextra', '-Wpedantic', '-Werror', + '-I' + args.runtime_include, + *generic_flags, generic_path, args.runtime_c, '-o', generic_exe]) + records = [] + + def images(name): + return enum_schemas if name.startswith('matrix.') else schemas + + for producer in commands: + batch(producer, [('encode', name, work / f'{producer}-{name}{suffix}.brf', seed) + for name, _, _ in RECORDS + for suffix, seed in (('', 0), ('-empty', -1))], producer + '-produce') + + for producer in commands: + for name, expected_id, _ in RECORDS: + path = work / f'{producer}-{name}.brf' + data = path.read_bytes() + assert int.from_bytes(data[4:8], 'big') == expected_id, (producer, name) + records.append((producer, name, 0, path)) + for qbs, schema in images(name): + view = validate_brf(schema, schema.record_by_id(expected_id), data) + generic(name, view, 0) + if name == 'truck.engine.EngineStatus': + run([args.generic_cpp, qbs, path]) + # All producer streams must match byte for byte below. Inspect + # one representative producer, rather than launch the same CLI + # repeatedly on identical bytes. Keep every five-way decode. + if producer == 'c': + inspection = run([args.inspector, '--qbs', qbs, '--brf', path, '--record-id', expected_id]).stdout + if name == 'truck.engine.EngineStatus': + assert '1450' in inspection and '-12' in inspection and '1234' in inspection and '1235' in inspection, inspection + # C generic views expose the actual nested backing span. Python's + # existing ValidatedRecord.source intentionally retains the root; + # do not infer child byte ranges from it or add a second parser. + for qbs, _ in images(name): + if producer != 'c' and qbs != images(name)[0][0]: + continue + prefix = str(work / (producer + '-' + name + '-cut')) if qbs == images(name)[0][0] else '-' + result = run([generic_exe, name, expected_id, qbs, path, 0, prefix]) + for line in result.stdout.splitlines(): + child_name, child_seed, child_path = line.split(' ', 2) + child_seed, cut = int(child_seed), Path(child_path) + records.append((producer, child_name, child_seed, cut)) + # Batch independent encodings for distinct array-element values. Seed zero + # already has an independent top-level producer file for each type. + for producer in commands: + requests = sorted({(name, seed) for p, name, seed, _ in records + if p == producer and seed != 0}) + batch(producer, [('encode', name, work / f'{producer}-{name}-{seed}.standalone', seed) + for name, seed in requests], producer + '-standalone') + for p, name, seed, path in records: + if p != producer: + continue + standalone = work / (f'{producer}-{name}-{seed}.standalone' if seed else f'{producer}-{name}.brf') + assert path.read_bytes() == standalone.read_bytes(), path + # Absent/default records distinguish absence from populated zero values and + # cover variable record/array/string empty representations in every cell. + for producer in commands: + for name, expected_id, _ in RECORDS: + path = work / f'{producer}-{name}-empty.brf' + records.append((producer, name, -1, path)) + for qbs, schema in images(name): + view = validate_brf(schema, schema.record_by_id(expected_id), path.read_bytes()) + generic(name, view, -1) + if producer == 'c': + run([generic_exe, name, expected_id, qbs, path, -1, '-']) + run([args.inspector, '--qbs', qbs, '--brf', path, '--record-id', expected_id]) + # All producers must agree before routing every stream through every consumer. + for name, _, _ in RECORDS: + for suffix in ('', '-empty'): + assert len({(work / f'{p}-{name}{suffix}.brf').read_bytes() for p in commands}) == 1, (name, suffix) + print('Producer \\ Consumer | ' + ' | '.join(VARIANTS), flush=True) + failed_cells = [] + for producer in VARIANTS: + row = [] + for consumer in VARIANTS: + if producer not in commands or consumer not in commands: + row.append('SKIP') + report['cells'].append(dict(producer=producer, consumer=consumer, result='SKIP', + reason='Go toolchain unavailable')) + continue + selected_records = [(name, seed, path) for p, name, seed, path in records if p == producer] + result = batch(consumer, [('decode', name, path, seed) for name, seed, path in selected_records], + f'{producer}-to-{consumer}', ok=False) + if result.returncode: + failed_cells.append((producer, consumer, result.stderr)) + row.append('FAIL') + report['cells'].append(dict(producer=producer, consumer=consumer, result='FAIL', + fixtures=[p.name for _, _, p in selected_records], + diagnostic=result.stderr)) + continue + for name, seed, path in selected_records: + observed = int.from_bytes(path.read_bytes()[4:8], 'big') + report['cells'].append(dict(producer=producer, consumer=consumer, + fixture=path.name, record=name, expected_id=BY_NAME[name][0], observed_id=observed, + bytes='PASS', decode='PASS', result='PASS')) + row.append('PASS') + print(producer + ' | ' + ' | '.join(row), flush=True) + assert not failed_cells, failed_cells + report['checks'].append(f'{len(records)} populated/default top-level and extracted nested streams; generic C/Python + C++ EngineStatus probe + inspector in both QBS modes') + + # Every populated/default producer fixture must retain its actual bytes + # under naming isolation, not just its schema_id. The A4.5 application + # separately exercises both revisions together in one process. + for variant in commands: + directory = work / variant + cli(*VARIANTS[variant], '--name-prefix', 'rev_a', '-o', directory, truck) + executable = work / (variant + '-prefixed-adapter') + if variant in ('c', 'cpp', 'cpp-c'): + compile_native(variant, directory, executable, adapters.prefixed(variant)) + command = [executable] + elif variant == 'python': + path = work / 'python-prefixed-adapter.py' + path.write_text(adapters.prefixed(variant)) + command = [sys.executable, path] + else: + path = directory / 'cmd/prefixed/main.go' + path.parent.mkdir(parents=True) + path.write_text(adapters.prefixed(variant)) + run(['go', 'build', '-o', executable, './cmd/prefixed'], cwd=directory) + command = [executable] + requests = [('encode', name, work / f'{variant}-{name}-prefixed{suffix}.brf', seed) + for name, _, _ in RECORDS for suffix, seed in (('', 0), ('-empty', -1))] + batch(variant, requests, variant + '-prefixed', command=command) + environment = dict(env, PYTHONPATH=str(work / 'python') + os.pathsep + env['PYTHONPATH']) + verify_identity(variant, run([*command, 'identity', '-', '-', 0], environment=environment).stdout.strip()) + for name, _, _ in RECORDS: + for suffix in ('', '-empty'): + assert (work / f'{variant}-{name}-prefixed{suffix}.brf').read_bytes() == (work / f'{variant}-{name}{suffix}.brf').read_bytes(), (variant, name, suffix) + report['checks'].append('all available producers: prefixed populated/default BRF bytes and full schema_id match every unprefixed fixture') + + # Negative controls call the very same adapter entry points as ordinary cells. + base = work / 'c-truck.engine.EngineStatus.brf' + if not base.exists(): + raise AssertionError('C99 baseline required') + for mutation in ('record-id', 'field-value', 'broken-pair'): + damaged = work / (mutation + '.brf') + data = bytearray(base.read_bytes()) + if mutation == 'record-id': + data[4:8] = (1).to_bytes(4, 'big') + damaged.write_bytes(data) + elif mutation == 'field-value': + adapter('c', 'encode', 'truck.engine.EngineStatus', damaged, 1) + else: + # Valid Timestamp delivered to the EngineStatus consumer cell. + adapter('c', 'encode', 'truck.common.Timestamp', damaged) + diagnostics = {} + for consumer in commands: + if mutation == 'field-value': + adapter(consumer, 'decode', 'truck.engine.EngineStatus', damaged, 1) + elif mutation == 'broken-pair': + adapter(consumer, 'decode', 'truck.common.Timestamp', damaged) + rejected = reject(consumer, 'truck.engine.EngineStatus', damaged) + diagnostics[consumer] = rejected.stderr[-2000:] + + report['mutations'].append({'mutation': mutation, 'result': 'DETECTED by same matrix decode/value assertions', 'diagnostics': diagnostics}) + # Malformed payloads exercise errors beyond record-ID mismatches. These + # mutations modify existing public producer bytes, not an alternate codec. + camera = work / 'c-truck.cms.CameraHealth.brf' + engine = base.read_bytes() + invalid_utf8 = bytearray(camera.read_bytes()) + location = invalid_utf8.index(b'front0') + invalid_utf8[location] = 0xff + enum_wire = bytearray((work / 'c-matrix.EnumSample.brf').read_bytes()) + enum_wire[-2:] = (4).to_bytes(2, 'big') # not a member of Mode + # Find an actual independently extracted Timestamp span, then change only + # its ID inside GearState; the parent's authoritative ID remains intact. + gear = bytearray((work / 'c-truck.transmission.GearState.brf').read_bytes()) + timestamp = (work / 'c-truck.common.Timestamp.brf').read_bytes() + child_offset = gear.index(timestamp) + gear[child_offset+4:child_offset+8] = (1).to_bytes(4, 'big') + errors = [('truncated', 'truck.engine.EngineStatus', engine[:-1]), + ('trailing', 'truck.engine.EngineStatus', engine + b'\0'), + ('invalid-utf8', 'truck.cms.CameraHealth', invalid_utf8), + ('unknown-enum', 'matrix.EnumSample', enum_wire), + ('nested-legacy-id', 'truck.transmission.GearState', gear)] + for label, name, data in errors: + path = work / (label + '.brf') + path.write_bytes(data) + for consumer in commands: + reject(consumer, name, path) + for qbs, schema in images(name): + assert run([args.inspector, '--qbs', qbs, '--brf', path, + '--record-id', BY_NAME[name][0]], ok=False).returncode == 6, label + try: + validate_brf(schema, schema.record_by_id(BY_NAME[name][0]), data) + except BrfError: + pass + else: + raise AssertionError(('generic Python accepted malformed record', label)) + assert run([generic_exe, name, BY_NAME[name][0], qbs, path, 0, '-'], ok=False).returncode == 1, label + report['checks'].append(f'{label}: all generated decoders, C/Python generic runtimes and both inspector modes reject') + legacy_types = set() + for producer, name, seed, path in records: + # A representative top-level and every nested type: current expected + # mapping rejects RC3 IDs; no claim about universal numeric validity. + if producer != 'c' or seed != 0 or name in legacy_types: + continue + legacy_types.add(name) + damaged = work / 'legacy.brf' + data = bytearray(path.read_bytes()) + data[4:8] = (BY_NAME[name][0] & 0xffff).to_bytes(4, 'big') + damaged.write_bytes(data) + for consumer in commands: + reject(consumer, name, damaged) + for qbs, schema in images(name): + assert run([args.inspector, '--qbs', qbs, '--brf', damaged, + '--record-id', BY_NAME[name][0]], ok=False).returncode == 6 + report['checks'].append('legacy RC3 mapping rejected by all available generated decoders and inspector; positive controls above') + report['elapsed_seconds'] = round(time.monotonic() - start, 3) + (output_root / 'report.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps({k: v for k, v in report.items() if k != 'cells'}, indent=2), flush=True) + + +if __name__ == '__main__': + main()