diff --git a/CLAUDE.md b/CLAUDE.md index 85e4b73..a52e24c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -97,8 +97,8 @@ YAML source (.brd) Two frontends coexist during migration: - **The normative YAML frontend** (`frontend::YamlCompiler::compile`, `compiler/frontend`) is - the production path. It is import-free and feeds normalized YAML directly through symbols, - semantic validation, layout, and Schema IR. + the production path. It loads the root and transitive relative-import closure, then feeds + normalized YAML through shared symbols, semantic validation, layout, and Schema IR. - **A legacy declaration-syntax lexer/parser** (`compiler/parser`, `compiler/ast`) exists only for parser/AST compatibility testing. It is not wired into the production pipeline, and import declarations it parses are syntax only — nothing resolves them. @@ -124,7 +124,7 @@ treats architecture docs as authoritative "what" and expects code to match them. | `schema_ir/` | Schema IR builder/validator (`proto/quarry/schema_ir.proto`) | | `frontend/` | `YamlCompiler` — orchestrates YAML → Schema IR | | `backend/` | Schema IR → generated C++ output planning and rendering | -| `imports/` | Reserved; no active import-resolution pass exists yet | +| `imports/` | Reserved; production relative-import graph loading lives in `frontend/` | Each CMake target in `compiler/CMakeLists.txt` corresponds 1:1 to one of these directories (`quarry_compiler_`), with dependencies flowing strictly downstream along the @@ -156,16 +156,16 @@ schema compiler's `--print-generated-code-api-version` query. ### `tools/` — `quarry-schema-compiler` The CLI entry point (`tools/schema_compiler`) built on the compiler libraries above. It -compiles exactly one `.brd` file through `YamlCompiler` and the backend, and writes generated -files. Supports `--list-outputs` (print planned generated paths without writing), +compiles one `.brd` root and its complete relative-import closure through `YamlCompiler`, +then emits selected namespaces for C, C++ owning/C-storage, Python or Go. Supports `--list-outputs` (print planned generated paths without writing), `--print-generated-code-api-version` (machine-readable compatibility query used by CMake), `--version`, `--help`. Full CLI contract and exit codes are documented in `tools/README.md` — treat that file as the source of truth for flag behavior rather than re-deriving it from code. ### Distribution boundary -Only two things are installed/exported: `Quarry::runtime` (header-only) and -`Quarry::schema_compiler` (executable), plus CMake package files +Installed/exported targets are `Quarry::runtime` (C++ header-only), `Quarry::runtime_c` +(compiled C runtime) and `Quarry::schema_compiler` (executable), plus CMake package files (`QuarryConfig.cmake`, `QuarryGenerate.cmake`, etc.) and the `quarry_generate_cpp()` helper. Everything else under `compiler/` (compiler libraries, Schema IR protobuf), `tests/`, `fuzz/` is a source-tree implementation detail, not a public diff --git a/compiler/README.md b/compiler/README.md index 31b6a74..b135609 100644 --- a/compiler/README.md +++ b/compiler/README.md @@ -21,7 +21,7 @@ and `backend::CodegenOptions` and returns generated files or a backend error. The compiler does not currently provide: * a file-loading source compiler facade -* an import resolver +* a package/network import resolver (production YAML relative imports are supported) * a declaration-syntax production frontend * a combined source-to-backend facade * install or export rules for compiler libraries @@ -83,3 +83,14 @@ libraries remain source-tree implementation details. There are currently no for compiler libraries. External compiler-library API shape, package layout, and stability guarantees are deferred until a real embedding consumer or packaging requirement exists. + +## Stage A configuration boundary + +`YamlCompiler::compile` resolves the complete transitive relative-import closure, +rejects cycles and imported configuration documents, and plans all namespaces +before selecting outputs. Multiple files may contribute to one namespace. +The CLI's configuration preparation shares one layout and wire identity with all +backends. Native gid then identifies normalized definitions and dependencies, +independently of schema_id and epochs. Compiler QBS accessors remain internal +tooling. See the [normative contract](../docs/specifications/configuration-and-code-identity.md) +and [readiness evidence](../docs/release-readiness-v0.1.31-rc.1.md). diff --git a/compiler/backend/README.md b/compiler/backend/README.md index 0be67bb..50b3b78 100644 --- a/compiler/backend/README.md +++ b/compiler/backend/README.md @@ -316,3 +316,13 @@ storage-policy options still use canonical namespace names. Unprefixed output is pinned byte for byte in `tests/fixtures/name_prefix/unprefixed_sha256.json`. See the [source naming contract](../../tools/README.md#deliberate-source-naming-isolation) and [multi-configuration example](../../examples/truck/multi_configuration/README.md). + +## Stage A contract and release migration + +Generate dependent namespaces from one authoritative configuration root. Selection +changes emission only; `--name-prefix` isolates deliberately coexisting sets without +changing wire identity. The [normative identity contract](../../docs/specifications/configuration-and-code-identity.md) +and [release notes](../../docs/release-notes-v0.1.31-rc.1.md) distinguish wire +schema_id, native gid and runtime epochs. Regenerate old bindings and rebuild +consumers; equal epochs do not certify native ABI compatibility. Python has +configuration import checks; the native per-namespace gid applies only to C/C++. diff --git a/compiler/backend_c/README.md b/compiler/backend_c/README.md index e22159f..cbae959 100644 --- a/compiler/backend_c/README.md +++ b/compiler/backend_c/README.md @@ -305,3 +305,13 @@ C++/C-storage wrappers use the same encoded stem; callback language linkage and identity-bearing external names retain their established rules. Unprefixed legacy C spellings and #119's general migration remain unchanged. The existing format-1 generated-code identity hashes the changed definitions normally. + +## Stage A contract and release migration + +Generate dependent namespaces from one authoritative configuration root. Selection +changes emission only; `--name-prefix` isolates deliberately coexisting sets without +changing wire identity. The [normative identity contract](../../docs/specifications/configuration-and-code-identity.md) +and [release notes](../../docs/release-notes-v0.1.31-rc.1.md) distinguish wire +schema_id, native gid and runtime epochs. Regenerate old bindings and rebuild +consumers; equal epochs do not certify native ABI compatibility. Python has +configuration import checks; the native per-namespace gid applies only to C/C++. diff --git a/compiler/backend_python/README.md b/compiler/backend_python/README.md index 1018f28..d7547bc 100644 --- a/compiler/backend_python/README.md +++ b/compiler/backend_python/README.md @@ -55,3 +55,13 @@ storage-policy options still use canonical namespace names. Unprefixed output is pinned byte for byte in `tests/fixtures/name_prefix/unprefixed_sha256.json`. See the [source naming contract](../../tools/README.md#deliberate-source-naming-isolation) and [multi-configuration example](../../examples/truck/multi_configuration/README.md). + +## Stage A contract and release migration + +Generate dependent namespaces from one authoritative configuration root. Selection +changes emission only; `--name-prefix` isolates deliberately coexisting sets without +changing wire identity. The [normative identity contract](../../docs/specifications/configuration-and-code-identity.md) +and [release notes](../../docs/release-notes-v0.1.31-rc.1.md) distinguish wire +schema_id, native gid and runtime epochs. Regenerate old bindings and rebuild +consumers; equal epochs do not certify native ABI compatibility. Python has +configuration import checks; the native per-namespace gid applies only to C/C++. diff --git a/compiler/parser/README.md b/compiler/parser/README.md index 24c4385..d865848 100644 --- a/compiler/parser/README.md +++ b/compiler/parser/README.md @@ -1,6 +1,7 @@ # Parser -Owns lexical scanning and syntax parsing for the current schema language. +Owns the legacy declaration-syntax lexer/parser compatibility surface. The +production schema language uses the YAML frontend. ## Lexer Responsibility @@ -46,12 +47,11 @@ errors through the diagnostics framework. Current implementation status: * the normative `.brd` grammar is defined in `docs/specifications/schema-language.md` -* the current parser implementation is transitional scaffolding for that YAML - grammar +* this declaration parser is legacy compatibility infrastructure, not the YAML grammar * the repository also contains a separate generic YAML syntax layer under - `compiler/yaml`; it preserves YAML order and source ranges but does not yet - decode Quarry schema vocabulary -* the production-facing YAML orchestration layer now compiles import-free YAML + `compiler/yaml`; its parser preserves YAML order/source ranges, and the separate + schema decoder interprets Quarry vocabulary +* the production-facing YAML orchestration layer resolves transitive YAML relative imports and compiles the configuration through validated Schema IR without a compatibility AST hop after source- schema normalization * the legacy declaration parser and AST remain compatibility infrastructure for @@ -61,8 +61,7 @@ Current implementation status: shape, source identity, source ranges, and parser diagnostics; they do not require symbol construction or semantic validation * import declarations remain parser syntax only on the legacy declaration - path; there is no import resolver or multi-file import graph in the current - compiler + path; production YAML has its own multi-file relative-import graph loader * the current temporary declaration grammar, annotation parsing, and fixed-size array handling are not normative language contracts * current annotations are transitional string-valued metadata; the normative diff --git a/compiler/schema_ir/README.md b/compiler/schema_ir/README.md index cf9aaa5..0e1d37a 100644 --- a/compiler/schema_ir/README.md +++ b/compiler/schema_ir/README.md @@ -54,9 +54,9 @@ Implementation status: * the normative `.brd` source contract is defined in `docs/specifications/schema-language.md` -* the production-facing YAML frontend now orchestrates the import-free YAML - pipeline through validated Schema IR directly from the normalized - source-schema model +* the production-facing YAML frontend resolves the complete relative-import + closure and orchestrates validated Schema IR directly from the combined + normalized source-schema model * direct normalized-source-schema tests under `tests/yaml/normalized_source_schema_pipeline_test.cpp` provide the primary Schema IR builder unit coverage diff --git a/docs/README.md b/docs/README.md index 23126bd..8bf4f49 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,7 +10,7 @@ Version resolution and release cleanliness are documented in [`versioning.md`](versioning.md). Quarry is a language-neutral schema compiler and BRF serialization system with -production C++, strict-C99 C, and Python backends. The documentation records +production C++, strict-C99 C, Python and Go backends. The documentation records current behavior and stable architecture decisions separately from deferred work. @@ -213,3 +213,10 @@ When adding or changing documentation: When two documents need the same concept, keep the full explanation in the most specific architecture document and add a short reference from the other. + +## Stage A release candidate + +- [Normative configuration and generated identity](specifications/configuration-and-code-identity.md) +- [Executable CLI guide](stage-a-cli.md) +- [v0.1.31-rc.1 release notes](release-notes-v0.1.31-rc.1.md) +- [Readiness and unresolved release gates](release-readiness-v0.1.31-rc.1.md) diff --git a/docs/compiler-architecture.md b/docs/compiler-architecture.md index 6b23a7a..b25d6de 100644 --- a/docs/compiler-architecture.md +++ b/docs/compiler-architecture.md @@ -249,9 +249,10 @@ separate from the compact runtime manifest. ## Import Resolution Policy -There is no active import-resolution stage in the current repository. -Import declarations remain legacy parser syntax only and are ignored by the -current downstream compiler pipeline. +Production YAML compilation resolves transitive relative imports through the +frontend graph loader before shared symbols, semantics and layout. Canonical paths +are loaded once and cycles are rejected. Legacy declaration-syntax imports remain +parser-only compatibility syntax; no package/network import resolver exists. --- @@ -385,7 +386,8 @@ C/C++ backends additionally compute generated-code identity for each namespace and variant over the complete configuration in dependency order. Format 1 hashes normalized generated definitions, the supplied wire configuration identity and direct dependency identities, including unselected namespaces and their effective -storage policies. `--generate` and output naming do not affect the result. This +storage policies. `--generate`, output directories, extensions and root-file stems do not affect +the result. `--name-prefix` can change emitted definitions and therefore gid. This is generation-time metadata, with no runtime Schema IR interpretation or hashing. It is distinct from both wire `schema_id` and the generated/runtime API epoch; see [the identity specification](design/configuration-identity.md#161-computation) @@ -406,3 +408,14 @@ Open questions for later specifications or implementation documents: * whether Schema IR should remain an in-memory compiler structure only, or also have a serialized debug/tooling representation for documentation generators, compatibility checkers, visualization tools, and IDE integrations + +## Stage A implementation boundary + +A1–A5 are merged; A6 reconciles specifications and release evidence. The +[normative identity contract](specifications/configuration-and-code-identity.md) +defines configuration, generated definitions and epochs separately. QBS identity +accessors read stored metadata without introducing runtime hashing or Schema IR +dependencies. `--describe` reports resolved IDs, identity, formats and epochs; +exact release tags are informational build metadata. Discovery, descriptors, +partial images and translation remain Stage B proposals. See the +[readiness report](release-readiness-v0.1.31-rc.1.md). diff --git a/docs/compiler-passes.md b/docs/compiler-passes.md index 759dfc3..d27496f 100644 --- a/docs/compiler-passes.md +++ b/docs/compiler-passes.md @@ -77,17 +77,16 @@ validation as an unsupported v0.1 construct; see `compiler/backend/README.md` for the exact supported array element type set. The `compiler/frontend` orchestration layer now exposes a production-facing -import-free YAML compilation path through validated Schema IR. That layer now +import-aware YAML compilation path through validated Schema IR. That layer now builds symbols, semantic state, and Schema IR directly from the normalized source-schema model. AST remains in use only for the independent legacy declaration-syntax parser and AST tests. The legacy declaration parser remains available during the migration. -Source loading remains outside the compiler passes. Callers register source -text with `SourceManager`, receive a `SourceFileId`, and parse exactly one -registered source file per parser invocation. There is no import-resolver -pass in the current repository; import declarations remain syntax only on the -legacy AST path and are ignored by downstream passes. +Root source registration remains caller-owned: callers register text with +`SourceManager` and receive a `SourceFileId`. Production `YamlCompiler` loads +relative imports through its graph loader. Each parser invocation parses one +registered unit. Legacy AST imports remain syntax only. There is no production root-source loading facade for declaration syntax yet; file loading and source registration remain caller-owned. The legacy declaration-syntax frontend is compatibility infrastructure rather @@ -173,15 +172,15 @@ or layout computation. --- -## 2. Import Resolution Status +## 2. Production YAML import loading -There is no import-resolver pass in the current repository. Import -declarations remain legacy AST syntax only. The parser retains them for -compatibility with historical `.brd` files, but downstream passes ignore them -and no production stage loads imported files, resolves import names to files, -or builds a document graph. - ---- +`frontend::YamlCompiler` loads the root's transitive relative-import graph, +canonicalizes paths, loads each once and rejects cycles before downstream layout. +A configuration root (`configuration` and `imports` only) owns no declarations +and cannot be imported. A record root also defines a configuration. Every source +unit contributes to the shared normalized/symbol/semantic models; namespaces may +span files. The legacy declaration parser retains imports as syntax only and is +not the production loader. No package or network import resolver is implied. ## 3. Namespace Builder @@ -216,8 +215,7 @@ Required by: ### Assumptions on Input -The schema has already had unsupported YAML imports rejected and normalized -identifiers validated. +The complete YAML import closure has been loaded and normalized identifiers validated. ### Responsibilities @@ -234,7 +232,7 @@ identifiers validated. * every registered declaration has a fully qualified name * namespace nesting is represented canonically * duplicate symbols have been rejected -* import declarations remain syntax only and do not produce symbols +* imported declarations participate in the shared symbol index; import directives do not become symbols ### Diagnostics Emitted @@ -585,3 +583,15 @@ Internal compiler errors indicate compiler defects rather than user errors. Schema IR is produced only if all compilation passes complete successfully. Backends are never invoked after fatal compilation failures. + +## Configuration preparation and generation + +After validated Schema IR, `tools/schema_compiler/configuration_preparation.hpp` +prepares the canonical BRF layout and algorithm-1 wire configuration identity once. +QBS and every backend consume those values; listing outputs uses planning without +hashing. Native backends then compute per-namespace format-1 gid in dependency +order, including unselected dependencies and effective storage policies. Selection +controls emission, never the resolved configuration or record IDs. Prefixing is a +backend naming projection. See [compiler architecture](compiler-architecture.md#configuration-preparation), +[the identity contract](specifications/configuration-and-code-identity.md) and +[CLI verification](stage-a-cli.md). diff --git a/docs/design/c-backend.md b/docs/design/c-backend.md index 6258c37..84c3d11 100644 --- a/docs/design/c-backend.md +++ b/docs/design/c-backend.md @@ -1,10 +1,13 @@ # C Backend -> Current status (PR-139): the C backend supports compiler-resolved -> cross-namespace enum and record fields, including arrays, by consuming -> `OutputPlan` dependency metadata and emitting deterministic generated-header -> includes. Referenced namespaces are generated from the same compilation root. -> Nested arrays and recursive by-value records remain out of scope. +> Stage A status: C/C++-storage epoch 7, header bindings backed by the shared C +> codec, with include-only compatibility `.c`/`.cpp` stubs. Relative-import +> dependencies, configuration/gid checks, per-namespace storage and explicit +> prefixes are implemented. The original proposal and milestone history below +> (including epoch-2 and split-source recommendations) are historical, not the +> current generation contract. See `compiler/backend_c/README.md` and +> `docs/specifications/configuration-and-code-identity.md`. Nested arrays and +> recursive by-value records remain unsupported. ## Implementation Status diff --git a/docs/design/configuration-identity.md b/docs/design/configuration-identity.md index dcc58c1..78bf1f0 100644 --- a/docs/design/configuration-identity.md +++ b/docs/design/configuration-identity.md @@ -2,7 +2,9 @@ Status: **approved; A4.1–A4.5 and #111 G1–G5 implemented**. A4 builds on hierarchical record IDs (#84) and configuration roots / `--generate` (#86); §15 records its historical review -and §16 specifies the implemented generated-code identity. +and §16 describes the implemented generated-code identity. The normative +[configuration and generated identity contract](../specifications/configuration-and-code-identity.md) +and [release-readiness report](../release-readiness-v0.1.31-rc.1.md) record the Stage A baseline. ## 1. Summary @@ -381,7 +383,7 @@ $ quarry-schema-compiler --describe examples/truck/schemas/configuration.brd configuration: class8_truck root: examples/truck/schemas/configuration.brd schema_id: 9200ca494f010801b830d0857cf66dde (algorithm 1: sha256-128) -compiler: quarry-schema-compiler 0.1.288 (2507998, release tag v0.1.31-rc.1) +compiler: quarry-schema-compiler 0.1.291 (2a9aafd, untagged) formats: brf 2, qbs 1, schema-ir 1 generated-code epochs: cpp 3, c 7, python 1, go 1 domains: 6 @@ -462,7 +464,7 @@ guide](../generated-code-identity-validation.md) for current measured coverage. order, C and C++ must fail to compile. 5. **Multiple configurations:** - C++: a program links rev A and rev B in separate translation units and decodes each - configuration's records correctly. This is the ODR regression test, and it would fail today. + configuration's records correctly. This is the maintained ODR regression test; it passes with generated-code identity isolation. - C: the same with two translation units. - Go: two import paths in one binary. - Python: rev A and rev B imported with `--name-prefix` in one process. @@ -588,7 +590,7 @@ A4.3 and A4.4 are independent of A4.2. The A5 cross-language matrix follows A4.5 types, so the C part is configuration-specific too (§4.3). Two configurations with different record IDs and layouts are linked into one executable from separate translation units and tested. -## 16. Generated-code identity in C and C++ bindings (#111 G1–G4) +## 16. Generated-code identity in C and C++ bindings (#111 G1–G5) `schema_id` identifies the wire configuration; it does not identify generated definitions. Field or enum-member renames, unused enums, `--c-optimize-size` and generator changes all keep @@ -641,11 +643,13 @@ identity it has when it is generated itself. The selected headers are checked to the normalized text their identity was computed from (A3); then every placeholder is substituted. Consequently the identity does **not** depend on `--output-directory`, `--file-extension`, -`--root-file-stem`, `--generate`, import order, the configuration name, source paths or the +`--root-file-stem`, `--generate`, the configuration name, source paths or the compiler build; and it **does** change with any change of generated definitions: names, unused enums, storage options, generator implementation, epochs, `schema_id` and, through the dependency -list and the dependency checks, any change of a generated dependency. Identical output from two -compiler releases has one identity. +list and the dependency checks, any change of a generated dependency. Identical normalized output from two +compiler releases has one identity. Import reordering preserves wire identity, but +may change declaration order and therefore gid (#90). `--name-prefix` can change +emitted definitions and therefore gid without changing format 1 or schema_id. ### 16.2 Generated C++ (owning and C storage) diff --git a/docs/design/record-identity-and-schema-discovery.md b/docs/design/record-identity-and-schema-discovery.md index e96ddc8..f179013 100644 --- a/docs/design/record-identity-and-schema-discovery.md +++ b/docs/design/record-identity-and-schema-discovery.md @@ -1,10 +1,10 @@ # Record Identity and Schema Discovery -Status: **accepted; Stage A in progress.** A1 (C++ include guards) is merged (#81), and so is A2 -(hierarchical record IDs, §3, #84). A3 (configuration roots and `--generate`, §4) is implemented. -Of A4, A4.1 (configuration identity, #91) and A4.2 (generated identity and dependency checks, #99) -are implemented; A4.3 onward are not. -`v0.1.31-rc.1` is blocked on Stage A. +Status: **accepted; Stage A implementation A1–A5 complete, A6 documentation reconciled**. +A1 #81, A2 #84, A3 #86, A4.1 #91, A4.2 #106 and #111 G1–G5 (#116–#123), +A4.3 #124, A4.4 #125, A4.5 #126 and A5 #127 are merged. Stage B remains future work. +This does not authorize release publication: see the +[release-readiness report](../release-readiness-v0.1.31-rc.1.md) for unresolved gates. ## 1. Summary @@ -20,7 +20,7 @@ for selected namespaces, but IDs always come from the complete configuration. The configuration's identity is QBS's existing `schema_id`, reused unchanged. Its input already covers every record ID, FQN and wire definition. -A Schema Descriptor and a three-level discovery protocol let a cloud service identify each vehicle's +The future Stage B Schema Descriptor and three-level discovery protocol would let a cloud service identify each vehicle's configuration, classify compatibility, and decode or translate data during OTA rollouts. Stage A, which blocks the release, delivers: @@ -35,7 +35,7 @@ Stage A, which blocks the release, delivers: Stage B delivers the binary descriptor section, discovery messages, partial retrieval, compatibility negotiation and gateway translation. -## 2. Findings from the current implementation +## 2. Historical findings before Stage A | Area | Current behavior | Consequence for this design | |---|---|---| @@ -50,7 +50,7 @@ negotiation and gateway translation. | Version metadata | Git builds report a numeric development version (`0.1.269-dirty`); the prerelease tag exists only in release-archive metadata | A release identity field is needed for "version including prerelease" | | Generic runtime nested records | Located by QBS table index; the child header must equal the referenced record's `record_id` | Works unchanged with hierarchical IDs | -## 3. Record ID assignment (normative proposal) +## 3. Implemented record ID assignment ### 3.1 Definitions @@ -97,8 +97,10 @@ FQN = namespace + `.` + name (`BC7006`). `record_id = (domain_id << 16) | local_record_id`, written big-endian in the BRF v2 header as today. Consequences: -- Every valid ID is at least `0x00010001`, and every ID below `0x10000` is invalid. Every RC3-era ID was - below `0x10000`, so legacy records are detectable and always rejected. +- Every application ID allocated by this algorithm is at least `0x00010001`. RC3-era IDs + below `0x10000` do not match the current expected mappings; generated decoders and the + inspector reject them in that configuration context. This does not add a universal numeric + range check to every generic parser. - Nested records carry their own domain's ID; there is no inheritance from the parent. - IDs are local to the configuration. The same record has different IDs in different configurations, so a receiver must know the sender's configuration (§6) before interpreting any ID. @@ -158,7 +160,7 @@ ruled out. separates configurations by import prefix. A4 adds an opt-in per-configuration name prefix for the other languages: - - C: a symbol prefix (for example `cfgA_truck_engine_EngineStatus_t`); + - C: an injectively encoded symbol prefix (for example `cfgA_truck_engine_EngineStatus_t`); - C++: an outer namespace (`cfgA::truck::engine`); - Python: a package prefix. @@ -187,12 +189,11 @@ Challenges and limits: - **Partial QBS images** (§8, level 2) would get a different `schema_id`, because the input covers the image's records. A subset must therefore carry its parent configuration's `schema_id` separately from its own content ID. -- **Device-side availability:** the C runtime doesn't expose or verify `schema_id`. Stage A adds a - read-only accessor; verifying it on the device needs SHA-256 in the runtime, which is a footprint - question and belongs to Stage B. +- **Device-side availability:** A4.3 exposes the stored identity with `quarry_qbs_schema_id()`. + This read-only accessor does not verify the digest; optional device-side hashing remains Stage B. - **128 bits** is sufficient for discrimination and uncoordinated identifiers. -## 6. Schema Descriptor +## 6. Schema Descriptor (future Stage B) ### 6.1 Contents @@ -252,7 +253,7 @@ very low risk: The binary section and the parser fix move to Stage B with the discovery protocol, where their format-design choices can be made together. That keeps the RC free of new wire-adjacent format work. -## 7. Fingerprints and compatibility classification +## 7. Fingerprints and compatibility classification (future Stage B) Two fingerprints per record, each SHA-256 truncated to 64 bits over the canonical QBS identity encoding: @@ -301,7 +302,7 @@ with the claimed value. **Authentication and authorization** belong to the transport (for example mutual TLS or the vehicle security gateway). The discovery messages carry no credentials. -## 9. OTA operation +## 9. OTA operation (future Stage B) 1. **Release time.** CI compiles each vehicle software configuration and uploads its QBS image, keyed by `schema_id`, to a cloud schema registry. The generated cloud decoders are versioned by `schema_id`; @@ -378,7 +379,8 @@ configuration root. Its domains are `truck.common` = 1 and `truck.engine` = 2, s `0x00020001`. - That number equals `truck.brakes.AbsEvent` in the truck configuration. **Interpreting IDs without - knowing the configuration is unsafe**, which is why the `schema_id` handshake is mandatory. + knowing the configuration is unsafe**, which is why Stage B proposes a `schema_id` handshake. Stage A applications + supply configuration context explicitly; no handshake is implemented. - Integration options: 1. **Preferred:** the supplier builds against the OEM's configuration root and `--generate`s only its namespaces, giving an exact match. @@ -402,7 +404,7 @@ configuration root. Its domains are `truck.common` = 1 and `truck.engine` = 2, s ## 12. Implementation plan -### Stage A (required for `v0.1.31-rc.1`) +### Stage A (implemented; documentation in A6) | PR | Scope | |---|---| @@ -420,7 +422,7 @@ version gates the release. | PR | Scope | |---|---| -| B1 | Compiler-side QBS parser honors ignorable sections; descriptor extension section `0x8001`; release-tag version field | +| B1 | Compiler-side QBS parser honors ignorable sections; descriptor extension section `0x8001` (informational CLI release-tag reporting already shipped in A4.4) | | B2 | `quarry.discovery` schemas and reference responder/requester (levels 0–2), paging, limits | | B3 | Partial QBS images with content ID plus parent `schema_id` | | B4 | Fingerprints and the compatibility classifier (`--compare A.qbs B.qbs --records ...`) | @@ -436,7 +438,7 @@ version gates the release. | Determinism | repeated builds byte-identical; import reorder leaves IDs and `schema_id` unchanged; selection (`--generate`) never changes IDs or `schema_id` | | Cross-language | C, C++, C++/C-storage, Python, Go × encode/decode × top-level, depth 1, depth 2 × inspector with the configuration image; nested records cut from a parent decode with their own type's decoder | | Configuration mixing | code generated from two configurations fails to build (C, C++, Go) or import (Python) | -| Legacy | RC3-era IDs (all below `0x10000`) rejected by every decoder and the inspector | +| Legacy | RC3-era IDs below `0x10000` rejected against each expected current type mapping by generated decoders and the inspector | | Identity | `schema_id` unchanged by reflective names, comments, import paths and compiler version; changed by any ID or wire change; `--describe` golden output | | Generation | multi-file namespace emits one complete file; CMake helper with a configuration root and selection; install and package consumer tests | | Stage B | descriptor section round trip; old readers skip it; paging and size limits; partial image identity; classifier on the truck A/B and reorder scenarios; translator round trips | diff --git a/docs/design/schema-identity.md b/docs/design/schema-identity.md index 1b1cae1..3a2af53 100644 --- a/docs/design/schema-identity.md +++ b/docs/design/schema-identity.md @@ -100,61 +100,22 @@ configuration changes, if it is needed, is future compatibility work. ## Record Renames -A record's Fully Qualified Name (FQN) defines its logical identity. - -Changing the FQN is therefore considered a change of logical identity unless -the schema explicitly declares that the new record is a rename of an existing -record. - -Record renames are explicit. - -The compiler never attempts to infer a rename. - -If a record's FQN changes without an explicit rename declaration, the compiler -treats the old record as removed and the new record as added. - -An explicit rename instructs the compiler to preserve the existing `recordId` -and associated compiler state. - -Illustrative example: - -```text -existing record: -quarry.telemetry.Location - -renamed record: -quarry.telemetry.GpsLocation - -explicit rename relationship: -quarry.telemetry.GpsLocation was renamed from quarry.telemetry.Location -``` - -With an explicit rename: - -```text -quarry.telemetry.Location -recordId = 17 - -becomes: - -quarry.telemetry.GpsLocation -recordId = 17 -``` - -Without an explicit rename, the compiler treats this as: - -```text -quarry.telemetry.Location removed -quarry.telemetry.GpsLocation added -new recordId allocated for quarry.telemetry.GpsLocation - -illustrative recordId: -quarry.telemetry.GpsLocation -recordId = 42 -``` - -This example describes the intended relationship only. It does not define final -schema syntax for declaring record renames. +Stage A has no rename declaration or preserved allocation state. Renaming a record +changes its FQN and can shift the sorted local IDs; renaming a namespace can shift +domain IDs. Recompile the complete configuration and assess compatibility rather +than assuming the previous ID survives. Explicit rename/evolution policy is future +work, not accepted schema syntax. + +## Configuration and generated identity + +The complete configuration has a 128-bit QBS `schema_id` (algorithm 1). It covers +canonical wire definitions and record/enum FQNs, but excludes field/member names, +unused enums, source paths, compiler versions and source naming options. +C/C++ namespaces additionally have a format-1 `gid` over normalized generated +definitions and dependency identities. API epochs check the generator/runtime +contract independently. None is an authentication mechanism or a native ABI proof. +See the [normative identity contract](../specifications/configuration-and-code-identity.md) +and [consumer migration guide](../generated-binding-compatibility.md). --- @@ -170,7 +131,7 @@ representations without changing their meaning. Binary identifiers are compiler-managed implementation details. -Binary identifiers remain stable as schemas evolve. +Binary identifiers are stable for the same configuration mapping, not across arbitrary schema evolution. Generated language bindings never define record identity; they only represent it. @@ -182,8 +143,6 @@ it. Topics intentionally deferred to future specifications or design documents: * record rename declaration syntax -* record ID allocation algorithm -* manifest format * namespace rename semantics * fieldIndex compatibility rules * compatibility rules diff --git a/docs/distribution-model.md b/docs/distribution-model.md index 423a5bd..6dcf8d8 100644 --- a/docs/distribution-model.md +++ b/docs/distribution-model.md @@ -1,7 +1,7 @@ # Distribution Model Quarry currently supports a small downstream SDK consisting of the -header-only runtime plus the installed schema compiler executable target. The +C++ header-only runtime, compiled C runtime and installed schema compiler executable target. The installed package surface is intentionally smaller than the source-tree build graph. @@ -9,7 +9,8 @@ graph. The supported installed SDK surface is: -* `Quarry::runtime` +* `Quarry::runtime` (C++ owning) +* `Quarry::runtime_c` (C99 and C++/C storage) * `Quarry::schema_compiler` * public runtime headers, including `` and @@ -68,9 +69,10 @@ fails configuration on mismatch. | C runtime library | `quarry_runtime_c`, exported as `Quarry::runtime_c` (PR-108) | Link through CMake and include public C runtime headers | Supported public SDK | | C runtime headers | `include/quarry/runtime_c/binary_record.h`, `include/quarry/runtime_c/version.h` | Compile generated or handwritten C that uses BRF runtime mechanics for the supported scalar, enum, bounded string/bytes, bounded array, nested-record, and compiler-resolved cross-namespace field subset of `--language c` | Supported public SDK | | CMake package files | `QuarryConfig.cmake`, `QuarryConfigVersion.cmake`, `QuarryTargets.cmake`, `QuarryGenerate.cmake` | Package discovery for the runtime(s), schema compiler target, generated-code API package metadata (C++ and, since PR-108, C), and installed-package generation helper (C++ only; no C equivalent yet, see "Evaluated Packaging Models") | Supported public SDK | -| Schema compiler executable | `quarry_schema_compiler`, exported as `Quarry::schema_compiler`, installed as `quarry-schema-compiler` | Direct CLI invocation or CMake command use through `$`; supports `--language cpp` (default), `--language c`, and, since PR-118, `--language python` | Installed tool target | +| Schema compiler executable | `quarry_schema_compiler`, exported as `Quarry::schema_compiler`, installed as `quarry-schema-compiler` | Direct CLI invocation or CMake command use through `$`; supports `--language cpp` (owning or C storage), `c`, `python` and `go` | Installed tool target | | Generated C++ code | Backend output under caller-selected paths | Owned by the downstream project that generated it | Downstream-owned build artifact | | Generated C code | C backend output under caller-selected paths (PR-107/PR-108) | Owned by the downstream project that generated it | Downstream-owned build artifact | +| Generated Go code | Go backend output under caller-selected module paths | Owned by the downstream project that generated it; links the separate Go runtime module | Downstream-owned build artifact | | Generated Python code | Python backend output under caller-selected paths (scalar, enum, bounded string/bytes, supported arrays, nested records, and record arrays) | Owned by the downstream project that generated it | Downstream-owned build artifact | | Python runtime package | `runtime/python/` (`quarry-runtime-python`, importable as `quarry.runtime.python`, with schema-neutral scalar, enum, string/bytes, and array helpers) | Standard wheel/sdist build and `pip install`; not CMake-installed or exported | Supported public SDK within documented scope; PyPI publication remains deferred | | Compiler libraries | `quarry_compiler_*`, `quarry_schema_ir_proto` | Internal source-tree composition and tests | Implementation detail | @@ -202,3 +204,15 @@ decision. In particular: separate host-tools package * language-specific examples should be introduced with their corresponding runtime or generator support + +## Stage A installed consumption + +Installed C includes `quarry/runtime_c/schema_id.h` and `generic_brf.h`; the QBS +identity accessor links `Quarry::runtime_c`. C++ QBS parsing remains compiler-owned +source-tree tooling, not an installed compiler-library SDK. Python wheel/sdist +and the Go runtime module are separate language packages, not CMake targets. +All five binding variants use one root identity; the installed C++ helper supports +`GENERATE`, `NAME_PREFIX` and `SCHEMA_ID_VARIABLE`. C, Python and Go generation +use the installed CLI directly. See [the CLI guide](stage-a-cli.md), +[consumer compatibility](generated-binding-compatibility.md) and +[release migration](release-notes-v0.1.31-rc.1.md). diff --git a/docs/layout-algorithm.md b/docs/layout-algorithm.md index 470d0c5..340b42f 100644 --- a/docs/layout-algorithm.md +++ b/docs/layout-algorithm.md @@ -35,10 +35,8 @@ The Semantic Model provides: All references have already been resolved before layout computation begins. -Layout computation may also consume preserved compiler state when the selected -compiler mode provides it. Preserved compiler state is an optional compiler -input used to reuse existing compiler-managed identifiers. It is not semantic -input and does not change the meaning of the Semantic Model. +Stage A computes identifiers afresh from the complete configuration; no preserved +compiler-state or manifest input is supported. Layout computation does not resolve names, validate schema language semantics, or recover from invalid Semantic Model state. @@ -89,7 +87,6 @@ reproducible. The assignment algorithm has these goals: * uniqueness -* stable assignment when preserved compiler state supplies an existing mapping * deterministic assignment * no user-authored record IDs @@ -128,28 +125,11 @@ The layout pass also verifies that each record's FQN is its namespace FQN and local name joined by `.` (`BC7006`), so the grouping and the canonical identity cannot disagree. -## Recompilation With Preserved Compiler State +## Recompilation and deletion -When preserved compiler state is available, the compiler may reuse existing -`recordId` assignments according to the selected compatibility policy. - -Identifier preservation is policy applied by the compiler before or during -layout computation. Layout computation consumes the resulting identifier mapping -and validates that it is usable for the current Semantic Model. - -New records receive new `recordId` values from the compiler-managed allocation -state after preserved assignments have been applied. - -Rules for record renames, removed records, and long-term identifier reuse belong -to a future compatibility specification. - -## Deleted Records - -Deleted records do not appear in the Layout Model. - -When preserved compiler state is available, deleted record handling is governed -by compatibility policy. Layout computation does not define long-term record ID -reuse policy. +Every compilation recomputes the sorted mapping. Deleted records disappear; +insertions or removals can renumber later locals or domains. No persisted ID reuse, +rename mapping or compatibility-policy mode is implemented. --- @@ -172,24 +152,10 @@ The deterministic field order is derived from the validated Semantic Model and must not depend on map iteration order, file system ordering, or backend behavior. -## Recompilation With Preserved Compiler State - -When preserved compiler state is available, the compiler may preserve existing -`fieldIndex` assignments according to the selected compatibility policy. - -Layout computation consumes the resulting field index mapping and validates that -it is usable for the current record layout. - -New fields receive new `fieldIndex` values from the record's compiler-managed -field allocation state after preserved assignments have been applied. +## Recompilation and removed fields -## Removed Fields - -Removed fields do not appear in the Layout Model. - -When preserved compiler state is available, removed field handling is governed -by compatibility policy. Layout computation does not define long-term -`fieldIndex` reuse policy. +Field indexes are recomputed from declaration order. Removed fields disappear; +there is no persisted field allocation state or automatic schema evolution policy. ## Limits @@ -287,7 +253,7 @@ reintroducing unresolved names. # Determinism -Identical Semantic Models and identical compiler state must always produce +Identical Semantic Models must always produce identical Layout Models. Determinism is achieved by: @@ -295,8 +261,6 @@ Determinism is achieved by: * deterministic record ordering * deterministic field ordering * compiler-managed identifier allocation -* consistent application of preserved identifier mappings supplied by compiler - state * deterministic diagnostic ordering * avoiding dependence on file system order, hash map order, or backend order @@ -307,34 +271,10 @@ artifacts, compatibility analysis, and predictable diagnostics. # Compatibility -Layout computation may evaluate compatibility constraints against preserved -compiler state when that state is available. - -The layout algorithm itself does not define schema evolution policy. It applies -the compatibility policy selected by the compiler and reports layout-level -conflicts. - -Changes that compatibility policy may allow include: - -* preserving a record's logical identity -* preserving an existing `recordId` -* preserving an existing field's `fieldIndex` -* preserving the field type associated with an existing `fieldIndex` -* appending a new field with a new `fieldIndex` - -Changes that compatibility policy may reject or require updated layout metadata -for include: - -* changing a record's logical identity without an explicit rename already - applied before layout computation -* changing the type associated with an existing `fieldIndex` -* exceeding field count limits -* attempting to reuse removed compiler-managed identifiers -* conflicting with preserved compiler state - -This section describes layout-level compatibility concepts only. Detailed -schema evolution, rename, identifier reuse, and binary compatibility rules -belong to a future compatibility specification. +Stage A validates one resolved configuration; it does not compare historical +schemas or apply a rename/evolution policy. Changes to IDs or layouts require +regeneration and rebuilding. BRF v2 alone does not guarantee historical data +compatibility. See [the migration guide](generated-binding-compatibility.md). --- @@ -347,10 +287,7 @@ Layout computation may emit diagnostics such as: * too many fields * layout overflow * unsupported layout construct -* incompatible preserved compiler state * invalid compiler-managed identifiers -* missing preserved identifier state required by the selected compiler mode -* field layout incompatible with preserved `fieldIndex` Diagnostics should use source metadata from the Semantic Model when reporting user-facing schema problems. diff --git a/docs/release-notes-v0.1.31-rc.1.md b/docs/release-notes-v0.1.31-rc.1.md new file mode 100644 index 0000000..3e05bea --- /dev/null +++ b/docs/release-notes-v0.1.31-rc.1.md @@ -0,0 +1,115 @@ +# v0.1.31-rc.1 release notes + +Candidate documentation; no release or public tag is created by A6. Relative to +v0.1.30-rc.3, Stage A adds configuration-wide identity and interoperability. +Publication remains gated by the [readiness report](release-readiness-v0.1.31-rc.1.md). + +## Changes + +- Hierarchical record IDs (#84): `(domain << 16) | local`, with domains sorted + by canonical namespace and locals sorted by record name. Domain 0 and + `0xff00`–`0xffff`, local 0 and `0xffff` are reserved; no system records are + assigned. Import traversal no longer determines numeric identity. +- Authoritative configuration roots and `--generate` (#86): root plus complete + transitive imports determine IDs and identity. Multiple files of one namespace + emit one complete namespace output. Record roots still work, but compiling a + component independently defines a different configuration. +- Configuration identity (#91, #93, #106, #115): all five variants embed the + same full QBS schema_id and check generated dependency edges. Native C/C++ + checks happen at compilation, Python at import, Go through constants. +- Native generated-definition identity (#116, #118, #120–#123): format-1 gid, + injective identity stems, identity guards, dependency checks and C++ inline + namespaces isolate definitions differing in names, unused enums, validation + bodies or host storage even when wire schema_id is equal. This is not a + prebuilt-library ABI certificate or whole-program scan. +- C storage selection (#121): compact presence flags globally or for exact + canonical namespaces with `--c-optimize-size[=NS,...]`. Mixed policies are + supported with consistent expectations across generation invocations. +- QBS identity accessors (#124): C `quarry_qbs_schema_id()`, internal C++ + `ValidatedQbsView::schema_id()` and Python read-only schema identity properties. + Accessors read stored bytes without new hashing or mandatory initialization. + Public view layouts stay unchanged; reflective C string validation now checks + actual payload strings, and fuzz build include paths/QBS parser entry are corrected. +- `--describe` and exact release metadata (#125): deterministic configuration + summary, IDs, formats and epochs; exact matching HEAD release tag or `untagged` + reported separately from numeric Git-derived development version. +- Explicit `--name-prefix` isolation (#126): two truck configurations coexist + in C, C++ owning, C++/C storage, Python and Go. Prefixed C encoding preserves + case and escapes `q`/`_`; unprefixed generated source remains unchanged. +- Cross-language validation (#127): actual BRF streams exchanged across all 25 + producer/consumer pairs, generated and generic decoding, inspector checks, + nested cuts, negative controls, mutation detection and determinism. The baseline + passed 295 streams / 1,475 consumer checks without matrix skips, including + Linux GCC and a targeted Linux Clang 18 matrix. This does not resolve #85's + separate full generic conformance failure. +- Post-RC3 C generation moved to header bindings backed by the shared BRF v2 + codec (#77), with no schema-specific C object required. C/C-storage runtime + descriptors, presence operations and generated decode operations evolved through + epoch 7 (#79); these are source/runtime-contract changes, not a wire-format bump. +- Earlier post-RC3 maintenance includes Go bindings/runtime (#80), generated C + decode operations (#79), C++ include guards (#81), inline header definitions + (#97), strict warning fixes (#98), complete CMake import dependencies (#95), + Git-environment isolation (#96) and receipt-based pre-push validation (#114). + +## Compatibility and migration + +BRF remains version **2**, QBS **1**, Schema IR **1**, wire identity algorithm **1** +and native gid format **1**. Owning C++ epoch remains **3** and Python **1**. +C/C-storage is now **7**, up from C epoch **2** at the exact v0.1.30-rc.3 tag; +Go is newly available with epoch **1**. Upgrade generated C/C-storage and their +linked runtime together: older epoch-2 bindings are not current runtime-contract +consumers. A4.2/gid changes themselves do not alter the runtime call contract, +so no epoch bump accompanies their generated source/linkage changes. Equal epochs +are not native ABI compatibility guarantees. + +The hierarchical allocation **breaks RC3 record mappings** despite retaining BRF +v2: old flat IDs below `0x10000` do not match the current configuration's types. +Format-version equality alone never establishes that historical records decode. +There is no automatic discovery, translation or persistent manifest/rename state. + +1. Choose one authoritative root and preserve its full import closure. Record its + `--print-schema-id`, `--describe`, generator commit and runtime/toolchain. +2. Regenerate **all** dependent bindings from that root, even when generated in + separate invocations. Use consistent storage options and prefix policy; + discard stale build-owned outputs because generation does not delete them. +3. Update generated includes/names/guards as required. Include generated C++ + headers instead of forward-declaring types globally: actual types now live + in identity-scoped inline namespaces. Header guards/metadata names changed. + Prefixed C APIs use encoded stems such as `revq0a_truck_engine_`. +4. Rebuild affected native binaries/libraries and their consumers together. + Previously generated bindings generally require regeneration; equal schema_id, + gid, epochs or sizes do not authorize native casts or stale object reuse. +5. Keep configuration context with stored/transmitted BRF data and choose its + decoder explicitly. Retain historical readers or plan an application-owned + migration for historical data; do not feed RC3 data to new bindings blindly. +6. Run the installed-package/example tests and the five-language matrix. Use + `scripts/quarry-validate validate HEAD` and `scripts/quarry-validate push` with + hooks enabled before delivery. + +## Known limitations and release gates + +- [#85](https://github.com/ip332/quarry/issues/85): Linux Clang 18 generic + conformance failure remains a publication blocker by recorded maintainer decision. + Targeted A5 Clang success is separate evidence, not resolution. +- [#88](https://github.com/ip332/quarry/issues/88): Python packaging-module + detection can succeed spuriously. Still in the milestone with no deferral; + publication readiness requires resolution or an explicit maintainer disposition. +- [#89](https://github.com/ip332/quarry/issues/89): fixed by validated-commit + receipts and short pre-push checks (#114); no hook bypass is required. +- [#90](https://github.com/ip332/quarry/issues/90): explicitly deferred, + non-blocking declaration-order source churn after import reordering. Wire IDs, + schema_id and QBS remain stable; source-byte/gid invariance is not promised. +- [#119](https://github.com/ip332/quarry/issues/119): approved release exclusion: + same-TU coexistence of distinct namespaces whose unprefixed C symbols collide + is unsupported, including dot/underscore and uppercase-enum case collisions. + Prefixed-only injective naming is implemented; general C renaming is deferred. +- Dependency checks cover generated edges, not arbitrary prebuilt objects or + application inline functions. Go's older-metadata diagnostic can be a generic + `undefined:` error; Python/Go have no native gid mechanism; Go has no QBS runtime. +- Stage B descriptor/discovery/partial-image/classification/translation remains + future work. Schema IR and compiler/QBS C++ libraries remain internal; Python + and Go runtimes are separate packages. No hardware-execution certification is + implied by Cortex-M cross-builds. + +See the [normative identity contract](specifications/configuration-and-code-identity.md), +[CLI guide](stage-a-cli.md) and [consumer migration contract](generated-binding-compatibility.md). diff --git a/docs/release-readiness-v0.1.31-rc.1.md b/docs/release-readiness-v0.1.31-rc.1.md new file mode 100644 index 0000000..278791e --- /dev/null +++ b/docs/release-readiness-v0.1.31-rc.1.md @@ -0,0 +1,165 @@ +# v0.1.31-rc.1 Stage A release readiness + +This is an evidence map, **not publication approval**. Baseline: +`2a9aafdbc3edbe9eef8ea84efa02cad717b1c7b0` (A5 #127 merged; #103 closed). +[Post-merge CI](https://github.com/ip332/quarry/actions/runs/44964419771) +passed Build/test, coverage, clang-tidy, Cortex-M and benchmarks before A6 began. +Linux GCC: **72/72 CTests**, 244.12 s; coverage: **67/67**, 239.16 s. +The separate Clang 18 matrix passed in 9.714 s. These baseline measurements are +not claims about a later A6 revision. Exact A6 commit validation/CI is recorded in +its PR and commit-bound `quarry-validate` receipt, avoiding a self-referential SHA +in this file. + +“Covered” means a maintained test exists and baseline CI passed it, not exhaustive +proof over all inputs/toolchains. “Partial” explicitly identifies a missing dedicated +scenario. “Future” rows are mapped exclusions, never counted as Stage A passes. +Paths below are source-tree evidence relative to the repository root; CTest names +identify executable test registrations (one CTest may contain many assertions). + +## Implementation provenance + +| Delivery | Implementation | +|---|---| +| Post-RC3 C runtime | #77 shared codec / #79 generated operations, C epoch 2 at RC3 to current 7; Go introduced by #80 | +| A1/A2/A3 | #81 guards; #84 hierarchical allocation; #86 roots/selection; #95 complete CMake dependencies | +| A4.1 | #91 identity preparation; #93 shared layout; #115 explicit backend identity | +| A4.2 | #106 configuration dependency checks; #116 native gid; #118 injective identity stems; #120 plain-C gid | +| G3/G4/G5 | #121 per-namespace C storage; #122 validation; #123 compatibility contract | +| A4.3/A4.4/A4.5 | #124 stored QBS identity; #125 describe/tag metadata; #126 explicit prefixes | +| A5 | #127 five-language byte-exchange matrix | +| A6 | This documentation/consistency-test PR, Closes #104; no compiler/runtime behavior changes | + +## Design §13 coverage + +Source: [record identity design §13](design/record-identity-and-schema-discovery.md#13-test-matrix). +Each semicolon-separated subrequirement is accounted for below. + +| Requirement | Implementation/source | Maintained test / CI evidence | Status and boundary | +|---|---|---|---| +| Sorted namespace domains | #84 `compiler/layout/layout.cpp` | `layout_smoke_test`: DomainsAreSortedNamespacesAndLocalsAreSortedNames, OrderingIsBytewiseNotLocaleAware | Covered; bytewise canonical names | +| Reordered, transitive, diamond and duplicate imports | #84 frontend/layout | `yaml_compiler_test`: LoadsTransitiveDiamondOnceInDeterministicOrder; `hierarchical_record_id_test`: ImportOrderDoesNotAffectIdsOrSchemaId | Covered; no network/package resolution | +| Multi-file namespace | #86 output planning | `yaml_compiler_test`: AggregatesSourceUnitsOfOneNamespaceIntoOnePlannedOutput; `schema_compiler_tool_test`: MultiFileNamespaceIsGeneratedAsOneUnit | Covered; one primary record per file remains | +| Enum-only namespace gets no domain | #84 layout | `hierarchical_record_id_test` shared fixture includes unused enum namespace; root mapping assertions | Covered; enum metadata is not a record ID | +| Cycle rejection | frontend graph loader | `yaml_compiler_test`: RejectsImportCycleWithCycleDiagnostic | Covered | +| Domain/local limits and reserved values | #84 layout | `layout_smoke_test`: ApplicationDomainLimitIsEnforced, LocalRecordLimitIsEnforced, RootNamespaceIsTheFirstDomain | Covered allocator boundary; no system records assigned | +| Truck golden mapping | #84/#91 | `hierarchical_record_id_test`, `schema_description_test`, `interop_matrix`, `stage_a_documentation_test` | Covered all 8 IDs | +| Local name order independent of declarations/files | #84 layout | `layout_smoke_test`: AssignmentIsIndependentOfInputOrder; `schema_description_test` swaps declarations/files | Covered | +| Insertion before existing local shifts only its domain | #84 sorted allocator | source algorithm plus rev B MirrorFold in `name_prefix_test`/`public_examples_test` | Partial: sorted/permutation and append cases provide indirect coverage only; dedicated before/after insertion regression tracked in [#129](https://github.com/ip332/quarry/issues/129). Low residual coverage risk; recommend non-blocking follow-up, not an approved exclusion | +| Repeated generation byte identity | output planning/backends | `hierarchical_record_id_test`: RepeatedCompilationIsDeterministic; `interop_matrix` determinism | Covered for maintained fixtures/options | +| Import reorder preserves IDs/schema_id | #84/#91 | `hierarchical_record_id_test`, `schema_compiler_tool_test`, `interop_matrix` | Covered, also both QBS modes; source declaration byte order excluded (#90) | +| Selection preserves IDs/schema_id | #86/#91 | `schema_compiler_tool_test`: GenerationSelectionNeverChangesIdsOrQbs; `configuration_identity_test`; matrix | Covered, selected/full shared output bytes | +| Five-language encode/decode × all pairs | #127 `tests/interop/matrix/` | `interop_matrix`, Linux GCC and targeted Clang 18 job | Covered 25/25 cells, 295 streams, 1,475 positive consumer checks, no skips | +| Top-level, depth 1 and depth 2 | matrix shared model | all 8 truck records, Gear→Engine and Vehicle→Gear→Engine; record arrays extend to depth 4 | Covered populated/default models; companion fixture adds enums without altering truck root | +| Extracted nested records | C generic extraction + generated adapters | every actual child/array-element span compared with standalone bytes and decoded by all 5 consumers | Covered, own ID/type and bytes checked | +| Inspector with configuration image | existing inspector + #127 driver | C representative populated/default records in both modes; every producer's bytes identical | Covered representative values, not every possible record/value combination | +| Configuration mixing C/C++/C-storage/Python/Go | #106/#127 | `configuration_identity_test`, matrix dependency replacement with expected guard diagnostics | Covered all 5; import/build checks, no whole-program scan | +| RC3 IDs rejected | current generated decoders and inspector | matrix legacy controls for actual expected types and nested Timestamp; valid positive controls | Covered contextual mapping rejection, no universal numeric parser rule claimed | +| Identity excludes reflective names | #91 canonical QBS input | `qbs_model_test`: IdentityInputIgnoresReflectiveNames; native gid field/member rename checks | Covered; FQNs still identity inputs | +| Identity excludes comments/import paths | canonical model/preparation | `schema_compiler_tool_test`: PrintSchemaIdIgnoresSourcePathAndDiffersByResolvedConfiguration, ConfigurationMetadataDoesNotAffectSchemaIdentity | Partial: paths/metadata/reflection invariance provide indirect coverage only; comment-only mutation tracked in [#130](https://github.com/ip332/quarry/issues/130). Low residual coverage risk; recommend non-blocking follow-up, not an approved exclusion | +| Identity excludes compiler version | QBS identity builder | `qbs_model_test`: ConfigurationIdentityIgnoresCompilerVersion | Covered metadata strings; exhaustive real cross-release build comparison unavailable | +| Identity changes with IDs/wire definitions | QBS canonical input | QBS model/serializer tests; `configuration_identity_test` rev B same-ID/renumbered fixtures; matrix identity mutation | Covered representative changes; not exhaustive all wire changes | +| Describe golden | #125 CLI | `schema_description_test`, `tests/fixtures/description/truck.txt` | Covered locale, normalization, errors, epochs and header identity | +| Namespace generation complete | #86 output planning | MultiFileNamespaceIsGeneratedAsOneUnit; SeparatelyGeneratedNamespacesReproduceFullGeneration | Covered all backend output inventories | +| CMake root/selection and install/package consumers | #86/#95/#126 helper | `schema_compiler_package_test`, `schema_compiler_install_test`, `runtime_package_consumer_test`, `public_examples_test`, `name_prefix_cmake_test` | Covered installed compiler/public headers; compiler libraries remain internal | +| Stage B descriptor round trip and old-reader skipping | Future parser/extension work | no maintained implementation | Future; not a Stage A pass | +| Stage B paging, size limits, partial image identity | Future discovery | no maintained implementation | Future; no discovery API advertised | +| Stage B classifier: truck A/B and reorder | Future classification | no maintained implementation | Future; equality is not compatibility analysis | +| Stage B translator round trips | Future translation | no maintained implementation | Future; historical readers/migrations remain application-owned | + +## Configuration-identity §9 coverage + +Source: [configuration identity §9](design/configuration-identity.md#9-test-requirements). + +| Requirement | Implementation/source | Maintained test / evidence | Status and boundary | +|---|---|---|---| +| 1 Golden ID and invariance to compiler metadata, prefix, selection, name, QBS mode | #91/#125/#126 preparation | `configuration_identity_test`: SchemaIdIsPinnedAndIndependentOfSelectionNameAndQbsMode; QBS model compiler-version test; `name_prefix_test`; matrix | Covered named dimensions; actual cross-release comparison limited | +| 2 Every backend embeds full identity for every selection | #106 backends | EmbedsThePrintedSchemaIdForEverySelection; preparation tests; matrix full 128-bit comparisons | Covered five variants | +| 3 Wrong root dependencies fail; same-root separate invocations work | #106/#127 checks | RejectsDependenciesFromAnotherConfiguration; RejectsDependenciesThatPredateIdentity; separate-generation tests; matrix | Covered all 5; Go older metadata may report `undefined:` | +| 4 Wrong include order | #106 native checks | `configuration_identity_test`: RejectsIncludePathMixing, parameterized native variants | Covered generated dependency edges | +| 5 C++ owning/C/C-storage separate-TU configurations | #106 + #111 isolation | CppConfigurationsWithDifferentLayoutsLinkTogether; CConfigurationsWithDifferentLayoutsLinkTogether; CppCStorageConfigurationsWithDifferentLayoutsLinkTogether; G4 O0/O2/link-order runtime cases | Covered measured ABIs only; application inline functions still caller-owned | +| 5 Go import paths / Python prefixed same process | #106/#126 | GoConfigurationsCoexistUnderDistinctImportPaths; `name_prefix_test`; truck `public_examples_test` | Covered; no runtime schema negotiation | +| 6 Prefix isolation, same QBS/IDs, files/guards/modules | #126 | `name_prefix_test`, `name_prefix_cmake_test`, matrix prefixed-byte controls and A/B example | Covered; unprefixed C #119 exclusion persists | +| 7 Stored C/C++/Python identity, invalid args, no hashing/mandatory allocation | #124 `runtime_c/schema_id.c`, `compiler/qbs/parser.hpp`, Python generic | `generic_c_runtime_test`, `qbs_parser_test`, Python conformance, installed C99 consumer, cross-language identity test | Covered minimal/reflective and unchanged layouts; no universal fabricated-view validation | +| 8 Describe/print golden and QBS matching | #125 | `schema_description_test`, CLI and preparation tests, `stage_a_documentation_test` | Covered complete 128 bits, both modes | +| 9 Zero mandatory footprint / explicit accessor cost separately | #106/#124 CI Cortex-M | `.github/workflows/ci.yml`, `cortex_m/scripts/report_footprint.py`, smoke + identity targets, G4 embedded report | Covered cross-build/link evidence; base comparison runs on PR events, not baseline push; no hardware execution claim | +| 10 CMake NAME_PREFIX/SCHEMA_ID_VARIABLE, differing roots | #126 `cmake/QuarryGenerate.cmake` | `name_prefix_cmake_test`, truck A/B native example via `public_examples_test` | Covered configure-time identities and shared output directory | + +Native gid adds the G4 matrix documented in +[generated-code identity validation](generated-code-identity-validation.md): C++ owning, +C++/C storage, C99, plain C headers consumed as C++20 and mixed TUs; actual runtime +behavior, both link orders, strict warnings, optional sanitizer and GCC LTO `-Wodr` +secondary evidence. It does not replace wire identity tests. Python/Go native gid +is N/A (not a skipped producer/consumer cell). + +## Issue #104 scope and acceptance coverage + +| Scope / acceptance criterion | Artifact and validation | Status / limitation | +|---|---|---| +| BRF allocation/ranges, QBS identity/accessors, generated constants/guards/dependencies/epochs | Updated BRF/QBS/compiler specs plus [identity specification](specifications/configuration-and-code-identity.md); source constants and maintained tests above | Documented; no algorithm/epoch change | +| Schema identity, layout, compiler passes/configuration preparation | Updated `design/schema-identity.md`, `layout-algorithm.md`, `compiler-passes.md`, `compiler-architecture.md` | Stale persistent state/import-free claims corrected to merged behavior | +| Manifest superseded | `specifications/manifest-format.md` status and cross references | Historical proposal retained, not available compiler mode | +| Versioning and A4.2 epoch rationale | `versioning.md`; version resolution tests; description/header checks | 3/7/1/1, BRF2/QBS1/IR1, exact tag separate from numeric version | +| Tools, compiler/runtime/backend/example and installed-package docs | Updated READMEs/distribution docs; [literal CLI guide](stage-a-cli.md) | Executable CLI/diagnostic checks plus installed consumer/example tests | +| Stage A implemented / Stage B future | Both design status lines, architecture boundary and specs | A1–A5 merged; A6 documentation delivered here, publication not authorized | +| Release notes: breaks, migration, compatibility, known issues | [Release notes](release-notes-v0.1.31-rc.1.md) | Requires regeneration/rebuild; does not promise RC3 BRF readability | +| Complete readiness map / open issue disposition | Every §13 area/subrequirement and §9 numbered item above; issue table below | Explicit partial/future rows retained, never counted as full coverage | +| Acceptance 1: scope updated and reviewed | This focused PR for independent review | Implementation complete; independent review pending | +| Acceptance 2: merged behavior checked | `stage_a_documentation_test`, existing `schema_description_test`, `consumer_documentation_test`, full native/Linux suites | Baseline CLI checked directly; A6 exact-revision results in PR/receipt | +| Acceptance 3: release notes and no unmapped requirements | This report and release notes | Covered, including explicit gaps | +| Acceptance 4: every doc link resolves | `stage_a_documentation_test` scans tracked Markdown paths and local heading fragments | Relative links checked; external services/network uptime not certified | + +## Authoritative truck mapping + +Root `examples/truck/schemas/configuration.brd`, identity +`9200ca494f010801b830d0857cf66dde`: + +| Record | ID | +|---|---| +| truck.VehicleSnapshot | 0x00010001 | +| truck.brakes.AbsEvent | 0x00020001 | +| truck.brakes.BrakeStatus | 0x00020002 | +| truck.cms.CameraHealth | 0x00030001 | +| truck.common.Timestamp | 0x00040001 | +| truck.engine.EngineStatus | 0x00050001 | +| truck.engine.FaultCode | 0x00050002 | +| truck.transmission.GearState | 0x00060001 | + +Revision B adds `truck.cms.MirrorFold` = `0x00030002`, retaining EngineStatus's ID +and bytes but changing full identity to `806e9a4e11d0df71c4e5b51045f85010`. +`public_examples_test` runs the existing installed-package/wheel A/B application +in all five variants. The A5 matrix adds prefixed/unprefixed byte comparisons. + +## Coverage-gap risk assessment + +The completion audit found no maintained test equivalent to either exact +metamorphic regression below. Existing tests reduce risk but do not close these +gaps; neither row is counted as fully covered. Duplicate searches reviewed all +issue titles and searched issue bodies before creating the focused follow-ups. + +| Gap / follow-up | Existing protection and remaining exposure | Risk / publication recommendation | +|---|---|---| +| [#129: insertion before existing locals](https://github.com/ip332/quarry/issues/129) | `layout_smoke_test` pins sorted domains/locals, permutation invariance and bytewise ordering. The A/B example appends MirrorFold. None directly compares insertion before existing locals while keeping the namespace set fixed, including unaffected IDs in another domain. | Low residual coverage risk because the allocator sorts each domain independently (`compiler/layout/layout.cpp`), backed by golden mappings and interoperability tests. A regression could have serious record-mapping impact. No current defect was found. Recommend a non-blocking focused test follow-up, subject to maintainer review. | +| [#130: comment-only identity mutation](https://github.com/ip332/quarry/issues/130) | QBS/CLI tests cover names, compiler metadata, paths, configuration names, selection and QBS modes. None directly edits only YAML comments and compares full identity plus both QBS images. | Low residual coverage risk: hashing consumes canonical resolved wire definitions, not raw source. A regression could cause spurious identity churn and configuration-guard failures; no unsafe decoding or current defect was demonstrated. Recommend a non-blocking focused test follow-up, subject to maintainer review. | + +These are recommendations for newly tracked coverage gaps, not maintainer-approved +release exclusions. They do not resolve or defer #85/#88, change #90's recorded +disposition, or broaden #119's approved exclusion. The follow-ups request tests +using existing helpers, not compiler/runtime functionality or identity redesign. + +## Outstanding issues and release decision + +| Issue | Disposition | Supporting evidence / remaining gate | +|---|---|---| +| [#85](https://github.com/ip332/quarry/issues/85) | **Publication blocker** | Open milestone bug; maintainer's 2026-11-17 comment requires investigation/resolution before #105. Linux Clang18 full generic presence assertion remains unresolved. A5 targeted Clang18 matrix passes, does not close it. | +| [#88](https://github.com/ip332/quarry/issues/88) | **Unresolved publication gate** | Open milestone bug, no approved deferral. `import build` can resolve a local namespace directory. Current CI has real dependencies and passes, which does not fix detection. Resolve or obtain explicit disposition before #105; A6 does not change build behavior. | +| [#89](https://github.com/ip332/quarry/issues/89) | **Fixed** | Closed; #114 commit receipts, `quarry_validate_test`, documented hooked pushes. Validation completes before SSH connection; no bypass needed. | +| [#90](https://github.com/ip332/quarry/issues/90) | **Explicitly deferred / non-blocking** | Maintainer's 2026-11-17 backlog comment; declaration order may change source/gid after import reorder. IDs/schema_id/QBS remain invariant. | +| [#119](https://github.com/ip332/quarry/issues/119) | **Approved exclusion / deferred** | Maintainer's recorded RC disposition: same-TU distinct namespaces with colliding unprefixed C symbols unsupported. #126 implements prefixed-only injective names, not general renaming. | +| [#104](https://github.com/ip332/quarry/issues/104) | **Independent review pending** | This documentation PR; no automatic merge. | +| [#105](https://github.com/ip332/quarry/issues/105) | **Not started** | Final release validation/publication remains separate; no tag or release created here. | + +No other issue disposition is changed by this report. The experimental +`explore/fqn-hash-record-ids` branch remains outside main; its rejected hash +allocation algorithm is not used. Native compiler/ABI permutations, actual +cross-release generator comparisons and board/RTOS execution are not exhaustive. +The candidate is ready for **A6 review**, not release publication. diff --git a/docs/schema-compiler-tool-distribution.md b/docs/schema-compiler-tool-distribution.md index 215c61b..3fdf9fa 100644 --- a/docs/schema-compiler-tool-distribution.md +++ b/docs/schema-compiler-tool-distribution.md @@ -20,30 +20,16 @@ explicit host compiler override for cross-compiling builds. ## Current CLI Contract -The build-tree command is: - -```text -quarry-schema-compiler [options] INPUT - -Options: - -o, --output-directory PATH Directory for generated files (default: generated) - --root-file-stem NAME Root namespace file stem (default: schema) - --file-extension EXT Generated file extension (default: .generated.hpp) - --list-outputs Print generated output paths without writing files - --emit-qbs PATH Emit the resolved schema as a deterministic QBS image - --qbs-reflective Include reflective record, field, and enum type names in QBS - --print-generated-code-api-version - Print the generated-code API compatibility version and exit - --version Show version information - -h, --help Show help -``` +The installed/build-tree CLI contract and verified flag examples are maintained +in [Tools](../tools/README.md#quarry-schema-compiler) and the +[Stage A CLI guide](stage-a-cli.md). `--help` is checked against the Tools excerpt. +Supported variants are C99, C++ owning, C++/C storage, Python and Go. Current behavior: * accepts exactly one YAML `.brd` input file -* supports one YAML document and the current single-schema-unit frontend - boundary -* writes generated C++ files into one output directory +* loads one YAML document per source unit across the complete relative-import closure +* writes selected namespaces for the requested backend into one output directory * defaults to `generated` for the output directory * defaults to `schema` for the root file stem * defaults to `.generated.hpp` for generated file extensions @@ -614,10 +600,10 @@ quarry-schema-compiler --print-generated-code-api-version ``` Successful output should be exactly one base-10 unsigned integer followed by a -newline, for example: +newline; the current C++ owning query returns: ```text -1 +3 ``` The query: @@ -927,3 +913,13 @@ identities for roots without a dependency edge; these checks stay optional. The installed module retains its `3.20...3.31` policy pin. Both configure mode and the inventory/query script path are tested with CMake 3.x; the public generation function itself requires configure mode because it creates build rules. + +## Stage A configuration metadata + +`--print-schema-id` and `--describe` query the complete root; `--generate` changes +emission only. `--list-inputs` enumerates resolved input dependencies. The installed +C++ helper supports `GENERATE`, `NAME_PREFIX` and `SCHEMA_ID_VARIABLE`; source naming +never changes wire IDs or schema_id. Full-query metadata and exact release tags +are [documented separately](versioning.md). No Stage B discovery or translation +API is installed. Existing install/package/example tests remain the verification +boundary; see [release readiness](release-readiness-v0.1.31-rc.1.md). diff --git a/docs/specifications/README.md b/docs/specifications/README.md index 7843f63..dc6ec64 100644 --- a/docs/specifications/README.md +++ b/docs/specifications/README.md @@ -30,21 +30,14 @@ Markdown specifications SHALL use the shared structure defined in # Required Sections -Every specification SHALL include these sections: - -* Status -* Version -* Purpose -* Scope -* Terminology -* Requirements -* Validation Rules -* Compatibility Rules -* Examples -* Open Questions - -Specifications MAY add additional sections when needed, but the required -sections SHOULD remain in the template order. +Follow [the authoring guide](spec-authoring-guide.md): Purpose, Scope, +Terminology, numbered Requirements, Examples and Related Documents. Add optional +sections only where useful; existing historical specifications are being reconciled +incrementally rather than creating empty sections. + +The implemented Stage A [configuration and generated-code identity contract](configuration-and-code-identity.md) +complements BRF allocation and QBS wire identity. The [manifest proposal](manifest-format.md) +is superseded, not an available persistent-ID mode. --- diff --git a/docs/specifications/binary-record-format.md b/docs/specifications/binary-record-format.md index 31b610b..d960dcc 100644 --- a/docs/specifications/binary-record-format.md +++ b/docs/specifications/binary-record-format.md @@ -6,19 +6,30 @@ Draft ## Version -BRF v1 (the current v0.1 format) and BRF v2 (draft). +BRF v2 is generated by current bindings. BRF v1 material below is historical +primitive-format documentation, not the current generator contract. ## Purpose This document defines the binary representation of Quarry records and -field payloads for BRF v1 and the proposed BRF v2 layout. +field payloads for historical BRF v1 and implemented BRF v2. The binary record format defines how record headers, field directories, payloads, nested records, scalar values, arrays, strings, bytes, and enum values are encoded. This document does not define schema syntax, transport protocols, application -semantics, cloud APIs, or the future QBS representation. +semantics, cloud APIs, or the separately specified QBS representation. + +## Scope + +BRF physical layouts, value encoding and validation, plus current configuration-local +ID allocation. Transport/discovery, persistent evolution policy and native ABI are +outside this specification. + +## Terminology + +The following format and identity terms are independent. ## Format Versions and Identities @@ -36,17 +47,13 @@ schema_id The identity of an exact schema definition and version. ``` -`record_id` SHALL mean only the logical identity of the record or message type. -It SHALL NOT identify a BRF physical format version, an exact schema revision, -an exact physical layout, a schema hash, or a schema evolution version. A -logical record MAY retain the same `record_id` across BRF v1 and BRF v2, -compatible schema evolution, and changes to a future exact `schema_id`. A new -`record_id` is required only when the logical record or message identity itself -changes such that it is treated as a different logical record type. - -A future `schema_id` MAY be carried by an outer protocol, a schema registry, -QBS, or a future header extension; BRF v2 does not define the schema identity -mechanism. +The FQN is the logical record identity; `record_id` is its compact identifier +within a configuration. It is not a global registry key or a physical-format +version. Sorted allocation may change IDs when configuration membership changes, +even for an otherwise unchanged record. Equal BRF format versions do not imply +historical-record compatibility. QBS `schema_id` identifies the complete wire +configuration and is not carried by the BRF v2 header. Applications provide +configuration context explicitly; discovery remains future Stage B work. The first header byte is the BRF format discriminator in both versions: @@ -59,7 +66,7 @@ MUST NOT be confused. --- -## BRF v1 (Current v0.1 Format) +## BRF v1 (Historical Format) ## Record Layout @@ -129,17 +136,11 @@ A `recordId` is the compiler-generated binary identifier of the logical record or message type. It is not a schema-version, schema-hash, physical-layout, or BRF-format identifier. -A logical record MAY retain the same `recordId` through compatible schema -evolution and across BRF format versions. A physical BRF layout change SHALL -be identified by `brf_format_version` and MUST NOT require a new `recordId` -solely because the physical format changed. - -A new `recordId` is required only when the logical record or message identity -changes such that it is treated as a different logical record type. - -Backward compatibility is provided by schema evolution rules, the selected BRF -format version, and generated readers. `record_id` is not a physical format -version field. +Physical format version and configuration-local IDs are independent. Current +Stage A allocation is specified below; adding a domain or inserting a record +can renumber IDs. +Generated decoders require their expected type ID and layout. Regenerate all +bindings and rebuild affected consumers after allocation changes. Older readers MAY read the fields they know and ignore unknown Field Directory entries and their referenced payload bytes when compatibility rules allow. @@ -150,10 +151,17 @@ work. ## recordId Structure and Reserved Ranges -This section is part of the protocol contract. It applies to BRF v1 and BRF v2 -alike; the header field remains an unsigned 32-bit big-endian integer. +The BRF v1 and BRF v2 physical headers represent `recordId` as an unsigned +32-bit big-endian integer. That field representation does not prescribe how IDs +are allocated. -A `recordId` is hierarchical: +The hierarchical mapping and reserved ranges below describe the **current Stage A +compiler's BRF v2 generation contract**. They do not specify historical BRF v1 +allocation or guarantee that older generated bindings used this algorithm. The +historical BRF v1 physical layout above remains unchanged; its allocation policy +is not defined here. + +A `recordId` allocated by the current Stage A compiler is hierarchical: ```text recordId = (domain_id << 16) | local_record_id @@ -166,15 +174,15 @@ Reserved and assigned ranges: | Range | Meaning | | --- | --- | -| `domain_id = 0x0000` | Reserved. No valid `recordId` has domain 0, so `recordId = 0` and every value below `0x00010000` is invalid. | +| `domain_id = 0x0000` | Reserved by current Stage A allocation; it assigns neither `recordId = 0` nor any value below `0x00010000`. | | `domain_id = 0x0001`–`0xFEFF` | Application domains (65,279), assigned by the schema compiler. | | `domain_id = 0xFF00`–`0xFFFF` | Quarry system domains (256). Reserved for Quarry-defined records; each is assigned an explicit constant by this specification when defined. None is defined yet. | | `local_record_id = 0x0000` | Reserved. | | `local_record_id = 0x0001`–`0xFFFE` | Application records (65,534 per domain). | | `local_record_id = 0xFFFF` | Reserved. | -The schema compiler assigns application IDs from one complete compilation root -(the root schema and its complete import closure, called the configuration): +The current Stage A compiler assigns application IDs from one complete +compilation root (the root schema and its complete import closure, called the configuration): 1. A record domain is a canonical namespace, not a source file. Several source files MAY contribute records to one namespace; they share its domain. Every @@ -1120,9 +1128,8 @@ BRF v1 and BRF v2 are distinct physical formats selected by `brf_format_version`. A v1 decoder MUST NOT interpret a v2 record as v1, and a v2 decoder MUST NOT interpret a v1 record as v2. -Changing from BRF v1 to BRF v2 does not, by itself, change `record_id`. -`record_id` changes only when the logical record or message identity itself -changes such that it is treated as a different logical record type. +A physical-version change does not itself define an allocation policy. The +current hierarchical mapping replaces RC3 flat IDs, despite retaining BRF v2. An exact schema change MAY change `schema_id` while retaining `record_id`. The schema identity mechanism and schema compatibility rules are outside this @@ -1137,7 +1144,7 @@ not by itself require a new logical `record_id`. The following are intentionally outside the first v2 implementation contract: * the transport or container location of an exact `schema_id`; -* a schema hash algorithm and schema identity registry; +* a schema identity registry (QBS algorithm 1 is already implemented); * public packed-field syntax; * the complete bit-spanning encoding rules for future packed fields; * whether a smaller BRF16 profile is justified by measurements; @@ -1147,3 +1154,40 @@ The following are intentionally outside the first v2 implementation contract: None of these questions changes the v2 fixed-region, 8-byte descriptor, record-relative-offset, or independent-identity decisions in this draft. + +## Requirements + +### Stage A allocation requirements + +These requirements apply to current Stage A BRF v2 generation, not historical +BRF v1 allocation or older generated bindings. + +REQ-BRF-001: Application IDs SHALL be `(domain_id << 16) | local_record_id`, +using the complete configuration. Domains SHALL be record-declaring canonical +namespaces, sorted bytewise by FQN from 1; enum-only namespaces SHALL get no domain. +Locals SHALL be records sorted bytewise by local name from 1. Duplicate imports, +file boundaries, selection and traversal order SHALL NOT affect this mapping. + +REQ-BRF-002: The allocator SHALL reserve domain 0 and `0xff00`–`0xffff`, and local +0 and `0xffff`; exceeding 65,279 application domains or 65,534 locals SHALL fail +(`BC7004` / `BC7005`). No system records are assigned by this specification yet. + +REQ-BRF-003: Nested records and record-array elements SHALL carry their own +assigned IDs. Generated decoders SHALL reject a header ID different from the +expected type in its configuration. Legacy-ID tests SHALL include valid positive +controls; this is not a requirement for every generic parser to reject every +number below `0x10000` independently of expected schema context. + +## Related Documents + +- [Configuration and generated identity](configuration-and-code-identity.md) +- [Layout allocation](../layout-algorithm.md) +- [QBS](quarry-binary-schema.md) + +## Examples + +In the authoritative truck configuration, EngineStatus is domain 5/local 1 +(`0x00050001`) and its nested Timestamp is domain 4/local 1 (`0x00040001`). +The nested header carries Timestamp's own ID. Revision B adds MirrorFold local 2 +in domain 3 without changing EngineStatus's numeric ID; the configuration identity +still changes. These examples do not define a cross-configuration compatibility rule. diff --git a/docs/specifications/configuration-and-code-identity.md b/docs/specifications/configuration-and-code-identity.md new file mode 100644 index 0000000..11ceb03 --- /dev/null +++ b/docs/specifications/configuration-and-code-identity.md @@ -0,0 +1,168 @@ +# Configuration and Generated-Code Identity + +## Purpose + +Define Stage A identity, generation and compatibility contracts independently of +release numbering. Status: implemented for the v0.1.31-rc.1 candidate; formats and +epochs below describe the merged Stage A implementation. + +## Scope + +Configuration roots, QBS identity, generated dependency checks, C/C++ generated +identity format 1 and runtime epochs. Descriptor discovery, partial images, +translation and compatibility classification remain future Stage B work. + +## Terminology + +- Configuration: one root and its complete transitive import closure. +- `record_id`: the configuration-local hierarchical BRF type identifier. +- `schema_id`: algorithm plus 128-bit canonical wire configuration identity. +- `gid`: per-namespace, per-native-variant generated-definition identity. +- Epoch: generated-code/runtime API contract, independent of either identity. +- `lp(x)`: unsigned big-endian u32 byte length followed by exactly those bytes. + +## Requirements + +### Configuration and selection + +REQ-ID-001: The compiler SHALL resolve the complete root import closure before +assigning IDs or computing configuration identity. A configuration document +SHALL contain only `configuration` and `imports`, declare no domain, and SHALL +NOT be imported. A record root remains valid but defines its own configuration. + +REQ-ID-002: A configuration root without `--generate` SHALL emit every planned +namespace; a record root SHALL emit its own namespace by default. Explicit +selection SHALL affect emission only. Every selected namespace SHALL include all +its declarations, including contributions from multiple files. Unknown selections +SHALL fail before writing output. Separate invocations from one root with the +same effective options SHALL agree on shared outputs. + +REQ-ID-003: Configuration identity SHALL use QBS algorithm 1, SHA-256 truncated +to the first 16 bytes of the existing canonical QBS identity input. The input +SHALL include all record IDs, record/used-enum FQNs and wire definitions, including +nested references. Field names, enum member names, unused enums, comments, paths, +configuration labels, compiler/release metadata, selection, naming prefixes and +C host-storage policy SHALL NOT contribute. The exact canonical wire input is +specified by [QBS](quarry-binary-schema.md#schema_id). + +REQ-ID-004: Every generated backend SHALL embed the full configuration identity, +not a selected subset identity. Each generated dependency edge SHALL check the +expected algorithm and full value: C/C++ at compile time, Python at import time, +Go through compile-time constant checks. Missing older metadata SHALL fail +visibly. Independent generated sets without a dependency edge SHALL NOT imply a +whole-program compatibility check. + +### Generated-definition identity format 1 + +REQ-ID-005: C (variant 1), C++ owning (2), and C++/C-storage (3) SHALL compute a +separate `gid` as SHA-256 truncated to its first 16 bytes over this encoding: + +```text +ASCII "QUARRY-GENERATED-CODE-ID" followed by 0x00 +u8 format=1; u8 variant; u8 schema_id_algorithm; 16 schema_id bytes +lp(canonical namespace FQN) +u32 file_count + for each file in role order: u8 role (1 header, 2 source); lp(normalized content) +u32 direct_dependency_count + for each direct dependency in bytewise FQN order: + lp(canonical FQN); u8 variant; u8 gid_format; 16 gid bytes +``` + +All multibyte integers are big-endian. File roles and dependency FQNs are unique; +self-dependencies and malformed placeholders are rejected. This is the existing +format, not a new identity algorithm. + +REQ-ID-006: Normalized content SHALL be emitted by the renderer using typed +placeholders, without post-render text replacement to discover tokens: + +| Bytes between `0x1e` and `0x1f` | Meaning | +|---|---| +| `S` plus `h`, `H`, `b`, or `0`–`3` | Own gid: lowercase/uppercase hex, byte list, or one word literal | +| `P` plus canonical namespace FQN | Generated include/output path for that namespace | +| `M` plus canonical namespace FQN | Encoded identity macro stem | + +REQ-ID-007: Identity computation SHALL cover all namespaces in dependency order, +including unselected dependencies and their effective storage policies. Final +rendering SHALL agree with normalized content before placeholder substitution. +Changing emitted definitions, dependency identities or variant SHALL re-identify +the affected namespace and dependents. Compiler version strings and output path, +extension or root-stem options alone SHALL NOT re-identify normalized definitions. +`--name-prefix` MAY change gid because it changes emitted public definitions. + +REQ-ID-008: Native generated dependency edges SHALL check gid metadata presence, +format and all four 32-bit words after configuration checks. Guards SHALL include +the gid; conflicting definitions of the same namespace/variant in one translation +unit SHALL fail explicitly. Identical copies MAY deduplicate. C++ definitions +SHALL use `quarry_gen_<32 lowercase hex digits>` inline linkage namespaces, +including plain-C headers consumed as C++20 and the C-shaped storage layer. + +REQ-ID-009: Generated metadata SHALL expose these existing names: + +| Variant | Metadata | +|---|---| +| C++ owning | `kQuarrySchemaIdAlgorithm`, `kQuarrySchemaId`, `kQuarryGeneratedCodeIdFormat`, `kQuarryGeneratedCodeId`; `QUARRY_GENERATED_CPP_NS__SCHEMA_ID_*` / `CODE_ID_*` | +| C | `QUARRY_NS__SCHEMA_ID_{ALGORITHM,W0,W1,W2,W3}`, `quarry_ns__schema_id()`; `QUARRY_GENERATED_C_NS__CODE_ID_{FORMAT,W0,W1,W2,W3}` | +| C++/C storage | `QUARRY_NS__SCHEMA_ID_*`, `quarry_ns__schema_id()` and `QUARRY_GENERATED_CPP_C_NS__CODE_ID_*` | +| Python | `QUARRY_SCHEMA_ID_ALGORITHM`, `QUARRY_SCHEMA_ID` | +| Go | `QuarrySchemaIDAlgorithm`, `QuarrySchemaID()`, `QuarrySchemaIDHi`, `QuarrySchemaIDLo` | + +The detailed guard/constant spellings and reserved-name diagnostics are recorded +in [the generated-code contract](../design/configuration-identity.md#16-generated-code-identity-in-c-and-c-bindings-111-g1g5). +Python and Go do not expose the native per-namespace gid mechanism. + +REQ-ID-010: Namespace identity stems SHALL preserve case, escape `q` as `qq` and +`_` as `q0` within segments, join segments with `_`, and use `0` for the unnamed +namespace. With an explicit prefix it SHALL be the leading encoded segment. +Generated identity names SHALL be checked against schema-derived identifiers; +Python SHALL apply its established reserved-module-name renaming policy and +reject resulting duplicates. Unprefixed C public symbol spellings remain legacy +and are not made injective by this identity encoding (issue #119). + +### Accessors and compatibility + +REQ-ID-011: Accessors SHALL return the stored QBS identity without new hashing, +initialization or mandatory allocation. C `quarry_qbs_schema_id()` SHALL require an +already parsed view with unchanged live backing bytes, clear non-null output on +failure, return `QUARRY_GENERIC_INVALID_ARGUMENT` for null arguments/backing or +fewer than 40 bytes, and `QUARRY_GENERIC_MALFORMED_QBS` for unsupported algorithm +or length metadata. These checks SHALL NOT be treated as validation of a fabricated +view or cryptographic verification. C++ `ValidatedQbsView::schema_id()` SHALL read +validated/cached metadata (a default view returns zeros). Python `QbsSchema.schema_id` +and `.schema_id_algorithm` SHALL be read-only; headerless hand-built metadata +SHALL raise `QbsError`. Python may return a small bytes value. C++ QBS views remain +compiler-owned tooling, not an installed standalone C++ QBS SDK. + +REQ-ID-012: Current epochs SHALL remain C++ owning 3, C/C-storage 7, Python 1, +Go 1. BRF 2, QBS 1, Schema IR 1, schema identity algorithm 1 and gid format 1 +SHALL remain separate version contracts. Equal epochs/identities SHALL NOT be +interpreted as native ABI compatibility or authentication. A4.2 and gid changes +preserve epochs because they do not change the generated-code/runtime call +contract; consumers still regenerate and rebuild for changed generated linkage, +guards, types or layouts. Existing global C++ forward declarations are insufficient +for identity-scoped types; include the generated header. + +## Examples + +The authoritative truck root has schema_id +`9200ca494f010801b830d0857cf66dde`; EngineStatus is `0x00050001`. +Revision B adds MirrorFold `0x00030002`, keeping EngineStatus's numeric ID but +changing configuration identity to `806e9a4e11d0df71c4e5b51045f85010`. +`--name-prefix rev_a` yields `rev_a::truck::engine` in owning C++ and +`revq0a_truck_engine_EngineStatus_t` in C. This does not change wire IDs or QBS. + +## Validation + +Pinned encoding vectors live in `tests/support/generated_code_identity_test.cpp`. +The [readiness matrix](../release-readiness-v0.1.31-rc.1.md) maps allocation, +identity, ODR, packaging and all 25 language exchanges to maintained tests. +Identical inputs/options are reproducible; import reordering preserves wire IDs, +schema_id and QBS, but declaration-order source-byte invariance remains #90. + +## Related Documents + +- [BRF](binary-record-format.md) +- [QBS](quarry-binary-schema.md) +- [Compiler](schema-compiler.md) +- [Consumer compatibility and migration](../generated-binding-compatibility.md) +- [Version and release-tag metadata](../versioning.md) +- [CLI contracts](../../tools/README.md) diff --git a/docs/specifications/manifest-format.md b/docs/specifications/manifest-format.md index 3fd2728..9046a0b 100644 --- a/docs/specifications/manifest-format.md +++ b/docs/specifications/manifest-format.md @@ -2,7 +2,16 @@ ## Status -Draft +**Superseded; historical proposal, not an implemented format.** + +Stage A assigns IDs deterministically from the complete configuration without +persistent allocation state. There is no manifest reader/writer, rename mapping +or supported identifier-preservation mode. QBS is the implemented runtime schema +image; Schema IR remains compiler-owned. The historical proposal below is +non-normative and MUST NOT be read as an available compiler contract. +See [the accepted design](../design/record-identity-and-schema-discovery.md#11-compatibility-and-format-impact), +[BRF allocation](binary-record-format.md#recordid-structure-and-reserved-ranges) +and [QBS](quarry-binary-schema.md). ## Version diff --git a/docs/specifications/quarry-binary-schema.md b/docs/specifications/quarry-binary-schema.md index ffd9361..b054d74 100644 --- a/docs/specifications/quarry-binary-schema.md +++ b/docs/specifications/quarry-binary-schema.md @@ -2,18 +2,19 @@ ## Status -Draft design specification. No QBS encoder, decoder, runtime, or exchange -protocol is implemented by this document. +Implemented QBS v1 container and identity contract. Compiler serialization, +C/Python generic runtimes and internal C++ QBS tooling exist. Schema exchange, +discovery and descriptor extensions remain future Stage B work. ## Version -QBS format version 1 (proposed). +QBS format version 1. ## Purpose QBS is a compact, architecture-independent runtime serialization of Quarry's canonical semantic schema and BRF v2 layout metadata. It is intended to let a -future runtime understand a BRF v2 record without recompiling the source schema +generic runtime understand a BRF v2 record without recompiling the source schema or importing compiler-only Schema IR. QBS is declarative metadata. It is not executable bytecode, a virtual machine, @@ -957,3 +958,24 @@ later stable record-ID allocation, schema exchange, and protocol evolution The QBS backend SHALL consume the existing canonical BRF Layout IR. It SHALL not introduce a second offset, width, nesting, or fixed/variable calculation path. + +## Stage A configuration identity access + +REQ-QBS-021: Minimal and reflective images of one configuration SHALL contain the +same algorithm-1 configuration identity at header bytes 12–27. Emission selection +and source naming prefixes SHALL NOT change either image's wire bytes. + +REQ-QBS-022: Runtime identity accessors SHALL read stored identity metadata rather +than recompute schema identity. The C accessor's argument/error contract, C++ +validated-view accessor and Python read-only properties SHALL follow +[REQ-ID-011](configuration-and-code-identity.md#accessors-and-compatibility). +An accessor SHALL NOT imply digest verification beyond its parser's contract. + +REQ-QBS-023: QBS schema_id SHALL remain distinct from native generated-code gid. +Generated identity SHALL NOT be introduced into BRF or QBS wire metadata. + +C uses the installed `quarry/runtime_c/generic_brf.h` and links `Quarry::runtime_c`. +C++ `ValidatedQbsView` remains compiler-owned tooling; Python uses `quarry.load_qbs()`. +Go has generated identity constants but no QBS runtime. Existing public view +layouts and runtime epochs are unchanged by accessors. Reflective C parsing +validates individual string payloads, not the binary offset table as UTF-8. diff --git a/docs/specifications/schema-compiler.md b/docs/specifications/schema-compiler.md index 1cffe8f..79ac780 100644 --- a/docs/specifications/schema-compiler.md +++ b/docs/specifications/schema-compiler.md @@ -2,7 +2,9 @@ ## Status -Draft +Implemented Stage A responsibilities, with historical future compatibility +requirements explicitly identified below. No manifest, profile-selection or +historical schema-comparison mode is implemented. ## Version @@ -21,6 +23,20 @@ responsibilities and architecture only. --- +## Scope + +Production YAML configuration compilation, namespace output selection and the +existing generation/identity contracts. Legacy declaration syntax is parser-test +compatibility infrastructure. Stage B discovery and historical schema evolution +are not available production modes. + +## Terminology + +A root is the one CLI input; its complete relative-import closure is the +configuration. A namespace is the generation unit; a domain is a namespace that +declares records. Wire schema_id, native gid and runtime epochs are defined in +[the identity contract](configuration-and-code-identity.md). + ## Requirements ### REQ-SC-001 @@ -29,9 +45,9 @@ The Schema Compiler SHALL parse schema files. ### REQ-SC-002 -The Schema Compiler SHALL accept legacy import declarations as syntax only and -SHALL NOT require an import-resolution stage to compile the current supported -schema pipeline. +The production YAML compiler SHALL load the root and its complete transitive +relative-import closure. Legacy declaration-syntax imports SHALL remain parser +compatibility syntax only. ### REQ-SC-003 @@ -61,7 +77,7 @@ languages. The Schema Compiler SHALL produce compiler artifacts requested by the selected configuration. -### REQ-SC-009 +### REQ-SC-009 (future compatibility work, not implemented in Stage A) The Schema Compiler SHALL support compatibility analysis involving `fieldIndex` and type associations. @@ -124,35 +140,22 @@ detail. ## Inputs -The Schema Compiler consumes: - -* `.brd` schema files -* normalized source-schema documents -* compatibility metadata -* reserved field metadata -* target language configuration -* target profile configuration - -Target profiles may describe constraints such as embedded memory limits, -supported field types, maximum nesting depth, and enabled generated outputs. +The production CLI consumes exactly one YAML root, its transitive relative-import +closure, target language/storage/naming options and emission selections. Internal +passes consume normalized source-schema models. Compatibility metadata, reserved +field mappings, persistent manifests and selectable target profiles are historical +future proposals, not supported CLI inputs. --- ## Outputs -The Schema Compiler may produce: - -* generated accessors -* generated validators -* generated binary codecs -* generated inspector metadata -* generated documentation -* compatibility reports -* schema manifests -* language-specific SDK files - -Generated outputs are build artifacts. Production systems consume these -artifacts directly. +Current outputs are C, C++ owning, C++/C-storage, Python or Go bindings for +selected namespaces, explicit minimal/reflective QBS images, and read-only CLI +inventories/identity/description text. Generated files include accessors, +validators and codecs. Schema IR remains compiler-owned tooling data. +Compatibility reports, persistent schema manifests and generated documentation +are not implemented outputs. Generation never deletes stale files. --- @@ -210,3 +213,40 @@ Detailed behavior is intentionally deferred to dedicated specifications: This document defines compiler architecture only. Detailed behavior is defined by the dedicated specifications that own those topics. + +## Implemented configuration generation + +REQ-SC-022: Configuration preparation SHALL compute the canonical BRF layout and +configuration identity once for generation/identity queries, then pass them to +backends and optional QBS emission. Output listing SHALL use backend planning and +SHALL NOT require identity hashing. Identity and selection behavior SHALL follow +[REQ-ID-001 through REQ-ID-010](configuration-and-code-identity.md#requirements). + +REQ-SC-023: Repeated generation with identical inputs and effective options SHALL +produce identical output files. Import reordering SHALL preserve record IDs, +schema_id and QBS bytes; source declaration ordering is not guaranteed invariant +(issue #90). `--generate` SHALL change emission selection only. + +REQ-SC-024: `--name-prefix` SHALL change source names and paths, not canonical +Schema IR names, record IDs, schema_id or BRF/QBS bytes. Storage-selection FQNs +SHALL remain canonical and unprefixed. Effective C host-storage policies SHALL +apply to unselected dependencies when computing native generated identity. + +CLI argument rules, diagnostics and exits are defined in +[Tools](../../tools/README.md); executable examples and checks are in the +[Stage A CLI guide](../stage-a-cli.md). + +## Examples + +The root `examples/truck/schemas/configuration.brd` imports eight record units. +Selecting `truck.engine` emits the complete engine namespace while its dependencies +retain the full root's IDs/identity. Compiling `engine.brd` independently instead +creates a different configuration. [Executable examples](../stage-a-cli.md) cover +selection, prefixes, storage, QBS modes and query diagnostics. + +## Related Documents + +- [Schema language](schema-language.md) +- [Configuration and generated-code identity](configuration-and-code-identity.md) +- [Compiler architecture](../compiler-architecture.md) +- [Tools](../../tools/README.md) diff --git a/docs/stage-a-cli.md b/docs/stage-a-cli.md new file mode 100644 index 0000000..703e55b --- /dev/null +++ b/docs/stage-a-cli.md @@ -0,0 +1,80 @@ +# Stage A CLI verification guide + +Run from the repository root with the current built or installed +`quarry-schema-compiler` on PATH (`build/debug/tools` for a source build). +These literal commands are executed by `stage_a_documentation_test`; temporary +outputs are used during testing. Full flag syntax is in [Tools](../tools/README.md). + +## Identity and resolved inputs + +```sh +quarry-schema-compiler --version +quarry-schema-compiler --help +quarry-schema-compiler --print-generated-code-api-version +quarry-schema-compiler --print-schema-id examples/truck/schemas/configuration.brd +quarry-schema-compiler --describe examples/truck/schemas/configuration.brd +quarry-schema-compiler --list-inputs examples/truck/schemas/configuration.brd +``` + +The API query prints `3`, the C++ owning epoch. The schema query prints +`9200ca494f010801b830d0857cf66dde` plus newline. `--describe` reports 6 domains, +8 records, formats `brf 2, qbs 1, schema-ir 1` and epochs +`cpp 3, c 7, python 1, go 1`. All eight IDs are tabulated in the +[readiness report](release-readiness-v0.1.31-rc.1.md#authoritative-truck-mapping). +`--list-inputs` lists all nine resolved schema paths (the root plus eight units), +without writing outputs. Compiler version/SHA/tag lines depend on the build; +the baseline reports `quarry-schema-compiler 0.1.291 (2a9aafd, untagged)`. +This is not a claim that the proposed release tag exists. + +## QBS modes + +```sh +quarry-schema-compiler --emit-qbs build/stage-a-docs/minimal.qbs examples/truck/schemas/configuration.brd +quarry-schema-compiler --emit-qbs build/stage-a-docs/reflective.qbs --qbs-reflective examples/truck/schemas/configuration.brd +``` + +Both headers contain algorithm 1 at byte 8 and the same full identity at bytes +12–27. Minimal and reflective images differ in optional names; repeat generation +of each mode is byte-identical. Selection or naming prefixes do not change +these wire bytes. Emitting QBS is explicit and does not generate bindings. + +## Selection, prefixing and storage + +```sh +quarry-schema-compiler --language c --name-prefix rev_a --generate truck.common,truck.engine --c-optimize-size=truck.common --output-directory build/stage-a-docs/c --list-outputs examples/truck/schemas/configuration.brd +quarry-schema-compiler --language c --name-prefix rev_a --generate truck.common,truck.engine --c-optimize-size=truck.common --output-directory build/stage-a-docs/c examples/truck/schemas/configuration.brd +quarry-schema-compiler --language cpp --cpp-storage c --c-optimize-size --generate truck.common,truck.engine --output-directory build/stage-a-docs/cpp-c examples/truck/schemas/configuration.brd +``` + +Listing writes nothing; generation writes exactly the listed files. Prefixes +nest paths beneath literal `rev_a/` and encode C symbols as +`revq0a_truck_engine_EngineStatus_t`. `--generate` and storage lists take canonical +unprefixed namespace FQNs. Bare `--c-optimize-size` compacts every namespace; +`=truck.common` compacts only that exact namespace, not its descendants. Declare +the same effective policy in separate invocations, including policies for +unselected dependencies; mismatches are compile errors. Output naming can change +source definitions/gid, never wire schema_id. Unprefixed #119 collisions remain +outside this RC's same-TU support contract. + +## Diagnostics and exits + +| Case | Exit | Diagnostic / behavior | +|---|---|---| +| Successful generation/query | 0 | stdout for queries; ordinary generation is quiet | +| Unknown `--generate` namespace | 1 | `BC8002`, lists available namespaces, no files written | +| Unreadable/invalid schema or backend/write failure | 1 | error on stderr | +| `--qbs-reflective` without `--emit-qbs` | 2 | `--qbs-reflective requires --emit-qbs` | +| `--describe` with `--print-schema-id` | 2 | query conflict | +| Invalid/repeated prefix, malformed option syntax | 2 | usage error | + +`--describe` ignores emission selections (even unknown FQNs), storage/backend +choices and output naming after basic argument parsing. It cannot combine with +other query modes, QBS emission or version output. Unknown per-namespace storage +names fail generation with exit 1; malformed lists fail usage with exit 2. +No discovery, compatibility negotiation, descriptor emission or automatic +historical-record translation is provided. + +The existing [consumer guide](generated-binding-compatibility.md#working-separate-invocation-examples) +executes separate generation plus strict C99/C++20 compilation. The +[truck A/B runner](../examples/truck/multi_configuration/README.md) and installed +example tests exercise all five variants; this guide does not duplicate them. diff --git a/docs/versioning.md b/docs/versioning.md index 432a67a..202fc2e 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -53,7 +53,7 @@ The wire `schema_id` algorithm and generated-code identity format are both `1`, with separate meanings. None derives from the package version, and equal epochs do not establish native ABI compatibility. See the [consumer compatibility and migration guide](generated-binding-compatibility.md) -for the three mechanisms and regeneration requirements. #111 G1–G4 changes none +for the three mechanisms and regeneration requirements. #111 G1–G5 changes none of these versions or epochs. To build the native compiler with fresh version metadata and display its @@ -87,3 +87,23 @@ preserves both fields when a tag exists. Missing or invalid numeric fallback metadata remains an error without Git. When archive Git SHA metadata is absent, the CLI explicitly reports `Git SHA unavailable`. None of these fields enters schema identity, generated-code identity or generated bindings. + +## Stage A epoch decision + +A4.2 (#106) adds generated configuration checks and changes generated C++ linkage; +#111 G1–G5 adds gid guards, inline namespaces and policy validation. These changes +require regenerating bindings and rebuilding affected native consumers, but do +not change the generator/runtime call contract, so owning C++ 3, C/C-storage 7, +Python 1 and Go 1 remain unchanged (approved A4.2 decision). A4.3's C accessor is +additive: only callers of it require the updated linked library. `--version` and +`--describe` report numeric development version, short Git SHA (or `Git SHA +unavailable`) and `release tag ` or `untagged`. These fields enter +neither wire schema_id nor native gid. A prefix may change gid through generated +source definitions, not release metadata. See the +[normative compatibility contract](specifications/configuration-and-code-identity.md#accessors-and-compatibility). + +The earlier post-RC3 C codec migration is a different epoch decision: the exact +`v0.1.30-rc.3` tag had C epoch 2, while the shared-codec/presence/decode-operation +work (#77/#79) reaches epoch 7. The unchanged A4.2/gid decision must not be read as +“no C runtime-contract changes since RC3.” Regenerate and link the matching C +runtime. Go was added after RC3 at epoch 1. diff --git a/examples/README.md b/examples/README.md index 2071141..4e31b02 100644 --- a/examples/README.md +++ b/examples/README.md @@ -26,3 +26,12 @@ Current examples: Each example README gives the install, generation, build, and execution commands. Bindings that reference one another are always generated from the same compilation root, so they share one record-ID mapping. + +## Stage A verification + +The [truck A/B example](truck/multi_configuration/README.md) demonstrates all five +variants in one application/process. The maintained [A5 matrix](../tests/interop/matrix/README.md) +exchanges actual BRF streams across all 25 producer/consumer pairs, including +nested cuts. These are complementary checks; independent round trips alone do +not establish interoperability. See the [CLI guide](../docs/stage-a-cli.md) and +[release migration](../docs/release-notes-v0.1.31-rc.1.md). diff --git a/runtime/README.md b/runtime/README.md index d261a66..ff33344 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -40,9 +40,8 @@ or perform schema exchange. The nested-reader Phase A substrate is kept in `runtime/detail/brf_validation_cache.hpp`. It uses stable integer indexes for -validated record nodes and relations, plus an explicit work stack. Public -nested-record and record-array access remains disabled until the subsequent -phase wires complete BRF child validation through this cache. +validated record nodes and relations, plus an explicit work stack. Nested-record and record-array access uses complete child validation through +this cache. `quarry/runtime/qbs_brf_reader.hpp` provides a read-only bridge from a validated `ValidatedQbsView` to an untrusted BRF v2 record. Callers validate a @@ -474,3 +473,14 @@ Python uses `QbsSchema.schema_id` and `.schema_id_algorithm`. All report the stored wire configuration identity, not generated-code `gid`. Parser validation is unchanged: C/Python do not compute its hash; the C++ parser already verifies it during parsing. The accessors add no verification and no API epoch bump. + +## Stage A QBS identity access + +C `quarry_qbs_schema_id()` and Python `QbsSchema.schema_id` / +`schema_id_algorithm` expose the stored full configuration identity. The existing +C++ compiler-owned `ValidatedQbsView::schema_id()` is internal tooling, not a new +installed C++ QBS SDK. These accessors introduce no hashing or mandatory startup; +they preserve public view layouts and epochs. C requires the updated linked +`Quarry::runtime_c`; its generated-code epoch remains 7. C++ owning stays 3, +Python and Go stay 1. Native gid is separate and absent from BRF/QBS. See +[the accessor contract](../docs/specifications/configuration-and-code-identity.md#accessors-and-compatibility). diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 14c82f4..6660767 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -133,6 +133,11 @@ if(QUARRY_PYTHON3_EXECUTABLE) --source "${CMAKE_SOURCE_DIR}" --compiler "$" --generated-include "${QUARRY_GENERATED_INCLUDE_DIR}") + add_test(NAME stage_a_documentation_test + COMMAND ${QUARRY_PYTHON3_EXECUTABLE} + "${CMAKE_CURRENT_SOURCE_DIR}/tools/stage_a_documentation_test.py" + --source "${CMAKE_SOURCE_DIR}" + --compiler "$") add_test(NAME consumer_documentation_test COMMAND ${QUARRY_PYTHON3_EXECUTABLE} "${CMAKE_CURRENT_SOURCE_DIR}/tools/consumer_documentation_test.py" diff --git a/tests/tools/stage_a_documentation_test.py b/tests/tools/stage_a_documentation_test.py new file mode 100644 index 0000000..9d34ee2 --- /dev/null +++ b/tests/tools/stage_a_documentation_test.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Check relative Markdown links and execute the Stage A CLI guide.""" +import argparse +from collections import Counter +from pathlib import Path +import re +import shlex +import shutil +import subprocess +import tempfile +from urllib.parse import unquote + + +def headings(markdown): + counts = Counter() + anchors = set(re.findall(r']+>', '', heading).lower() + slug = ''.join(c for c in heading if c.isalnum() or c in '_- ').replace(' ', '-') + count = counts[slug] + counts[slug] += 1 + anchors.add(slug + ('-' + str(count) if count else '')) + return anchors + + +def check_links(source): + names = subprocess.check_output(['git', '-C', str(source), 'ls-files', '*.md'], text=True) + # Also exercise newly added documents before staging during development. + files = {source / name for name in names.splitlines()} + files.update((source / 'docs').glob('*v0.1.31-rc.1.md')) + files.update((source / 'docs/specifications').glob('configuration-and-code-identity.md')) + files.add(source / 'docs/stage-a-cli.md') + links = 0 + for path in sorted(files): + markdown = path.read_text() + for destination in re.findall(r'\]\(([^)\s]+)(?:\s+"[^"]*")?\)', markdown): + if re.match(r'^[a-zA-Z][a-zA-Z0-9+.-]*:', destination): + continue + target_name, _, fragment = destination.partition('#') + target = path.parent / unquote(target_name) if target_name else path + assert target.exists(), f'{path.relative_to(source)}: missing {destination}' + if fragment and target.is_file() and target.suffix == '.md': + assert unquote(fragment) in headings(target.read_text()), ( + f'{path.relative_to(source)}: missing heading {destination}') + links += 1 + return len(files), links + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', required=True) + parser.add_argument('--compiler', required=True) + args = parser.parse_args() + source = Path(args.source).resolve() + compiler = str(Path(args.compiler).resolve()) + files, links = check_links(source) + guide = (source / 'docs/stage-a-cli.md').read_text() + commands = [] + for block in re.findall(r'```sh\n(.*?)```', guide, re.S): + for line in block.replace('\\\n', ' ').splitlines(): + words = shlex.split(line, comments=True) + if words: + assert words[0] == 'quarry-schema-compiler', words + commands.append([compiler, *words[1:]]) + assert commands + with tempfile.TemporaryDirectory(prefix='quarry-stage-a-docs-') as temporary: + root = Path(temporary) + shutil.copytree(source / 'examples/truck', root / 'examples/truck') + + def run(flags, status=0, diagnostic=None): + result = subprocess.run([compiler, *map(str, flags)], cwd=root, + text=True, capture_output=True, check=False) + assert result.returncode == status, (flags, result.returncode, result.stderr) + if diagnostic: + assert diagnostic in result.stderr, (flags, result.stderr) + elif status == 0: + assert not result.stderr, result.stderr + return result.stdout + + outputs = {} + for command in commands: + outputs[tuple(command[1:])] = run(command[1:]) + schema = 'examples/truck/schemas/configuration.brd' + identity = run(['--print-schema-id', schema]).strip() + assert identity in guide and identity == '9200ca494f010801b830d0857cf66dde' + assert run(['--print-generated-code-api-version']).strip() == '3' + description = run(['--describe', schema]) + assert 'formats: brf 2, qbs 1, schema-ir 1' in description + assert 'generated-code epochs: cpp 3, c 7, python 1, go 1' in description + readiness = (source / 'docs/release-readiness-v0.1.31-rc.1.md').read_text() + for record_id, fqn in re.findall(r'^ (0x[0-9a-f]{8}) (\S+)$', description, re.M): + assert f'| {fqn} | {record_id} |' in readiness, (record_id, fqn) + assert len(run(['--list-inputs', schema]).splitlines()) == 9 + help_text = run(['--help']) + assert '```text\n' + help_text + '```' in (source / 'tools/README.md').read_text() + for reflective in (False, True): + name = 'reflective.qbs' if reflective else 'minimal.qbs' + image = root / 'build/stage-a-docs' / name + original = image.read_bytes() + assert original[:5] == b'QBS\x00\x01', original[:5] + assert original[8] == 1 and original[12:28].hex() == identity + run(['--emit-qbs', image, *(['--qbs-reflective'] if reflective else []), schema]) + assert image.read_bytes() == original + for flags, listed in outputs.items(): + if '--list-outputs' in flags: + directory = root / flags[flags.index('--output-directory') + 1] + assert set(listed.splitlines()) == { + str(p.relative_to(root)) for p in directory.rglob('*') if p.is_file()} + run(['--qbs-reflective', schema], 2, '--qbs-reflective requires --emit-qbs') + run(['--generate', 'missing', schema], 1, 'BC8002') + run(['--describe', '--print-schema-id', schema], 2) + run(['--name-prefix', 'bad-prefix', schema], 2) + run(['--language', 'c', '--c-optimize-size=missing', schema], 1) + rev_b = 'examples/truck/multi_configuration/rev_b/configuration.brd' + assert run(['--print-schema-id', rev_b]).strip() == '806e9a4e11d0df71c4e5b51045f85010' + assert '0x00030002 truck.cms.MirrorFold' in run(['--describe', rev_b]) + print(f'Checked {files} Markdown files / {links} relative links and heading fragments; ' + f'executed {len(commands)} literal CLI examples, QBS headers, mappings and error controls.') + + +if __name__ == '__main__': + main() diff --git a/tools/README.md b/tools/README.md index b48ec2a..ab269bd 100644 --- a/tools/README.md +++ b/tools/README.md @@ -32,7 +32,7 @@ through the production YAML frontend and writes generated files for the selected namespaces and the selected C++, C, Python, or Go backend. ```text -quarry-schema-compiler [options] INPUT +usage: quarry-schema-compiler [options] INPUT Options: -o, --output-directory PATH Directory for generated files (default: generated) @@ -48,16 +48,17 @@ Options: --generate NS[,NS...] Emit only these namespaces (repeatable). Default: the root's namespace, or every namespace of a configuration root. IDs and QBS never change. - --emit-qbs PATH Emit a deterministic binary QBS image + --emit-qbs PATH Emit the resolved schema as a deterministic QBS image + --qbs-reflective Include reflective record, field, and enum names in QBS --list-inputs Print all resolved schema input paths without writing files --list-outputs Print generated output paths without writing files --print-generated-code-api-version Print the generated-code API compatibility version and exit + --print-schema-id Print the resolved configuration's 128-bit schema_id --name-prefix NAME Nest generated source names and paths beneath NAME --describe Describe the full configuration without writing files - --print-schema-id Print the resolved configuration's 128-bit schema_id --version Show version information - -h, --help Show help + -h, --help Show this help text ``` `--language` selects which backend generates output: `cpp` (the default, @@ -314,10 +315,12 @@ compilation is quiet and returns exit code `0`. `--version` is a terminal informational option. It prints: ```text -quarry-schema-compiler +quarry-schema-compiler [-dirty] (, ) ``` -to stdout, writes nothing to stderr, and exits with code `0`. When combined +Release-tag metadata is `release tag ` or `untagged`; it is +independent of the numeric development version. Output goes to stdout, with +nothing on stderr and exit code `0`. When combined with otherwise valid generation options or an input path, it still reports the version and does not generate files. @@ -383,8 +386,6 @@ directory. If the output directory is absolute, listed paths are absolute. The tool does not canonicalize or rebase them. Output order is deterministic and matches backend `GenerationPlan` order. -The output is line-oriented and does not define an escaping format; scripts -should avoid newline characters in output-directory, root-stem, or extension The output is line-oriented; scripts should avoid newline characters in output-directory, root-stem, or extension arguments. @@ -712,3 +713,11 @@ under canonical namespace keys. Prefixes can change those definitions and their native objects ABI-interchangeable. See the [truck multi-configuration example](../examples/truck/multi_configuration/README.md) for working C, C++, C-storage, Python and Go consumers. + +### Stage A executable documentation + +The [CLI verification guide](../docs/stage-a-cli.md) runs literal commands for all +identity/root/selection/prefix/QBS/storage query modes and checks expected errors. +The [release notes](../docs/release-notes-v0.1.31-rc.1.md) describe regeneration and +rebuild requirements. These are implemented Stage A features; descriptor discovery, +partial images, compatibility classification and translation remain future work.