Skip to content

Commit 0ac471e

Browse files
authored
test(encrypt): specify declaration grammar
1 parent 292b954 commit 0ac471e

11 files changed

Lines changed: 3993 additions & 16 deletions

File tree

‎conformance/stack-encrypt/README.md‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
This directory holds a shared test contract for Stack Encrypt bindings. The
44
[implementation plan](../../docs/plans/2026-10-31-stack-encrypt-conformance.md)
55
sets out the wider work; [coverage.md](coverage.md) maps existing evidence and
6-
gaps. This first profile is **experimental**, not certification of an entire SDK.
6+
gaps. These profiles are **experimental**, not certification of an entire SDK.
77

88
## Run
99

@@ -18,12 +18,29 @@ No credentials or database are required. The task refuses a missing test guest.
1818
It runs native Rust against frozen vectors, Go against the same vectors, then
1919
native Rust against the ciphertexts Go has just produced. It never regenerates
2020
expectations. CI also runs the Go cases on its other supported host platforms.
21+
The same task runs the shared declaration acceptance/rejection corpus in both
22+
languages, with native observations of normalization.
2123

2224
The Rust runner is `packages/stack-encrypt/tests/conformance.rs`; the Go runner
2325
is `languages/golang/encrypt/conformance_test.go`. Go calls the record interface
2426
used by generated code. Testing public SDK declarations is a separate layer.
2527
Python and TypeScript runners are pending; their absence is not a passing result.
2628

29+
## `record-declarations-v1` contract
30+
31+
The [declaration grammar](declaration-grammar.md) defines the engine's current
32+
record-plan syntax, defaults, context rules, kind/index table and null policies.
33+
`v1/declarations.json` contains 201 cases, including malformed frames and all
34+
21 kinds against five scalar indexes. The resolver is explicitly `none`; EQL
35+
targets need their own profile.
36+
37+
The runners are `packages/stack-encrypt/tests/declarations.rs` and
38+
`languages/golang/encrypt/declaration_conformance_test.go`. Both call the engine
39+
without a cipher. Valid-frame declaration diagnostics agree exactly; malformed
40+
frames document the different native-parser and WASI-boundary classifications.
41+
Native Rust also checks normalization observations. Go's checker does not expose
42+
the parsed plan, so it asserts acceptance and diagnostics.
43+
2744
## `record-scalars-v1` contract
2845

2946
`v1/cases.json` has a corpus format `version`, a semantic `profile`, a public

‎conformance/stack-encrypt/coverage.md‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`.
88
|---|---|---|
99
| Scalar value widths and lossless transport | `packages/stack-encrypt/tests/value_kinds.rs`; `languages/golang/encrypt/value_kinds_test.go`; initial shared scalar cases | Expand shared cases to decimals, dates, timestamps, floats, bytes and all widths; Python/TS mappings |
1010
| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases | Blob profile; encoded targets; supported version matrix |
11-
| Record declaration and lowering | `packages/stack-encrypt/tests/record_lowering.rs`; `languages/golang/encrypt/fixture_test.go` | Normative grammar, normalization, accepted/rejected definition corpus |
11+
| Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/declarations.json` shared by native Rust and Go; native normalization observations; existing record lowering suites | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes |
1212
| Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix |
1313
| Query terms and diagnostics | `packages/stack-encrypt/tests/query_operators.rs`; `languages/golang/encrypt/query_test.go`; initial equality/query-error cases | Common rejection corpus for every operator, capability and input shape |
1414
| Missing, SQL NULL and sealed null | `packages/stack-encrypt/src/dynamic/record.rs` null tests; `languages/golang/encrypt/null_test.go` | Explicit language mappings and common missing/null fixtures |
@@ -22,3 +22,30 @@ Paths are relative to the repository root. New profile cases run from `v1/`.
2222

2323
Python and future TypeScript runners have no evidence in this checkout. Their
2424
absence is a delivery gap, not a test skip that counts toward certification.
25+
26+
## Consolidation policy
27+
28+
Shared semantic expectations should be maintained once and executed by each
29+
language runner. Conformance can replace duplicate case tables and fixture
30+
maintenance. It does not eliminate the need to execute the Rust and Go paths.
31+
No existing test has been deleted in these first two slices.
32+
33+
| Existing evidence | Relationship to conformance | Consolidation action |
34+
|---|---|---|
35+
| Rust `dynamic/record.rs` tests `a_malformed_plan`, `a_null_is_refused_as_its_key`, `a_missing_or_null_index_payload_is_the_default` | Many inputs and diagnostic outcomes are now shared declaration cases | Move the remaining cases and retain any unique display/low-level assertions before removing duplicate rows |
36+
| Rust kind/index admission tests | The corpus has the complete 21-kind/five-index acceptance matrix | Share case data; retain direct tests that compare declaration admission with actual term execution |
37+
| Rust `value_kinds.rs`, Go `value_kinds_test.go` | Already share `value_kinds.json`; cover more types and generated SDK code than the initial scalar profile | Enroll that existing fixture under named requirements instead of copying it; keep generated-code assertions |
38+
| Rust `query_operators.rs`, Go `query_test.go` | Already share operator vectors, including verification and target limits | Reuse their fixture and cases when adding an operator profile; preserve host/generated query mapping tests |
39+
| Go checker and host validation tests in `guest_test.go` | Exercise host rejection and diagnostic forwarding through public checker methods | Keep adapter-specific assertions; raw-frame conformance bypasses host validation deliberately |
40+
| Native scalar/record round trips and cross-opening | Some behavior overlaps, but existing tests cover more types and API paths | Replace only exact duplicates after matching requirements and execution paths |
41+
42+
Keep Rust compile-fail, ownership/zeroization, batching, fuzz/property, and
43+
implementation regression tests. Keep Go generation, host type conversion,
44+
error wrapping, cancellation and guest lifecycle tests. Keep independent
45+
PostgreSQL oracles and live-provider tests. These observe guarantees a shared
46+
engine corpus cannot prove by itself.
47+
48+
For each removal, link the old assertion to stable case IDs, compare coverage
49+
and failure behavior, and run both runners in CI. Preserve unrelated assertions
50+
from mixed tests. Enroll Python and TypeScript against the existing corpus so
51+
adding a language does not create another copy of the expected behavior.
Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
# Record declaration grammar
2+
3+
Use this contract when a binding lowers an SDK declaration to the engine's record
4+
plan. Send the complete plan to the engine checker before executing it.
5+
6+
For example, this declaration seals and equality-indexes an int64 field:
7+
8+
```json
9+
{
10+
"value": {
11+
"context": ["users", "value"],
12+
"outputs": ["c", "eq"],
13+
"type": "int64"
14+
}
15+
}
16+
```
17+
18+
Run the executable cases with `mise run test:conformance`, after building the
19+
deterministic test guest as described in [README.md](README.md).
20+
`ciphertext-untyped`, `index-only`, and every `type-*-eq` case exercise these forms.
21+
22+
## Scope and authority
23+
24+
`record-declarations-v1` describes the engine at PR #1404's `b684a217e`, not future
25+
SDK syntax. It is an experimental conformance profile, not a new production wire
26+
version. The input is a Vitamin C **typed transport frame**. JSON below is a
27+
readable projection; it cannot distinguish every integer width or carry bytes.
28+
29+
The executable authority is `stack_encrypt::dynamic::record::plan_with`, with the
30+
selected target resolver. Native `record::plan` and the Go guest without EQL use
31+
`NoTargets`. The corpus fixes that resolver explicitly as `none`. It checks
32+
target syntax and unavailable-target refusals; it does not certify EQL targets.
33+
34+
The full contract has three parts: frame validity, the structural grammar below,
35+
and the semantic constraints. A shape-only JSON Schema would not enforce the
36+
context, index, null or resolver rules. SDK tooling must ask the engine instead
37+
of implementing those rules again. Test runners convert fixture values and
38+
observe results; they do not provide another semantic validator.
39+
40+
## Structural grammar
41+
42+
This is a typed grammar. `Object{...}` denotes a transport object, `List<T>` a
43+
transport array, `?` an optional member, and `|` an alternative. Literal words
44+
denote text values. Each object has exactly the listed keys, except `Plan`, whose
45+
non-reserved keys are field names. Object key order is unrestricted.
46+
47+
```text
48+
Plan = Object{
49+
"context_field"?: Text,
50+
(FieldName: FieldSpec)+
51+
}
52+
FieldName = Text except "context_field"
53+
54+
FieldSpec = Object{
55+
"context": FieldContext,
56+
("outputs": NonEmptyList<Output> | "target": Target),
57+
"type"?: ValueKind,
58+
"null"?: "sealed" | "sql"
59+
}
60+
61+
FieldContext = Label | [FieldContext, ContextScalar]
62+
Label = NonEmptyList<PlainSegment>
63+
ContextScalar = Text | Bytes | Int32 | Int64 | UInt32 | UInt64
64+
65+
UnitOutput = "c" | "passthrough" | "eq" | "ore" | "ope" | "ore_block"
66+
Output = UnitOutput | Object{UnitOutput: Null}
67+
| "match" | Object{"match": Null | MatchOptions}
68+
| "json" | Object{"json": Null | JsonOptions}
69+
70+
MatchOptions = Object{
71+
"tokenizer"?: Tokenizer,
72+
"downcase"?: Bool,
73+
"short_words"?: Bool,
74+
"k"?: Integer,
75+
"m"?: Integer
76+
}
77+
Tokenizer = "standard" | Object{"standard": Null}
78+
| Object{"ngram": Integer}
79+
80+
Target = NonEmptyText | Object{
81+
"name": NonEmptyText,
82+
"options"?: JsonOptions
83+
}
84+
JsonOptions = Object{
85+
"sealed_root"?: Bool,
86+
"ordered"?: List<JsonPathText>
87+
}
88+
89+
ValueKind = "bool"
90+
| "int8" | "int16" | "int32" | "int64" | "int128"
91+
| "uint8" | "uint16" | "uint32" | "uint64" | "uint128"
92+
| "float32" | "float64" | "decimal" | "date" | "timestamp"
93+
| "string" | "bytes" | "array" | "object" | "json"
94+
```
95+
96+
`outputs` and `target` are exclusive and one must be present. Present optional
97+
members must have the declared type: `"type": null` is not omission.
98+
The explicit null alternatives for enum payloads are exceptions, pinned by the
99+
`unit-output-null-*` and `match-default-*` cases. Unknown keys and output/type
100+
names fail; no unknown option is ignored.
101+
102+
`Integer` here means an integer-valued transport tag accepted by the option's
103+
integer reader, within its bounds. It does not mean a floating-point value that
104+
happens to be integral. Width is not an option's identity. Context integer width,
105+
in contrast, is part of context identity and must survive parsing unchanged.
106+
107+
Every object key must be unique, including keys nested inside options. The frame
108+
must contain exactly one complete value within the codec's depth and size bounds.
109+
Duplicate keys, truncation and trailing data fail before declaration semantics.
110+
Do not change these codec rules in this specification.
111+
112+
## Context semantics
113+
114+
Try the `Label` alternative before decomposing an extension. A flat text list
115+
is a label; `["users", "region", "value"]` has three segments. It is not the
116+
extended context `[["users", "value"], "region"]`. Extensions nest to the left.
117+
An extension is scalar, so `[["users", "value"], ["tenant"]]` is refused.
118+
Bare `"users/value"` is not a field label.
119+
120+
A plain segment is nonempty and cannot contain `/`, parentheses, control
121+
characters, or the invisible format characters listed by `Label::check_segment`
122+
in `packages/stack-encrypt/src/descriptor.rs`. It cannot start with `b64:`, `-`,
123+
or an ASCII digit. That shared label rule is referenced rather than reimplemented
124+
by a binding. It applies to label segments, not SDK variable names.
125+
126+
Without `context_field`:
127+
128+
- Every field label has at least two segments.
129+
- The last segment is the field's identity. All preceding segments form the
130+
plan label, which must agree across fields.
131+
- All fields have the same ordered extension values, including their types.
132+
- Sealed/indexed field identities cannot collide. The field's map key and its
133+
identity may differ; renaming a map key does not implicitly change its label.
134+
135+
With `context_field`:
136+
137+
- Its value names a declared field, whose sole output is `passthrough`.
138+
- That field declares `string` or omits `type`; omission resolves to `string`.
139+
- Every field label has exactly one segment: its identity.
140+
- Extensions still agree across fields. No target field is admitted.
141+
- At execution, each record supplies the named field's label value. Its validity
142+
and the opener's expected-context constraint are runtime requirements.
143+
144+
The grammar does not add call-time context roles or defaults. Context composition
145+
is observed by `extended-context`, `flat-label-is-not-extension`, the
146+
`typed-extension-*` cases, and the mixed-context refusals.
147+
148+
## Output and kind semantics
149+
150+
An output list is nonempty. Output keys are unique after reading their options:
151+
two differently configured match indexes still collide on `match`.
152+
`passthrough` is always the sole output. Ciphertext is explicit; an index-only
153+
declaration does not implicitly acquire `c`.
154+
155+
Every field with a scalar index declares `type`. Ciphertext-only and passthrough
156+
fields may omit it. Declaring a kind checks values during execution; it does not
157+
select a different leaf encoding.
158+
159+
| Declared kind | `eq` | `match` | `ore`, `ope`, `ore_block` |
160+
|---|---|---|---|
161+
| bool | Refused | Refused | Refused |
162+
| int8, uint8 | Admitted | Refused | Refused |
163+
| Other integer widths | Admitted | Refused | Admitted |
164+
| float32, float64, decimal, date, timestamp | Admitted | Refused | Admitted |
165+
| string | Admitted | Admitted | Admitted |
166+
| bytes | Admitted | Refused | Admitted |
167+
| array, object, json | Refused | Refused | Refused |
168+
169+
The corpus explicitly tests all 21 kinds against all five scalar indexes.
170+
`array` and `object` may still be sealed without indexes. A `json` field requires
171+
a document target. A raw `json` output has a recognized syntax but is refused as
172+
`json_index_pending`; it is not an alternative to a document target.
173+
174+
Match defaults are 3-grams, `downcase: true`, `short_words: false`, `k: 3`, and
175+
`m: 256`. Every missing option takes its default. The bounds are:
176+
177+
- `3 <= k <= 16`.
178+
- `m` is a power of two from 32 through 65536.
179+
- N-gram length is nonzero and representable by the implementation's integer reader.
180+
- `short_words: true` requires n-grams of length at least three.
181+
182+
Standard tokenization cannot enable short words. An invalid option fails when
183+
the declaration is checked, before values or keys are needed.
184+
185+
## Null semantics
186+
187+
Omitting `null` keeps the field required. A typed field then refuses null values;
188+
an untyped value's ability to represent null is not an implicit nullable column.
189+
`null` is a storage policy, distinct from a null option payload or a missing key.
190+
191+
| Policy | Declaration requirements | Runtime meaning |
192+
|---|---|---|
193+
| `sql` | Any non-passthrough field | Missing/null source leaves no encrypted field output; the host stores SQL NULL |
194+
| `sealed` | A fixed-width bool, number, decimal, date or timestamp; only equality indexes, if any | Missing/null source is sealed with type-appropriate padding; equality uses the field's null term |
195+
196+
Text, bytes and composite kinds cannot request sealed null. Passthrough cannot
197+
request either policy. These cases check declaration admissibility only; runtime
198+
padding, queries, missing values and round trips retain their existing tests.
199+
200+
## Targets and JSON options
201+
202+
Target syntax is parsed before resolver lookup. `options` takes JSON-index
203+
options; a null options object or unknown option is an invalid target.
204+
`sealed_root` defaults to true, and `ordered` to an empty set.
205+
Paths are parsed by `JsonPath::parse`; ordered paths cannot select array positions.
206+
Repeated equivalent paths collapse into the set.
207+
208+
Under this profile's `none` resolver, every otherwise valid target produces
209+
`stack_encrypt::target_none` with its target name. A missing target capability
210+
must never silently turn into a ciphertext-only field.
211+
212+
For a resolver that supplies EQL types, additional existing rules apply: the
213+
target must be producible, its column label has exactly two segments, and the
214+
plan has neither extensions nor a context field. An explicit kind matches the
215+
target's plaintext kind; otherwise that kind is inferred. Only a document target
216+
accepts JSON options. Sealed-null rules include the target's own indexes.
217+
Those resolver-dependent outcomes and normalization need an EQL profile; this
218+
corpus does not claim they have been verified across bindings.
219+
220+
## Normalization observations
221+
222+
The native runner observes the parsed plan directly. Its `normalized` fixture
223+
field is a test report, not a canonical production serialization:
224+
225+
- `label` and `context_field` identify the resolved context source.
226+
- `extension` lists typed scalar parts, preserving width and order.
227+
- `fields` retains transport field order, label segments, resolved kind,
228+
null policy and output order.
229+
- Unit output aliases become bare keys. Default match options become `"match"`.
230+
Non-default match options are explicit; `short_words` is emitted only when true.
231+
232+
No binding should sort production fields, flatten contexts, coerce context
233+
integers, or infer omitted ciphertext outputs from these observations.
234+
`frame-field-order` checks field order independently of the JSON projection.
235+
236+
The Go plan-check export returns success or a diagnostic, not a normalized plan.
237+
Its runner therefore verifies acceptance and diagnostics. It does not claim an
238+
independent observation of normalization or add a production export for testing.
239+
240+
## Diagnostics and corpus format
241+
242+
The corpus is `v1/declarations.json`. Its version, profile and resolver are
243+
required. Case IDs are unique and stable. Every case contains exactly one input:
244+
245+
- `{"json": value}` converts JSON objects in lexical key order. Nonnegative
246+
integers become uint64, negative integers int64, and fractional values float64.
247+
Arrays preserve order. This is fixture conversion, not SDK policy.
248+
- `{"frame_hex": text}` supplies exact transport bytes, including typed contexts,
249+
original field order and malformed frames that JSON cannot represent.
250+
251+
`accepted` is mandatory. Refused cases require `expected_error`, containing the
252+
native engine diagnostic code and structured payload. Accepted cases may include
253+
`normalized`. Runners reject unknown corpus keys and contradictory outcomes.
254+
255+
A malformed transport frame also has `boundary_error`. The native parser reports
256+
`stack_encrypt::dynamic_plan` with `not_an_object`; the WASI frame check reports
257+
`stack_guest_abi::malformed_input` before reaching that parser. Both runners verify
258+
the frame really is malformed. Valid-frame declaration errors must agree exactly
259+
on code and payload; Go also requires `ErrEncoding`. Error prose is not contractual.
260+
261+
Cases isolate a failure where practical. This profile does not define universal
262+
error precedence for declarations containing several independent faults.
263+
Neither runner initializes a cipher to check declarations. The Go checker has
264+
no credentials and uses a refusing transport.
265+
266+
## Evidence and limits
267+
268+
The corpus covers 201 cases: 91 accepted and 110 refused, including the complete
269+
scalar kind/index matrix. The native runner also checks selected normalization
270+
observations. Existing codec tests own exhaustive frame validity, depth limits,
271+
and integer-reader behavior. Existing EQL tests own resolver/catalog behavior.
272+
Runtime operations and language-specific declarations remain separate layers.
273+
274+
See [coverage.md](coverage.md) for the consolidation policy. New Python and
275+
TypeScript runners can adopt these inputs and expectations without copying the
276+
engine's validation rules.

‎conformance/stack-encrypt/v1/cases.json‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22
"version": 1,
33
"profile": "record-scalars-v1",
44
"seed": "0000000000000000000000000000000000000000000000000000000000000000",
5-
"context": [
6-
"conformance"
7-
],
5+
"context": ["conformance"],
86
"field": "value",
97
"required_capabilities": [
108
"records",

0 commit comments

Comments
 (0)