| Internet-Draft | CDDL Code Generation | November 2026 |
| Jeremy O'Donoghue | Expires 31 May 2027 | [Page] |
The Concise Data Definition Language (CDDL) was specified to express the structure of CBOR and JSON data, principally so that instances can be validated against a specification. It is now starting to be used as the source from which encoders and decoders are generated.¶
Compilation exercises a specification language in ways that validation does not. This document records three things. First, guidance for CDDL authors on which constructions compile to small, fast, one-pass code and which do not. Second, a description of what a code generator has to do with a CDDL specification, and where implementation and run-time cost lies. Third, a set of questions where RFC 8610 and its updates say nothing, are under-determined, or determine in a way that deployed specifications do not follow, each with a motivating example drawn where possible from a published RFC or an active Internet-Draft.¶
This document is a discussion input. It creates no requirements on implementations and defines no new CDDL syntax.¶
This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.¶
Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at https://datatracker.ietf.org/drafts/current/.¶
Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."¶
This Internet-Draft will expire on 31 May 2027.¶
Copyright (c) 2026 IETF Trust and the persons identified as the document authors. All rights reserved.¶
This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Revised BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Revised BSD License.¶
[RFC8610] specifies CDDL as a notational convention for expressing CBOR and JSON data structures. Its main intent is validation: given a specification and a data item, decide whether the item matches. The matching rules are stated normatively in Appendix C of [RFC8610], which is written throughout in those terms.¶
A second use has grown up alongside the first. Protocol specifications in working groups including CBOR, COSE, RATS and SCITT now carry their normative data definitions in CDDL, and implementers of those protocols are becoming interested in deriving the encoder and decoder from the specification rather than transcribe it by hand. The appeal is clear: the specification is the only authoritative statement of the format, a transcription can drift from it, and a generated codec using correct tools cannot.¶
Compilation makes greater demands on a specification language than validation does, in a specific way. A validator may answer "does this item match?" by any means it likes, including exhaustive search, because it has the whole item in front of it and a wrong answer is the only failure mode that matters. A generated decoder on a constrained target typically reads the input once, in order, with bounded memory and no ability to put bytes back. To emit such a decoder, a generator must decide in advance, at compile time, from the specification alone — what the decoder will do at each point. Where the specification language leaves a matching question open, a validator can leave it open too; a generator has to pick, and two generators picking differently emit codecs that disagree about the same bytes on the wire.¶
This document investigates the extent to which such a gap exists and how to address it.¶
Section 3 gives guidance to CDDL authors: constructions that compile efficiently, constructions that do not, and what to write instead. It is deliberately light on rationale, and cross-references Section 4 for the reasons.¶
Section 4 describes what a code generator must do with a CDDL specification: what it must resolve before any code shape can be chosen, what it must analyse, and which decisions determine the shape and size of the generated code. It is a description of the problem, not a specification of a solution.¶
Section 5 records open design questions. Each gives a motivating piece of CDDL, states what the normative text does and does not settle, and explains the consequence. These are the topics likely to require working group attention.¶
Section 6 treats the security consequences: a generated validator that is incomplete relative to the normative semantics can reject valid data on a signature-verification path, and a generated decoder that silently fails to enforce a constraint silently moves a trust boundary.¶
Appendix A is an informative description, in more detail, of one possible compilation model for CDDL: an intermediate representation and the passes over it.¶
It does not define a new CDDL dialect, propose new syntax, or extend the language. Every example is CDDL as specified by [RFC8610], [RFC9165] and [RFC9682].¶
It does not specify an intermediate representation normatively. Appendix A describes one, because the open issues in Section 5 were found by building it and the level of detail required by an implementation makes the substance of the questions easier to assess, but nothing in this document requires that design or any other.¶
It does not resolve the issues raised in Section 5. Where a position is offered it is marked as the author's, and the reasoning is given so that it can be disagreed with, but resolution is properly the role of the working group through clarification of text in the relevant normative specification.¶
The guidance and the questions come from implementing a CDDL compiler and measuring it against a corpus of CDDL extracted from published RFCs and active Internet-Drafts. Appendix B describes the corpus and the method. Quantitative claims in this document are from that single implementation and that single corpus, and are stated with the corpus they were measured on so that they can be checked or contradicted. Where an analysis is incomplete, its numbers clearly marked as lower bounds.¶
Two observations relate to other implementations, in Section 6.2 and Section 6.3. They are stated as such, and the implementations are not named: in each case the point raised is a failure mode that any implementation of CDDL can reach, and attaching it to a particular tool risks it being read as a report on that tool rather than as a hazard to design against.¶
Section numbers in RFC references are given explicitly because several of the passages at issue are in appendices that are easily overlooked.¶
This document is informational. It places no requirements on implementations and deliberately uses no normative key words: the guidance in Section 3 is advice about how to get efficient generated code from a suitable tool, not conformance language, and the options in Section 5 describe text the working group might wish to write.¶
The following terms are used:¶
An implementation that decides whether a data item matches a CDDL specification. A validator is a matcher.¶
An implementation that reads a CDDL specification and emits source code (or a table) that encodes or decodes conforming data items.¶
A decoder that reads its input once, in encounter order, with working memory bounded by a constant chosen at compile time, which cannot re-read a byte it has consumed. This is the code shape a constrained target often requires.¶
Reconsidering a matching decision previously taken. A one-pass decoder cannot backtrack, so a schema that requires it cannot be compiled to a single pass without either buffering the input or restarting the decode.¶
The compile-time decision of how a matcher selects among the arms of a type choice or the entries of a group at run time, for example a jump table on the CBOR major type, or a sequence of trial matches in order.¶
Of a type choice, that its arms can be shown at compile time to be pairwise disjoint under some stated test, so that dispatch can select one arm without trying another. The question of what "under some stated test" might mean is the subject of Section 5.2.¶
The initial byte of a CBOR encoded data item together with its argument (Section 3 of [RFC8949]). The major type, a tag number, an integer value, and a string's length all live in the head.¶
Used interchangeably for a CDDL document or fragment.¶
Strongly Connected Component. In a directed graph, two nodes are mutually reachable if there is a path from each to the other. An SCC is a maximal set of nodes in which every node is reachable from every other.¶
A generator reads a CDDL specification and emits a decoder, an encoder, or both. The decoder is in general the harder case and the rest of this section is largely about it.¶
The target shapes the problem. On a large host for which performance is not a significant issue, a decoder may buffer the input, build a general CBOR value tree, and then match the tree against the specification at leisure; that is what a validator does, and it makes almost every question in Section 5 moot. On a constrained target, or one for which high-performance decoding is a strong requirement, the decoder is normally expected to:¶
read the input once, in order, without storing it;¶
use working memory bounded by a constant known at build time (or bounded by concurrent throughput requirements);¶
contain no allocator (or allocate sparingly), and borrow from the input buffer rather than copying;¶
and have a code footprint proportional to the specification rather than to a general CBOR engine.¶
Those constraints are what make the specification's matching semantics a code-generation question. A one-pass decoder cannot try an alternative and then try another, because trying the first consumed input it cannot get back. Thus, for every point where the specification permits more than one way to proceed, the generator must either prove at compile time which way to go, emit a decoder that buffers, or refuse the specification. All three of those are acceptable outcomes; silently emitting a decoder that is right most of the time is not, and is the failure mode this document is most concerned with.¶
Nothing about the decoder code shape can be decided from the concrete CDDL syntax. Before any analysis, a generator has to reduce the specification to a form in which every name stands for something known. In practice that means:¶
Name resolution. Every typename and groupname bound to its rule.¶
Extension collection. All /= contributions to a name merged into one
ordered type choice and all //= contributions into one ordered group
choice. Appendix C of [RFC8610] permits this explicitly: a number of
such rules "could be replaced by collecting all the right-hand sides and
creating a single rule with a type choice or a group choice built from the
right-hand sides in the order of the rules given".¶
Kind inference. For each rule, determine whether it denotes a type or a group. Appendix C of [RFC8610] states the problem — "whether the name defined by a rule stands for a type or a group isn't always determined by syntax alone" — and gives no algorithm. See Section 5.5.¶
Generic expansion. Each distinct instantiation expanded once. See Section 5.10 on termination.¶
Group splicing. Group references resolved into the groups that include
them, and & enumerations reduced to the value choice they denote.¶
Prelude. The Appendix D of [RFC8610] prelude lowered through the same
path as the user's rules, so that uint is major type 0 and biguint is a
tag-2-wrapped byte string because Appendix D says so, rather than because
the generator has a second, hand-maintained copy of the prelude. A generator
that hard-codes a mapping from prelude names to target types will sooner or
later map biguint to a 64-bit integer and silently truncate a bignum.¶
The basis for the above scheme is one sentence in Appendix C of [RFC8610],
about the rule production:¶
A rule defines a name for a type expression (production "type") or for a group expression (production "grpent"), with the intention that the semantics does not change when the name is replaced by its (parenthesized if needed) definition.¶
That sentence specifies that inlining, splicing and instantiation are semantics-preserving rather than a reinterpretation, and it is the foundation of any useful CDDL compiler.¶
One caveat on splicing. A group reference cannot be flattened into its referrer
unconditionally. An occurrence indicator applies to the whole group entry it
precedes: per Section 3.2 of [RFC8610] such an entry "matches sequences of
name/value pairs that are composed by concatenating a number of sequences that
the basic group entry matches". So * ( a, b ) admits a, b, a, b but not
a, a, b, while the flattened * a, * b admits both. Flattening is sound only
where the occurrence is exactly once and no cut crosses the boundary.¶
With names resolved, a generator computes facts about the specification. The set below is what the author found necessary; Appendix A.4 has more detail.¶
Reference-graph for strongly connected components. Identifies which rules are recursive. This bounds splicing, decides which rules must become functions rather than being inlined, and is the only sound termination condition for several of the passes above.¶
Possible major types per node. An 8-bit set. Disjointness of two nodes at this level is a single bitwise AND, which is why this is the first thing to compute.¶
Refined first sets. Major type refined by tag number, by literal value, by string length, by container shape. This is the input to dispatch.¶
Nullability and emptiness. Whether a node can match nothing, and whether a group can match an empty sequence. This is required to decide whether an occurrence's lower bound is satisfiable, and to prune branches that cannot match.¶
Representation and lifetime. Whether a decoded value can borrow from the input or must be copied; whether a field is optional in the target language or has a default. For a recursive specification this must be a fixpoint over the SCCs; computing it by traversal per field gives the wrong answer on a cycle.¶
Size estimate. Used to decide whether to inline a subtree or emit it as a shared function.¶
Appendix C of [RFC8610] fixes the semantics of a type choice: "The choice uses PEG semantics as discussed in Appendix A: the first choice that matches wins." This means the result of matching is unique even where several arms would match. Trying the arms in order is therefore always correct, and compiling a choice to a jump table is an optimisation rather than a change of meaning.¶
What is not covered in normative text is any notion of a choice whose arms are disjoint. That is Section 5.2, and it is the question to which a generator most needs an answer: trying the arms in order is something a one-pass decoder cannot do.¶
To make the question concrete it helps to order candidate tests by what the decoder must hold in memory to apply them. The author's implementation uses six items obtained from three locations:¶
| Item | Location | What the decoder must do |
|---|---|---|
| major type | head | Read the 3-bit major type of the head byte. |
| tag number | head | Read the argument of a major-6 head. |
| literal value | head | Read the argument of the head it has already decoded. |
| container shape | header | Read a container's element or pair count, or learn which keys it holds. |
| fixed array position | inner | Decode a fixed-position array element, then dispatch. |
| designated map key | inner | Find a named map key and decode its value, in an order the data model does not fix. |
The locations are the real implementation cost steps, and the split between the last two matters most. A fixed-position array element arrives before everything that depends on it, so a streaming decoder reads it, dispatches, and continues with no buffer. A map member key may arrive last, because [RFC8949] does not fix map ordering, so dispatching on a key means either buffering the whole map or assuming an order the data model does not guarantee. Those have different implementation complexity, and a determination that lumped them together would be choosing against the cheaper one by accident.¶
The whole head item is one read. In CBOR the major type, the tag number, an integer's value and a string's length are all in the head and its argument, so "major type, then tag, then literal value" is not three tests but one decoded head inspected three ways. This is what shapes the author's view on Section 5.2.¶
Where a choice cannot be dispatched, an ordered fallback is correct and must remain available: it is [RFC8610]'s semantics, not a failure. What a generator should provide in such a case is a diagnostic naming the two overlapping arms, so that the CDDL author learns the specification has left the cheap subset and can consider whether this is important in the intended application.¶
Map matching is where the normative text is least clear for implementing a generator; the problem is multiplicity: [RFC8610] defines map matching twice, in two places, and the definitions are not equivalent. Section 5.3 sets the issue out in more detail. This subsection describes what a generator must do.¶
Appendix C of [RFC8610] is declarative: a map expression "matches a valid CBOR map the key/value pairs of which can be ordered in such a way that the resulting sequence matches the group expression". That is an existential quantifier over orderings, a search.¶
The search can be solved in polynomial time. While "Exists an ordering" reads as factorial, it is not: assigning the map's members to the group's entries, subject to each entry's occurrence bounds, is a degree-constrained bipartite matching problem, solvable in polynomial time by max-flow. The members are one side, the entries the other, an edge exists where the member's key matches the entry's key type and its value matches the entry's value type, and each entry's degree is bounded below and above by its occurrence indicator. This holds as long as each entry's value type can be tested independently of the assignment; a nested group with its own choices can reintroduce a true search, and that boundary is an obvious place for the working group to draw a line.¶
The normative semantics is tractable. The most common implementation in existing tools — walk the entries, claim the first unclaimed member whose key and value match, never reconsider — is an unforced incompleteness rather than a necessary compromise. It is still the most reasonable choice for a one-pass decoder, which cannot buffer the map at all; but a host-side validator need not have this limitation.¶
For a generator, a map compiles into three parts:¶
A key index. For integer keys, a dense or sparse jump table. For a small set of text keys, a perfect hash, or a length-and-first-byte prefilter that avoids most comparisons. This is where G7's integer keys pay off most.¶
A per-entry satisfaction record. Which entries have been satisfied, which are still open, and which are over their upper bound. For a map whose entries are all specific keys plus disjoint wildcards (G9), this is a bitmap and the assignment can take place immediately.¶
A failure rule. What to do with a member whose key matched an entry whose value type then rejected it. This is the cut, and it is the part that the normative text does not fully settle; see Section 5.3.¶
An array compiles to a sequence matcher over the group. Appendix C of [RFC8610] gives array matching as matching "a CBOR array the elements of which -- when taken as values and complemented by a wildcard (matches anything) key each -- match the group", so it is group matching with positions instead of keys.¶
The interesting content is occurrence. Appendix C of [RFC8610] says that an occurrence indicator "acts as a (possibly infinite) group choice that contains choices with the group repeated each of the occurrences times", and group choices use PEG semantics, first match wins. The order of that expansion's choices is not specified, which is the subject of Section 5.4.¶
Three possible shapes could be emitted by a generator:¶
A fixed-arity tuple, where every entry's occurrence is exactly once. The cheapest case: read the count from the header, check it, destructure.¶
A homogeneous loop, where one entry repeats and nothing after it overlaps. Also cheap, and the most common case seen in our CDDL corpus.¶
A state machine, where occurrences and choices interleave. Compiling the group to a nondeterministic finite automaton and determinising it where possible is both the cleanest semantics and the most efficient implementation; it also accepts more specifications than either PEG order does. It is, as Section 5.4 notes, a change in the normative model for this construct, from prioritised choice to language membership.¶
The automaton view has one property worth noting. An automaton that tracks its whole reachable state set accepts exactly when some expansion works, with no search written anywhere and with memory proportional to the specification rather than to the input. That is the backtracking reading, obtained for free. Committing to the longest run is a different traversal, not the same traversal with a flag, which means a generator cannot offer both readings by setting a bit, and has to be built to emit one or the other.¶
Group recursion breaks all three shapes, because it makes the element language context-free rather than regular. See G15 and Section 5.4.¶
Section 3.8.3.2 of [RFC8610] observes that "CDDL uses controls as its main extension point", Section 3.8 of [RFC8610] provides for further operators to be defined "by new versions of this specification or by registering them", and Section 6.1 of [RFC8610] establishes the IANA registry. A generator meets three categories.¶
Statically foldable. .size, .bits, .lt and relatives, .plus,
.cat, .det over singleton operands. These evaluate at compile time to a
value, a range, or a bit mask, and they improve the generated code: a
.size-constrained byte string is a length check against a constant, and
.size on an integer narrows the target type. .plus, .cat and .det
over non-singleton operands yield a set of literals, which is still a good
discriminator.¶
Representation predicates. .cbor, .cborseq, .b64u and similar
describe an embedded encoding. These are the best case for a generator,
because they mark a self-delimiting nested decode (G21).¶
Foreign grammars and anything unknown. .abnf, .abnfb, .regexp
embed another language. An unregistered or unimplemented operator is in the
same position from the generator's point of view: it knows a constraint
exists and cannot evaluate it.¶
For a validator, "warn and ignore" is a defensible implementation of the
third category. For a generator it is not. Ignoring .size does not produce
a decoder that reports it could not check the size; it produces a decoder
that accepts out-of-range data, with no run-time trace of the omission.
The author's position is that a generator should refuse unknown foreign
grammars, which is Section 5.7, and that the IANA registry should carry enough
structure for a tool to know what it is refusing and why, which is Section 5.6.¶
Two decisions are not about matching at all but dominate the usability of generated code.¶
Borrow or copy. A decoder that borrows text and byte strings from the input buffer needs no allocator, which can be the difference between usable and unusable on a constrained target. Whether a given field can borrow depends on whether the input outlives the decoded value, which is a property of the whole reachable subgraph from that field, so it has to be computed as a fixpoint over the reference graph's SCCs, not by traversal per field. A traversal that returns "no borrow needed" when it meets a cycle gives the wrong answer for any recursive specification that carries a string.¶
Optionality and defaults. An entry with occurrence ? becomes an
optional field. An entry with .default should fold the default into the
field rather than exposing the absence to the caller, because the caller
cannot usefully distinguish "absent" from "absent, meaning this".¶
The fold is only half of what .default asks for, and the other half is lost
exactly here. Section 3.8.6 of [RFC8610] defines .default as a variant of
.ne, where "the implied .ne control is there to prevent this value from
being sent over the wire": a generated decoder must therefore reject a
present value equal to the default, and a generated encoder must omit the
field when the value equals the default rather than encoding it. A generator
that folds present-and-equal-to-the-default into the same field as absent has
destroyed the distinction it needed in order to report the violation, so the
check has to be emitted ahead of the fold. Both halves are compile-time work
against a literal the schema supplies, which makes this an inexpensive
language constraint to enforce and, based on the author's comparison of
implementations, not always enforced correctly — see Section 6.2.¶
Collecting the above: a generator can emit a one-pass decoder for a specification when, at every point, the next step is determined by input already read. Four constructions break that, in rising order of implementation complexity:¶
A type choice whose arms are not disjoint at any location affordable to a constrained implementation (Section 4.4, G1-G6).¶
A map whose entries can claim the same member, where the choice of which one claims it affects the verdict (Section 4.5, G9-G11).¶
A variable-count group entry followed by an overlapping entry (Section 4.6, G13, G14).¶
A recursive group (G15).¶
For 1 to 3, the fallbacks are to buffer, or to refuse with a diagnostic. For 4 there is no bounded-memory implementation at all.¶
Case 1 can often be handled with a single-head lookahead buffer, which is a few bytes. Case 3 needs a buffer as large as the longest run the variable-count entry might take, which is unbounded in general. Case 2 needs the whole map. So "this specification needs backtracking" is not a single cost but three different costs, and a generator that reports which case applies is more useful to a CDDL author than one that simply reports a refusal.¶
The claims above about which constructions matter in practice come from measuring 286 closed CDDL schemas extracted from 54 RFCs and 11 active Internet-Drafts. Appendix B describes the corpus, the analysis, and its limits — in particular that the analysis is sound in one direction only, so every figure is a lower bound on what an implementation could achieve.¶
Of those 286 schemas, 174 contain a type choice, holding 498 choice sites between them. Cumulatively by discriminator strength:¶
| Discriminator strength | Location | Sites dispatchable | Schemas fully discriminable |
|---|---|---|---|
| major type | head | 48.4% | 36.2% |
| + tag number | head | 53.4% | 37.4% |
| + literal value | head | 83.7% | 79.9% |
| + container shape | header | 85.5% | 83.9% |
| + fixed array position | inner | 87.0% | 85.1% |
| + designated map key | inner | 87.3% | 86.2% |
"Fully discriminable" means every choice site in the schema dispatches at that strength or weaker, the property a conformance label would have to assert.¶
Three results impact the rest of this section.¶
The coarse discriminator alone is not viable. Major type only fully handles 36% of schemas. A profile set there would leave most real RFC schemas outside it, which makes the label useless for the purpose a label has.¶
The item that adds most is the literal value, and it is cost-free. Adding it to major-plus-tag takes the set of matched schemas from 37% to 80% — more than every other location combined — and it stays in the head location, with no buffering, no lookahead and no assumption about encoding order. The intuition that implementation cost rises with discriminating power is wrong for CBOR based on the sample corpus: the big win is in the head, which can be implemented with a single read.¶
The expensive discriminators have little benefit. Discriminating over the whole container band increases the matchable schemas from 80% to 86%: 11 schemas of 174, 18 sites of 498. The case of two maps distinguished by a designated key — the construction that forces buffering — accounts for just 2 sites out of 498, and in the one instance where analysis could not separate the arms, the root cause was a wildcard entry which could not have been separated by any key discriminator (G11).¶
What dominates the long-tail of CDDL that cannot be matched by a one-pass
implementation is not container-related. Counted by distinct choice site, the
leading obstacles are an arm whose type is a subset of a sibling's
— "fixed" / tstr and the like — at 25 sites, and two arms sharing
a major type with nothing finer available, at 19 sites; arrays follow at 17.
No single location of any single pass scheme addresses the first two, and
no discriminator over the encoding could, because the arms are not disjoint.
That is why G3 is in this document and why it is placed before the array
and map advice.¶
The array figure is narrower than its third placing suggests. Of its 105 pairs,
95 are in four of the per-document concatenations, and 89 of those in the
concatenations of [RFC9052] and its predecessor — two generations of
the same COSE document, where COSE_Sign, COSE_Sign1, COSE_Encrypt and
their siblings are all arrays (G4). Restricted to per-block files, the array
obstacle is 10 pairs at 6 sites. The specific shape commonly causing the
issue, two unbounded arrays both admitting the empty array, accounts for 12
of the 105 pairs and all 12 are one rule: [RFC9165]'s allowed-types,
the subject of Section 5.2 sub-question Q1c.¶
One further observation from the CDDL corpus: nine overlapping arm pairs
are two .size-controlled strings of provably different length, as in
[RFC8990]'s initiator (G6). A string's length is in its head, so
these are separable at header-band cost. The discriminator above has no
location for it. Nine pairs is more than the designated-map-key location
is worth, which suggests that if a profile is to include anything beyond
the head location, a length control has greater impact than a map key.¶
Each question below gives a motivating piece of CDDL, states what the normative text says, explains why, in the author's opinion, the text does not settle the question, and says what the consequence is for generated code. Options are listed with their trade-offs. Where the author has a position it is marked as such.¶
As noted in Section 1: CDDL was specified as a validation language but is increasingly used as a compilation source. Most of these issues are invisible to a validator and unavoidable for a generator. Several can be settled by minor text changes; two of them, Section 5.3 and Section 5.4, may require amending normative text rather than clarifying it.¶
The questions are numbered for reference within this document and the numbering carries no implied priority. Section 5.13 ranks them in order of importance for a code generator.¶
[RFC9290], Standards Track, which is well behaved:¶
oltext = text / tag38 tag38 = #6.38([tag38-ltag, text, ?tag38-direction])¶
and [I-D.ietf-rats-corim], which is not:¶
protected-corim-header-map = protected-corim-header-map-inline /
protected-corim-header-map-hash-envelope
protected-corim-header-map-inline = {
&(alg: 1) => int
&(content-type: 3) => "application/rim+cbor"
meta-group
* cose-label => cose-value
}
protected-corim-header-map-hash-envelope = {
&(alg: 1) => int,
&(payload_hash_alg: 258) => int
&(payload_preimage_content_type: 259) => "application/rim+cbor"
? &(payload_location: 260) => tstr
meta-group
* cose-label => cose-value
}
¶
Appendix C of [RFC8610] is explicit that a type choice uses PEG semantics, first match wins, so the result of matching is well defined even when several arms match. What is not defined anywhere is a notion of a schema whose arms are disjoint, that is, one that can be matched without trying an arm and abandoning it.¶
This is not an ambiguity as the text is complete and consistent. It is an absence. [RFC8610] had no reason to define a disjointness property, because a validator never needs one: PEG order gives it a unique answer and it has the data item in hand.¶
A generator cannot use that answer. A one-pass decoder that tries the first arm has consumed input it cannot return, so "try the arms in order" is not available to it; it needs to know, before reading anything, that one arm can be selected from what it is about to read. Today every generator invents its own notion of what it can handle, authors have no portable way to know whether a specification will compile, and the two tools have no vocabulary in common with which to explain a refusal.¶
A choice that is discriminable in the head location compiles to one head read and an indexed branch. A choice that is not compiles either to a chain of trial matches with a buffer, or to a refusal. This can mean the difference between a few hundred bytes of flash and an implementation a constrained implementer cannot realistically use.¶
The measurement in Section 4.10 says where this line can be efficiently drawn based on the evidence of existing normative and proposed CDDL. The head location — major type, then tag, then literal value — reaches 80% of real schemas at the cost of a single head read. The container location buys six further percentage points, and its most expensive location buys just two additional choice sites in 498.¶
(a) Status quo. No notion of discriminability; each tool defines its own accepted subset. Zero working group effort; no interoperability, and no shared diagnostic vocabulary.¶
(b) A normative compilable profile. A companion document defines a discriminator function and a profile such that a schema is in the profile exactly when all choice arms have pairwise-disjoint discriminators. Strong interoperability; requires the working group to fix the discriminator precisely, and any choice excludes some schemas people have already written.¶
(c) Informational guidance only. A document like Section 3 of this one, with no normative profile. Cheap and useful to authors; no interoperability guarantee.¶
(d) Author annotation. A registered control operator or directive by which an author asserts discriminability, which tools check. Explicit and opt-in, but adds additional rules to the language and still needs (b)'s discriminator definition.¶
Q1a. Must a determinism profile exclude extensible maps, or can it dispatch
on them? The CoRIM example above is the general shape: a designated-key
discriminator works only in a closed map, and a trailing
* cose-label => cose-value makes each arm admit every key the other
requires. COSE header maps are extensible by design, so this is the principal
map idiom in the groups this work targets rather than a corner case. Options:
require closed maps within a choice, which excludes COSE; let the author
nominate the discriminant key, making the dispatch declared rather than
inferred; or admit arm order as the tie-break for extensible maps
specifically, at the cost of a two-tier definition.¶
Q1b. Should any .feature "..." as a choice arm be discouraged, or blessed?
The CDDL corpus contains no bare any choice arm at all. Each of the four
choice sites, in [RFC9165] and [RFC9880] is any under the feature-gated
extension point, as in any .feature "allowed-type-extension".
So the question is not whether any should be a match arm but whether an extension
point can defeat single-pass dispatch. A profile could treat a feature-gated arm as
outside the choice if the feature is disabled, which has zero cost and is
probably what the authors intended; the alternative is to require that an
extension point be a socket, which has a well-defined shape (G16).¶
Q1c. Is [* a] / [* b] intended to be order-dependent? Both arms accept
the empty array, so the first wins for empty input under PEG semantics. The
only instance in the corpus is allowed-types from Section 4 of [RFC9165],
reused almost verbatim by [RFC9880]. The order is invisible to a validator —
both arms accept [] and the verdict is the same either way — and only
impacts a generator, which must pick one arm's decoder to run.¶
The author regards this as the most consequential question, and the one where the normative text may require amendment rather than clarification.¶
[RFC9880], Standards Track, states the normative syntax of the Semantic Definition Format as CDDL in its Appendix A. It contains:¶
jso-items = {
...
? ((type: "number" / "string" / "boolean" / "integer")
// compound-type
// $$SDF-EXTENSION-ITEMTYPE
// (type: text .feature "itemtype-ext") ; EXTENSION-POINT
)
...
}
compound-type = (
"type" => "object"
? required: [+text]
? properties: named<dataqualities>
)
¶
Match a map containing "type": "object". Arm 1's member key is the bareword
type, so by Section 3.5.4 of [RFC8610] it carries an implied cut. The key
matches, the cut locks in the selection, and the value "object" is not in
"number" / "string" / "boolean" / "integer". Per Section 3.5.4 of [RFC8610]
the entire map then fails to match; and per Appendix A of [RFC8610]'s
parenthetical about cuts, the alternatives of the containing choice are
disabled, so arms 2, 3 and 4 are never tried. compound-type is unreachable,
and so is the arm the document itself labels ; EXTENSION-POINT. The
construct is wrapped in ?, which Appendix C of [RFC8610] makes a further
containing group choice, so the zero-repetition escape is disabled too.¶
An interesting detail to note is compound-type's own first entry. It writes
"type" => "object" with an explicit => and a literal key, declining the
: shortcut and so declining the cut. [RFC9880]'s authors were aware of cut
semantics and were managing them by hand, but the precaution fails because
the cut that kills compound-type is in arm 1, not in compound-type. An
author following the specification carefully cannot avoid this.¶
[RFC8610] defines map matching twice, and the definitions are not equivalent.¶
Appendix C of [RFC8610], declarative:¶
a map expression, which matches a valid CBOR map the key/value pairs of which can be ordered in such a way that the resulting sequence matches the group expression¶
That is an existential quantifier over orderings, with nothing said about how the match is identified.¶
Section 3.5.3 of [RFC8610], procedural:¶
For each candidate name/value pair that the PEG algorithm would try, a matching member is picked out of the entire map. For certain group expressions, more than one member in the map may match.¶
That is a greedy pick with no reconsideration. The same section then prints
its own counter-example, do-not-do-this (G10), and observes that against
{3: 5, 4: 6} the first entry "might pick off the '3: 5', leaving '4: 6' for
matching the second one. Or it might pick off '4: 6', leaving nothing for the
second entry." Under Appendix C of [RFC8610] that map matches: the
ordering 3:5, 4:6 exists. Under Section 3.5.3 of [RFC8610] the outcome
is indeterminate. The disagreement is resolved by exhortation rather than by
ruling: "the specification writer is simply urged to not write pathologically
non-deterministic specifications".¶
Cut is then defined only in the vocabulary of the procedural reading. Section 3.5.4 of [RFC8610]:¶
A cut in this position means that once the member key matches the name part of an entry that carries a cut, other potential matches for the key of the member that occur in later entries in the group of the map are no longer allowed. In other words, when a group entry would pick a key/value pair based on just a matching key, it "locks in" the pick -- this rule applies, independently of whether the value matches as well, so when it does not, the entire map fails to match.¶
"Would pick", "locks in" and "the entire map fails" are all steps in a process the declarative reading does not have. Appendix C of [RFC8610]'s text addresses this with single clause whose operative word is left undefined: a key value matches its key type "unless a cut preceding it in the group applies".¶
Two further passages decide how far a cut reaches. Appendix A of [RFC8610], on prioritised choice:¶
The two alternatives listed are to be tested in left-to-right order, locking in the first successful match and disregarding any further potential matches within the choice (but not disabling alternatives in choices containing this choice, as a cut (Section 3.5.4) would).¶
The parenthetical provides clear statement about cut: a PEG prioritised choice does not disable alternatives in containing choices, and a cut does.¶
The occur production in Appendix C of [RFC8610]:¶
An occurrence indicator modifies the group given to its right by requiring the group to match the sequence to be matched exactly for a certain number of times (see Section 3.2) in sequence, i.e., it acts as a (possibly infinite) group choice that contains choices with the group repeated each of the occurrences times.¶
So an occurrence indicator is a containing group choice — the thing Appendix A of [RFC8610] says a cut disables.¶
Four separate reasons, in increasing order of severity.¶
The two definitions of map matching disagree, on the RFC's own example. A tool has to pick one, and the text does not say which is normative.¶
Cut has no declarative definition, and the candidate reconstructions are not equivalent. Supplying such a definition means choosing how "a cut applies" restricts the set of legal assignments. There are at least three possible, non-equivalent, answers.¶
(A) Static, key-type exclusion. For each cut-carrying entry E, delete from
the assignment relation every edge from a member whose key is in E's key type
to any entry textually after E. Computable without knowing the assignment,
hence compatible with the declarative reading, and it reproduces
Section 3.5.4 of [RFC8610]'s own example: in
{ ? "optional-key" ^ => int, * tstr => any } the edge from
"optional-key": "nonsense" to the wildcard is deleted, so the pair can only
go to the first entry, which requires int, and the map fails.¶
(B) Dynamic, picked-member exclusion. The cut excludes only the member the
entry actually claimed. This is a literal reading of the prose:
"other potential matches for the key of the member", definite and
singular, naming the pair just picked. But under a free existential it makes
a cut a no-op on any optional entry: the search simply declines to let
the first entry pick at all, since ? permits zero, the wildcard takes the
pair, and the map matches — the outcome Section 3.5.4 of [RFC8610] exists
to prevent. So reading (B) presupposes the procedural semantics of
Section 3.5.3 of [RFC8610] and is incompatible with
Appendix C of [RFC8610]'s.¶
(C) Mandatory claim. A member whose key is in E's key type must be assigned to E or to an entry at or before it, and the map fails if it cannot be. Agrees with (A) on the cases described above but differs in general, and states the rule as an obligation rather than as an edge deletion.¶
Readings (A) and (B) are indistinguishable for every :-keyed entry, which
is probably why this has gone unnoticed. The grammar is
memberkey = type1 S ["^" S] "=>" / bareword S ":" / value S ":", so a :
key is always a bareword or a literal value and therefore a singleton
type. With a singleton key type, "the member whose key matched" and
"every member whose key is in the key type" are the same member. Since
Section 3.5.4 of [RFC8610] makes : imply a cut, essentially all deployed
CDDL sits where the readings coincide. They diverge only for an explicit ^
on a type1 => member key with a non-singleton key type, such as
? tstr ^ => int, which appears nowhere in the 647-block corpus. The
question is therefore a non-issue against current CDDL, but a generator still
has to choose, and two generators choosing differently will emit decoders
that disagree on the same wire bytes.¶
The scope rule the text does give breaks a Standards Track schema. Two requirements, each in a published document, cannot both be satisfied:¶
Section 3.5.4 of [RFC8610]'s own extensible-map-example requires a cut
to survive the zero-repetition alternative of its own ?. Otherwise the
search declines to pick and the wildcard absorbs the pair, and the section's
stated purpose fails.¶
[RFC9880]'s jso-items requires a cut to stop at a // boundary.
Otherwise three of its four arms are unreachable.¶
Appendix C of [RFC8610] says those are the same construct.¶
So "a cut is scoped to the group-choice alternative it was written in" gives
the wrong answer for Section 3.5.4 of [RFC8610]'s example, and "a cut
escapes containing choices" gives the wrong answer for [RFC9880]. The
rule cannot be stated over the desugared grammar at all. It is expressible
only over surface syntax, distinguishing a // the author wrote from a group
choice introduced by expanding an occurrence indicator, a distinction
Appendix C of [RFC8610] explicitly denies. Settling this therefore means
amending Appendix C of [RFC8610]'s occur paragraph or
Appendix A of [RFC8610]'s parenthetical, not only clarifying
Section 3.5.4 of [RFC8610].¶
Every reading a one-pass decoder can implement loses
order-independence. The author's implementation currently takes the
surface-syntax rule: // is a cut barrier, an occurrence indicator is not,
and the cut claims the member the entry would have picked (reading (B)).
It accepts [RFC9880]'s jso-items and rejects
Section 3.5.4 of [RFC8610]'s example, which is the pair of answers the
published documents require. It is not free. For¶
m = { ? tstr ^ => int, * tstr => any }
¶
the verdict becomes sensitive to the order the pairs were encoded in:¶
| Input | search + backtrack | search + commit | greedy |
|---|---|---|---|
{"a": 1, "b": "x"}
|
match | match | match |
{"b": "x", "a": 1}
|
match | no match | no match |
Map matching is supposed to be order-independent by construction: that is the consequence of Appendix C of [RFC8610]'s "can be ordered in such a way". A cut on a non-singleton key type cannot be implemented in a single-pass decoder. Full backtracking is the only approach that works for this case. The author knows of no reading of the current text that gives both suggesting that this needs a determination rather than a convention, at least for single-pass decoders.¶
Confirming that the declarative reading governs, and stating the reduction, would let a host-side validator be complete at polynomial cost instead of greedy. Settling the cut rule would let a generator compile a map entry's failure path to a constant — fail the map, or skip to the next entry — instead of leaving it to each implementation's reading. And a precise cut rule is what makes the key-index optimisation in Section 4.5 sound: knowing that a member whose key hits a cut-carrying entry can go nowhere else is needed to allow an implementation to use a jump table with a fail-on-mismatch default.¶
Three things.¶
Which of Appendix C of [RFC8610] and Section 3.5.3 of [RFC8610] governs map matching.¶
Whether a cut's exclusion ranges over the key type or over the picked member.¶
Whether a cut's reach stops at a group-choice alternative, and if so whether occurrence-induced choices count as alternatives.¶
(a) Greedy-with-cut, normatively. Define map matching as a single left-to-right greedy pass and a cut as a commit point. Cheap to implement, bounded memory, matches what several implementations already do. Changes the language: it rejects data the current normative text accepts, so it would have to be an explicit and breaking update.¶
(b) Confirm search semantics and specify the algorithm class. Keep "exists an ordering" and state normatively that it is a degree-constrained bipartite matching problem with a given reduction, plus precise cut propagation rules. Faithful to the current text; makes a conformant implementation achievable; polynomial in time. Higher implementation complexity for a simple validator, and the cut rules will require careful drafting.¶
(c) A determinism constraint. Declare schemas on which greedy and search results differ to be ill-formed and require tools to diagnose this. Keeps implementations cheap and retains existing text, but "greedy and search differ" is itself a non-trivial static analysis, and it is a third notion of determinism to add to Section 5.2 and Section 5.4.¶
(d) A profile split. Core CDDL is greedy; a "full matching" profile is search. Lets constrained validators be simple and complete with respect to their profile. Two semantics for one syntax is a documentation and interoperability hazard.¶
Section 4.4 of [RFC9052], Standards Track, quoted in full under G13:¶
Sig_structure = [
context : "Signature" / "Signature1",
body_protected : empty_or_serialized_map,
? sign_protected : empty_or_serialized_map,
external_aad : bstr,
payload : bstr
]
empty_or_serialized_map = bstr .cbor header_map / bstr .size 0
¶
Appendix C of [RFC8610]: an occurrence indicator "acts as a (possibly infinite) group choice that contains choices with the group repeated each of the occurrences times". Group choices use PEG semantics, first match wins. The order of the group expansion's choices is not stated.¶
Under PEG semantics, order provides the answer. Consider [* int, * int]
against [1, 2, 3]. If the expansion of * is ordered by increasing
repetition count, the first entry matches zero times and the second takes all
three. If is it ordered by decreasing count, the greedy reading used by most
implementations, the first takes all three. Both are consistent with "a
group choice containing the group repeated each of the occurrence times"; the
text does not pick one. Where the two entries have different element types the
choice is observable, and for a generated parser it determines the control-flow.¶
Separately, if an occurrence is a group choice and group entries may
reference other groups, then an array group's element language is in general
context-free, not regular. a = (1, a) with [a] is syntactically legal
and the text does not forbid it. Implementations either nest to an arbitrary
maximum depth, which is non-conformance, or exhaust the stack.¶
[* int, * int] may seem easy to dismiss as a schema nobody would write.
Sig_structure from COSE provides a counterpoint. Its optional third element
sits in the middle of the array and its type overlaps the fourth element's:
the empty byte string satisfies both empty_or_serialized_map, via
bstr .size 0, and external_aad. So on the four-element COSE_Sign1 body
["Signature1", h'', h'', h''] a matcher that consumes the optional element
because it can is then one element short, and the only way to accept is to
backtrack. Measured with the author's implementation, the backtracking reading
matches and the committed reading does not; both verdicts are exact, so this
is a policy divergence and not an undecided case.¶
The overlap is also not a rare input. Section 4.4 of [RFC9052] says of the
external_aad field that "[i]f this field is not supplied, it defaults to a
zero-length byte string", and of the sign_protected field that if there are no
protected attributes "a zero-length byte string is used". So the two elements
whose types overlap both take the empty byte string as their default value:
the colliding case is the default, not the corner case.¶
[RFC9052] says sign_protected "is omitted for the COSE_Sign1 signature
structure", a correlation between element 2's presence and element 0's value
that cannot be expressed in CDDL, so the schema admits both and the matcher must
disambiguate by length. A one-pass verifier generated from this fragment
therefore accepts every multi-signer COSE_Sign and rejects every
COSE_Sign1, data-dependently, on the signature-verification path. See
Section 6.1.¶
Declaring sequence matching to be a language-membership test rather than a prioritised choice allows compiling the group to an automaton and determinising it. That is simultaneously the cleanest semantics, the most permissive matching (it matches whenever any split works), and efficient implementation: a state-set automaton has memory proportional to the specification, not to the input. It also removes the need for a generator to choose between two orders that the text does not distinguish.¶
Forbidding group recursion explicitly costs nothing identifiable and removes an unbounded-memory hazard from every implementation.¶
(a) Specify greedy (longest-first). State that occurrence expansion is
ordered by decreasing repetition count. Matches most implementations and most
author intent. Makes [* a, * b] with overlapping a and b behave
surprisingly but predictably. Simple.¶
(b) Specify lazy (shortest-first). Arguably the more natural reading of "repeated each of the occurrences times" as an enumeration. Contradicts known existing implementations.¶
(c) Declare sequence matching to be a language-membership test. Drop PEG ordering for occurrence; define array-group matching as "the element sequence is in the language of the group", with group recursion either forbidden or handled as a context-free membership test. Cleanest semantics, licenses automaton compilation, accepts the largest number of schemas. Changes the normative model for this construct and requires the group recursion question to be decided.¶
(d) Forbid ambiguity. Require that occurrence expansions be unambiguous and require tools to diagnose otherwise. Sidesteps the order question; a fourth notion of determinism; some real-world schemas become ill-formed.¶
Is a = (1, a) well-formed, and if so is [ a ] a context-free language?
Options: forbid group recursion explicitly, which every implementation
effectively does today by imposing arbitrary depth limits or crashing; allow
it and require a context-free membership test; or allow it only in the tail
position, which is equivalent to a regular language. The author's preference
is to forbid group recursion explicitly as there seems to be no need for it.¶
Section 5.2.1 of [RFC9528] and Appendix C.2 of [RFC9528], Standards Track, where the external authorization data field of Section 3.8 of [RFC9528] is given its CDDL:¶
EAD_1 = 1* ead¶
Appendix C of [RFC8610] is candid about the difficulty:¶
Note that whether the name defined by a rule stands for a type or a group isn't always determined by syntax alone: e.g., "a = b" can make "a" a type if "b" is a type, or a group if "b" is a group. More subtly, in "a = (b)", "a" may be used as a type if "b" is a type, or as a group both when "b" is a group and when "b" is a type (a good convention to make the latter case stand out to the human reader is to write "a = (b,)"). [...] this semantic processing may need to span several levels of rule definitions before a determination can be made.¶
It describes the problem precisely and specifies no algorithm.¶
Kind determines everything downstream of it: whether a bare Foo, inside
a map is a group inclusion to be spliced or a type to be matched;
whether ~Foo is legal; whether a rule can be the target of //=. An
implementation that guesses — for example by trying to expand the name
as a group and treating success as evidence — is substituting a heuristic
for an analysis, and two implementations with different heuristics can
disagree exactly in the cases the RFC flags as subtle.¶
The EAD_1 example shows the question is not confined to those subtle cases.
EAD_1 = 1* ead is a group rule by Appendix B of [RFC8610]'s second
alternative: assigng admits a plain =, and grpent begins with an
optional occur. A parser that commits to the type production on seeing
EAD_1 = parses 1 as a uint literal and then has nowhere to put the *.
The author's implementation rejected this schema until the case was found, so
kind inference decides whether a tool can read a Standards Track protocol's
extension schema at all. The case needs one token of lookahead past
the literal — a * there can only be an occur, because neither rangeop
nor ctlop can begin with * — which may be a useful data point for how much
lookahead CDDL should require of a conforming parser.¶
Note also that the RFC's own a = (b) example is genuinely ambiguous, not
merely hard: a may be used as a type or as a group, and which it is depends
on the use site rather than the definition. So kind may need to be a property
of a (rule, use-site) pair, or rules may need to be kind-polymorphic.¶
This is not a question of the efficiency of generated code, but more about whether code can be generated at all.A specified fixpoint would make the subtle cases portable, and would let a tool report an unresolvable kind as a diagnostic naming the use site instead of emitting a decoder for whichever reading it happened to take.¶
(a) Status quo. Each implementation infers as it sees fit; schemas are non-portable in the cases the RFC already flags.¶
(b) Specify a fixpoint algorithm. A normative least fixpoint over the
reference graph, with a stated rule for the ambiguous a = (b) case, for
instance kind-polymorphic, resolved per use site. Portability for the subtle
cases; moderate drafting effort; matches what a compiler must do anyway.¶
(c) Optional kind annotations. Promote the existing (b,) convention from a
human-readable hint to significant syntax. Small and backward-compatible, and
it eliminates the hard cases; existing schemas without the comma stay
ambiguous.¶
(d) Forbid the ambiguous forms. Simplest for tools; breaks existing schemas; loses genuinely useful kind-polymorphic rules.¶
[RFC9741], Standards Track, defines .printf, used as:¶
hexlabel<K> = text .printf (["0x%04x", K])¶
A tool that does not implement .printf can see the operator's name and
nothing else.¶
Section 3.8 of [RFC8610] provides that "[f]urther control operators may be defined by new versions of this specification or by registering them according to the procedures in Section 6.1", and Section 3.8.3.2 of [RFC8610] notes that "CDDL uses controls as its main extension point". Section 6.1 of [RFC8610] establishes the registry and states what a registration contains:¶
Each entry in the subregistry must include the name of the control operator (by convention given with the leading dot) and a reference to its documentation.¶
A name and a reference. Nothing more.¶
A tool meeting an unregistered or unimplemented operator currently has one safe behaviour available to it: warn and ignore. That is adequate for a validator and unsafe for a generator, as Section 4.7 sets out. To do better, a tool needs to know, for an operator it does not implement, at least the following: does it constrain the value or the representation? Is it statically foldable? Does it affect the discriminator of Section 5.2? Is it decidable at all?¶
That information exists in each operator's defining document, in prose. It is not available to a tool, and it is not in the registry.¶
This is not an ambiguity or omission in [RFC8610]; it is a missing facility. The registry was designed to record extension points for human readers, and the compilation use case would benefit if it was machine-readable.¶
Two effects. A generator that knows an unfamiliar operator is a value
predicate can at least emit a correct, albeit unoptimised, run-time check or a
principled refusal, rather than choosing between silence and rejecting every
schema that uses anything it has not been taught. And a generator that knows
an operator is statically foldable can fold it: .size becomes a constant
bound and narrows the generated integer type, .bits becomes a mask
comparison, and a computed literal becomes a literal — none of which have run
time cost.¶
(a) Status quo. Zero effort; every tool hand-codes a table of known operators and cannot behave safely on unknown ones.¶
(b) Add a structured "compiler profile" column. Each registration states: value or representation predicate; foldable or not; affects the discriminator or not; decidable or not. Low cost, immediately useful, gives tools a principled default for an unknown-but-registered operator. Requires agreeing the vocabulary and retrofitting existing registrations.¶
(c) Define operator classes and require new registrations to declare one. A small closed set: value predicate, representation predicate, string grammar, computed literal, feature gate, intersection. Easy to specify and implement generically, because a tool handles a whole class. The classes may not partition cleanly and the set may need future extension, which is itself a registry.¶
(d) Require a formal semantics per operator. Most rigorous; far more effort than the problem warrants.¶
(e) Let the schema carry author-supplied implementation code. Rather than
describe an operator's behaviour to a tool, have the schema contain it: a
fragment in the tool's implementation language, bound to the operator at its
point of use in the manner of a yacc semantic action, plausibly inside a
conventionally formatted comment so that existing parsers are unaffected. No
registry action is needed, and an author can use an operator the moment it is
invented. Declined below on three grounds: it scales as the product of
schemas and target languages, it has no evaluation model to attach to while
Section 5.3 and Section 5.4 are open, and it makes a schema executable
(Section 6.6).¶
time-zone-info = tstr .abnf
("time-zone-name / time-numoffset" .det IXDTFtz)
suffix-key = tstr .abnf ("suffix-key" .det IXDTF)
¶
An entire ABNF grammar, assembled by a computed-literal operator, embedded in a CDDL type.¶
Section 2 of [RFC9165] is explicit about tool limits:¶
For these operators, as with all control operators, targets and controllers are types. The resulting type is therefore formally a function of the elements of the cross-product of the two types. Not all tools may be able to work with non-unique targets or controllers.¶
So .plus, .cat and .det over non-singleton types yield a set of
literals, and the RFC anticipates tools declining. Separately,
Section 3 of [RFC9165] defines .abnf and .abnfb, which embed an ABNF
grammar, and Section 3.8.3 of [RFC8610] defines .regexp with XSD regular
expression semantics.¶
"Not all tools may be able to" indicates that declining is expected. It does not say what declining looks like. A tool may silently not enforce an operator constraint and still claim conformance. For a validator that is a soundness hole; for a generator it implies a decoder that accepts invalid data, with nothing at run time to indicate that a constraint was dropped.¶
As an example, a validator that ignores .regexp returns "valid" for an
item that does not match the specification. A wrong answer, but one answer,
delivered once, by a tool the user is actively running. A generator that
ignores .regexp bakes the wrong answer into a shipped product, where it
is exercised on every input forever and reported nowhere.¶
Indirectly: a requirement to refuse rather than ignore moves the decision to
compile time, which is where it belongs, and lets a generator fold the
operators it can evaluate aggressively without having to be conservative
about the ones it cannot. .size, .bits and the comparison operators all
fold to constants; the generated code is smaller and faster than a run-time
check.¶
(a) Status quo. "Not all tools may be able to" stands as the only guidance.¶
(b) Require explicit refusal. A conforming tool that cannot evaluate a control operator rejects the schema rather than ignoring the operator. Closes the silent-unsoundness hole at zero specification cost. Makes some tools reject schemas they currently process usefully.¶
(c) Define conformance profiles. For instance a core level without embedded grammars and a full level with them. Lets constrained tools be conformant at a stated level; another profile to document and track.¶
(d) Bound the cross-product. Specify a minimum cross-product size tools must support, or require singleton operands. Makes the computed-literal operators portably implementable; restricts a feature whose generality may have users.¶
Section 3.2 of [RFC9682] extends tag syntax to allow a type as the head number, motivated by [RFC9277]'s tag range. The RFC's own example is well behaved:¶
ct-tag<content> = #6.<ct-tag-number>(content) ct-tag-number = 1668546817..1668612095¶
[RFC9594], Standards Track, has the degenerate case:¶
extended_scope = #6.<TAG_FOR_THIS_SEMANTICS>(scope) TAG_FOR_THIS_SEMANTICS = uint¶
Section 3.2 of [RFC9682]: head-number = uint / ("<" type ">"). A tagged
type's tag number may be an arbitrary type expression.¶
There is no issue with the text; it is a consequence that was not discussed. A tag number is one of the most useful discriminators available, because a choice among differently-tagged items compiles to a clean jump table. A tag number given as a type may be a literal, a range, a union of ranges, or something not statically enumerable at all. In the first case dispatch is a table; in the second and third it degrades to a sequence of range tests; in the fourth it vanishes, and the arm becomes indistinguishable from every other tagged arm.¶
The two examples above are on opposite sides of that line. 1668546817..1668612095
is a range test. uint is every tag number there is, so an extended_scope
arm is not separable from any other tagged arm whatsoever. The author's corpus
measurement records six overlapping arm pairs attributable to a
statically-unknown tag number.¶
A guarantee that head numbers are statically enumerable would make tag dispatch always compile to a table or a small set of range tests. It would also let a generator report, at compile time, that a choice is not dispatchable because of how a tag number was written, which is actionable advice to the CDDL author.¶
(a) Status quo. Any type permitted as a head number. Maximum expressiveness; dispatch quality varies unpredictably with how the author wrote the tag type.¶
(b) Require statically enumerable head numbers. Restrict to literals, ranges, and unions of those. Guarantees tag dispatch always works; excludes head numbers computed through control operators or referencing non-trivial types. Believed to cover every real usage.¶
(c) Guidance only. Note that a non-enumerable head number defeats tag-based dispatch. Cheap; authors can still do it unknowingly.¶
.within and .and subtype assertions a tool may check statically?
One idiom, "this map must have at least one member", written four ways across six documents ([RFC9115], [RFC9290], [I-D.ietf-rats-corim], [I-D.ietf-rats-ar4si], [I-D.ietf-rats-coserv] and the EAT delta-assertion draft):¶
non-empty<M> = (M) .and ({ + any => any })
non-empty<M> = M .and ({+ any => any})
non-empty<M> = M .within ({+ any => any})
non-empty-array<M> = (M) .and ([ + any ])
¶
And, from [RFC9758], Standards Track, the case where the assertion is the only shape information available at all:¶
eid = $eid .within eid-structure eid-structure = [ uri-code: uint, SSP: any ] $eid /= [ uri-code: 2, SSP: ipn-ssp2 / ipn-ssp3 ]¶
Section 3.8.5 of [RFC8610] gives .and the semantics of intersection, gives
.within the same formal semantics, and then distinguishes them by intent:¶
While both forms have the identical formal semantics (intersection), the intention of the ".within" form is that the right-hand side gives guidance to the types allowed on the left-hand side, which typically is a socket (Section 3.9):¶
and continues, after an example:¶
For ".within", a tool might flag an error if type1 allows data items that are not allowed by type2. In contrast, for ".and", there is no expectation that type1 is already a subset of type2.¶
The example it gives between those two passages is
message = $message .within message-structure, extended by
$message /= [3, dough: text, topping: [* text]], which is essentially the eid
construction above. So [RFC8610] both anticipated the socket use case and
allowed for static checks.¶
Three things are missing from "a tool might flag an error".¶
It is permissive, so acceptance is tool-dependent. A schema whose
.within is violated may be rejected by one conforming tool and accepted by
another. That is a portability hazard of the kind Section 6.4
describes, and the term "might" is the issue.¶
No decidable fragment is identified. General subtyping over CDDL, with recursion and arbitrary control operators, is not decidable, so "might flag an error" cannot be strengthened to a requirement without first saying over what fragment. Identifying that fragment is what this question addresses.¶
Nothing says what a generator may conclude. A tool permitted to flag an
error is not thereby permitted to rely on the assertion. In the eid case that
is the whole value: $eid is a socket, so its plug set is open and a generator
knows nothing about its shape, except the .within, which says every plug is
an array whose first element is a uint. If a generator may rely on that, it
can emit a dispatch on uri-code, and a plug violating the assertion is a
diagnosable error at the point of extension. If it may not, it must treat eid
as any, which defeats dispatch for every choice eid appears in
(see also Section 5.2 sub-question Q1b).¶
The corpus evidence that the distinction is not understood by authors is the
non-empty idiom above: the same constraint, with no socket (so no subtype
intent to express) written as .within in one document and .and in
five. If .within carried consequences, this would not happen.¶
An intersection that narrows a type generally narrows the generated
representation and the discriminator: int .within 0..10 is a u8 with a
range check, not an i64. An intersection that is provably empty should be a
compile-time error, because today it manifests as a decoder that can never
accept anything. And a checked .within over a socket, as in the eid case,
turns an extension point from any, which defeats dispatch for its whole
choice, into a known shape.¶
(a) Status quo. "A tool might flag an error", with no fragment and no
statement of what may be relied upon. Zero effort; .within remains
interchangeable with .and in practice.¶
(b) Require a static check over a defined decidable fragment. Specify the
fragment — for instance non-recursive, with control operators restricted to
value predicates. Require tools to check within it, and state that a
generator may rely on the assertion. Makes .within do as it was intended
to; needs drafting work.¶
(c) Keep the check permissive but state the reliance rule. Leave "might flag
an error" alone, and add that a tool is permitted to use a .within
controller as an upper bound on the target's shape. Less effort than (b) and
captures most of the value for code generation, at the cost of leaving
acceptance tool-dependent.¶
(d) Deprecate .within. If the check stays optional and nothing may be
relied on, it adds nothing over .and. Honest simplification; loses
documentation value; breaks existing schemas.¶
Synthetic, because the corpus contains no instance, which is itself the main evidence that forbidding it costs nothing:¶
a<t> = [t, a<[t]>]¶
For contrast, the generic idioms that do occur, in [RFC9393] and [RFC9581], [RFC9781], [RFC9880] and [RFC9682] respectively, are all finite and all well-behaved:¶
one-or-more<T> = T / [ 2* T ]
JC<J,C> = JSON-ONLY<J> / CBOR-ONLY<C>
named<X> = { * text => X }
ct-tag<content> = #6.<ct-tag-number>(content)
¶
Every one takes its parameters as leaves. None instantiates itself.¶
Section 3.10 of [RFC8610] introduces generics by example. Appendix C of [RFC8610] gives their semantics, in one sentence:¶
Rule names can have generic parameters, which cause temporary assignments within the right-hand sides to the parameter names from the arguments given when citing the rule name.¶
Nothing in either place bears on termination.¶
a<t> = [t, a<[t]>] is polymorphic recursion: each instantiation requires a
new, strictly larger instantiation, so expanding instantiations at compile
time does not terminate. Every implementation the author is aware of expands
at compile time, so such a schema meets the tool as an out-of-memory
condition or an arbitrary depth cap, not as a diagnostic. Nothing in the text
says it is ill-formed, so a tool that rejects it is arguably
non-conformant, and a tool that accepts it is likely to crash with memory
exhaustion.¶
Not efficiency: diagnosability. Forbidding polymorphic recursion converts a crash or a hang into an error message, and the useful form of that message names the growing instantiation chain.¶
(a) Forbid polymorphic recursion. Require that the set of instantiations reachable from the root be finite, and require tools to diagnose. Enables compile-time expansion, which is what everyone does; costs authors nothing identifiable.¶
(b) Permit it and require a non-expanding implementation. Instantiation handled by type-passing or boxing at run time. Preserves full generality; raises implementation complexity for no known use case, and is hostile to code generation for constrained targets.¶
(c) Silence. Status quo: implementation-defined failure on a legal schema.¶
[RFC9052] again, where the answer is currently carried in prose alongside the CDDL rather than in it:¶
empty_or_serialized_map = bstr .cbor header_map / bstr .size 0¶
A generated decoder for this must decide whether the embedded header_map
may use indefinite-length encoding, whether its keys arrive in a defined
order, and whether integer values are minimally encoded. None of those is
expressible in the CDDL, and all three change the generated code
substantially.¶
Nothing, by design. CDDL describes the data model; Section 4.2 of [RFC8949] describes deterministic encoding; the relationship between a schema and an encoding profile is left to the protocol specification's prose. Section 3.2 of [RFC8610] says so directly:¶
Note that CDDL, outside any directives/annotations that could possibly be defined, does not make any prescription as to whether arrays or maps use definite-length or indefinite-length encoding. That is, there is no correlation between leaving the size of an array "open" in the spec and the fact that it is then interchanged with definite or indefinite length.¶
The clause "outside any directives/annotations that could possibly be defined" is [RFC8610] anticipating exactly this question and leaving it open. The separation it protects is real and worth protecting; the observation here is only that a generated codec needs the information and currently has to get it from somewhere other than the schema.¶
A generated encoder must choose definite or indefinite length for arrays, maps and strings; minimal or non-minimal integer width; and a map key order. A generated decoder for a constrained target benefits from being allowed to assume definite-length containers: it reads the count from the head and avoids the streaming state machine and the unbounded-nesting handling that indefinite length requires. Today that assumption cannot be expressed in the schema, so it becomes a generator flag, which means the schema is not a complete specification of the interface, and two implementations generated from the same schema with different flags do not interoperate.¶
Note that [I-D.ietf-cbor-serialization] addresses this interoperability question in depth and defines a number of serialization models.¶
"May I assume definite-length containers?" is the single highest-value assumption for constrained-target code generation. With it, a container decode is a counted loop. Without it, every container decode needs a streaming state machine, a nesting-depth limit, and a break-stop check on every element — which is both larger code and a larger attack surface (Section 6.3).¶
(a) Out of scope. Encoding profile stays in the protocol specification's prose. Preserves the clean separation; leaves generated codecs under-specified by the schema, and every generator invents a flag to specify what code gets generated.¶
(b) A registered control operator on a type. Expressible per type and uses the existing extension point; mixes encoding concerns into type syntax, which is the separation (a) is protecting.¶
(c) A module- or file-level directive. With [I-D.ietf-cbor-cddl-modules] arriving, a directive is a natural home. Keeps encoding out of type syntax while making it part of the schema artefact; depends on the modules work landing and on directives being the right granularity.¶
(d) A separate companion artefact. A profile document or annotation file alongside the CDDL. Zero language change; another file to keep in sync, and tooling must agree on its format, which is a new specification anyway.¶
~ unwrap when its target is a type choice?
From [RFC9090], whose object identifiers are a choice of two tags:¶
oid = #6.111(bstr) roid = #6.112(bstr) any-oid = oid / roid¶
~oid is settled: the tagged type, bstr. ~any-oid is not. The same shape
arises wherever a rule names a family of tags rather than one, which is the
ordinary way to write an extensible tagged type.¶
Section 3.7 of [RFC8610], in full:¶
The "unwrap" operator (written by preceding a name by a tilde character "~") can be used to strip the type defined for a name by one layer, exposing the underlying group (for maps and arrays) or type (for tags).¶
with the restatement in Appendix C of [RFC8610]:¶
an "unwrapped" group (see Section 3.7), which matches the group inside a type defined as a map or an array by wrapping the group¶
So ~ is two-valued, and each value is defined for a single wrapping
construct: one map, one array, one tag. The text says what one layer of a tag
is. It does not say what one layer of a choice of two tags is.¶
Three readings are each defensible from "by one layer":¶
Distribute. ~any-oid is ~oid / ~roid, so bstr / bstr. Natural, and
the only reading under which the operator is total.¶
Reject. A choice is not a wrapping construct, so there is no layer to strip. Consistent with the text naming exactly three targets.¶
Strip the choice itself. Read "one layer" as the outermost syntactic
layer, which here is the /, giving oid / roid unchanged: the operator
becomes a no-op.¶
The third is unlikely to be intended but is hard to exclude from the wording
alone. The first and second differ: under distribute, ~any-oid allows a
bare byte string; under reject, a schema using it is ill-formed. A choice
whose arms are a tag and a map is worse still, because the two arms unwrap
to different kinds — one to a type and one to a group — and distributing
then produces something that is neither.¶
The same question arises for a generic rule, ~p<int>, where the instantiation
must be expanded before the unwrap target is known. That is an ordering
constraint rather than a semantic gap, but an implementation that resolves ~
before expanding generics meets it as an unresolvable target.¶
[I-D.ietf-cbor-serialization] provides evidence that this question needs
further consideration, because its guidance on bignums points authors at
two prelude names that are type choices. It observes that the prelude's
bigint and biguint (Appendix D of [RFC8610]) do not describe which
of the available encodings a bignum is required to use, and recommends
that protocols use integer or unsigned and state the requirement in
prose. The prelude defines those as:¶
bigint = biguint / bignint integer = int / bigint unsigned = uint / biguint¶
So the recommended names are exactly the ones ~ has no stated meaning for.
A schema that wants the unwrapped form — the content byte string, with the
tag stripped — can write ~biguint today and has nowhere to go: ~unsigned is
this question.¶
[I-D.ietf-cose-cbor-encoded-cert] is the deployed instance:¶
CertificateSerialNumber = ~biguint¶
accompanied by prose stating that this deviates from
Section 3.4.3 of [RFC8949] and offering an alternative deterministic
encoding — a protocol that has thought about the question and written down
its answer. Following the new recommendation turns that line into
~unsigned, which under option (b) is ill-formed, and under option (a) is
uint / bstr: a choice of a number and a byte string, which is at least
discriminable by major type but is not what either document describes.¶
Two properties deserve consideration when determining this issue, as they are both consequences of unwrapping rather than of the choice:¶
~ strips the tag, so the wire item is a plain byte string and CBOR's
integer encoding rules never reach it. The schema deliberately declines
to model the serial number as a CBOR integer at all and is thus
unconstrained by encoding rules.¶
The unwrapped bstr also carries none of tag 2's own constraints. The empty
byte string and a leading-zero encoding both validate against it, where the
tagged form admits neither. A reading of ~ that distributes over a choice
inherits this: ~ is a widening operator on a tagged type, and every option
here has to be chosen in the knowledge that authors reach for it because
they want the bytes and not the tag.¶
A generator must know whether an unwrapped name yields a type or a group before it can emit anything at all, a choice that cannot be deferred to run time. "Distribute" also needs the arms to agree in kind, which is a well-formedness condition no text states, so a generator cannot currently report it as a conformance failure.¶
(a) Distribute over the choice, requiring the arms to agree in kind. ~ of
a choice is the choice of the unwraps; a choice whose arms unwrap to different
kinds is ill-formed and tools must diagnose it. Makes the operator total and
states the condition that makes it meaningful.¶
(b) Restrict ~ to a single map, array or tag. State that the target must
resolve to exactly one wrapping construct, and require a diagnostic
otherwise. Removes the ability to write ~any-oid, which no corpus
schema currently does — and also the ability to write ~unsigned, which
[I-D.ietf-cbor-serialization]'s guidance asks for
(Section 5.12.4). Option (a) does not restore it: ~unsigned
distributes to ~uint / ~biguint, and uint is not a wrapping construct, so
the arms cannot agree in kind. Under either determination that guidance needs
a companion spelling for the unwrapped case.¶
(c) Silence. Status quo: implementations diverge on a schema the text
appears to admit, some accepting a bare bstr where others reject the
document.¶
| Question | Topic | Author's view of priority | Cost to WG |
|---|---|---|---|
| Q5 (5.6) | Control-operator registry metadata | Highest leverage | Low |
| Q9 (5.10) | Generic instantiation termination | Easy win | Low |
| Q2 (5.3) | Map matching: search versus greedy; cut propagation | Most consequential | Moderate to high |
| Q3 (5.4) | Occurrence expansion order; group recursion | Most consequential | Moderate to high |
| Q1 (5.2) | Discriminability profile | High value for interoperability | High |
| Q4 (5.5) | Kind inference algorithm | Portability of subtle cases | Moderate |
| Q6 (5.7) | Minimum control-operator conformance | Soundness | Low to moderate |
| Q8 (5.9) |
.within / .and static checking |
Makes .within meaningful |
Moderate |
| Q7 (5.8) | Non-literal head-number dispatch | Narrow | Low |
| Q10 (5.11) | Encoding profile declaration | Valuable for constrained codegen | Moderate |
| Q11 (5.12) |
~ over a type choice |
Now reached by a published recommendation | Low |
Section 5.3 and Section 5.4 are the two cases where a determination could invalidate
implementation work, because they change what a generated matcher must do
rather than merely how well it does it. They are also the two where the text
appears to need amendment rather than clarification: Section 5.3 because
Appendix A of [RFC8610]'s parenthetical and Appendix C of [RFC8610]'s
occur paragraph together make two published documents' requirements
contradictory, and Section 5.4 because the expansion order is simply not stated.¶
CDDL is used to specify security-relevant formats: COSE structures, CWT and EAT claim sets, RATS evidence and attestation results, SCITT receipts. For these cases, "does this item match the specification?" is part of an authorisation or verification decision, and a tool that answers it wrongly represents a security defect rather than a quality-of-implementation issue. That makes any under-determinations in Section 5 potentially security-relevant.¶
A matcher that is incomplete relative to the normative semantics rejects data the specification admits. Where the matcher is on a verification path, that is a denial of service against valid inputs, and because the incompleteness is usually data-dependent, it is a denial of service that appears intermittently and is hard to attribute.¶
The Sig_structure case in Section 5.4 is a concrete instance, and one that evades
testing. A one-pass verifier generated from Section 4.4 of [RFC9052]'s CDDL
accepts every multi-signer COSE_Sign structure and rejects every
COSE_Sign1 structure. Both are valid per the schema, and which one arrives
depends on the peer. A test suite exercising COSE_Sign passes; deployment
against a COSE_Sign1 peer fails every signature check. Nothing in the
generated code indicates that a matching decision was approximated.¶
The converse direction is worse. A matcher that is unsound — that accepts data the specification forbids — moves a trust boundary. The map case in Section 5.3 is the live example: a greedy map matcher that ignores a cut accepts a map whose member has the right key and the wrong value type, where the correct answer is to reject the whole map. If the specification's purpose was to constrain what a downstream consumer will see, that constraint is gone.¶
The guidance for implementers is therefore: a generator should report which constructions in a schema it has approximated, and that report should reach the person deploying the generated code, not just the person who ran the generator. The guidance for the working group is Section 5.7: a tool that cannot enforce a constraint should be required to say so rather than permitted to ignore it.¶
Section 4.7 describes the categories of control operator a generator may be unable to evaluate. The security consequence is specific to generation rather than validation: where a validator's omission produces one wrong answer on one run, a generator's omission is compiled into a shipped artefact and exercised on every input thereafter, with no run-time trace.¶
The operators most likely to be dropped are the ones most likely to be
security-relevant. .size bounds a buffer. .regexp and .abnf constrain a
string that will be parsed, logged, or used in a path or a URI by something
downstream. .bits constrains a flag word. A decoder that accepts
out-of-range data for any of these is handing its caller a value its caller's
contract says cannot occur. [RFC9581]'s .abnf-constrained time zone names
are an example where the constrained string is subsequently interpreted.¶
The gap is not only confined to the operators that are hard to evaluate. The
author tested five independently developed validators against the worked
example in Section 3.8.6 of [RFC8610], where ? displayed-step: (number .gt
0) .default 1 carries an implied .ne that the same section says is there
"to prevent this value from being sent over the wire". Three of the five
accept a value explicitly sent equal to its declared default. One of those
three announces on every run that it is ignoring .default, and then
validates the base type, which admits the forbidden value, because the
forbidden value satisfies it. .default is neither ambiguous in the text nor
difficult to check: it is a comparison against a literal the schema supplies.
That it is the least reliably enforced control the author measured
suggests the hazard described here is not a consequence of evaluation
difficulty, and that a tool which announces an omission and proceeds
has moved the trust boundary as much as one that says nothing: Section 5.7
option (a), in the field.¶
A generator that emits a comment saying a constraint is unenforced is being honest to a reader of the generated source and silent to relying parties. The author's position, and the reason for G19 and Section 5.7, is that refusal is the correct behaviour for a generator and that the constraint should be expressed in a form the generator can enforce, or stated in prose as an obligation on the application rather than as a schema constraint that looks enforced.¶
Several of the readings discussed in Section 5 differ in their worst-case resource consumption, and the costly readings are reachable from attacker-controlled input.¶
Map matching. The declarative reading of Section 5.3 is an existential over orderings. Implemented naively as backtracking search it is exponential in the number of map members, and the input controls that number. Implemented as the degree-constrained bipartite matching described in Section 4.5 it is polynomial, and that is the main practical argument for stating the reduction normatively: a conformant implementation should not have to discover the polynomial algorithm independently, because the ones that do not will be quadratic or worse on hostile input. Note that greedy readings are linear; they are a cost of implementation completeness.¶
Occurrence. A backtracking implementation of Section 5.4 can be exponential in the number of adjacent variable-count entries. The automaton formulation is linear in the input and polynomial in the specification, with memory proportional to the specification. A matcher that accepts specifications from an untrusted source — a schema registry, a module import — should bound automaton size at compile time as well as bounding work at match time.¶
Group recursion. Section 5.4's sub-question is directed at an unbounded-memory hazard: a recursive group makes an array's element language context-free, and the implementations that enforce an arbitrary maximum depth are choosing an undiagnosed wrong answer over a crash. Forbidding group recursion removes the hazard from every implementation.¶
Indefinite-length encoding and nesting. Independently of CDDL, indefinite-length containers require a decoder to carry unbounded nesting state unless it imposes a limit (Section 5.11). A generator permitted to assume definite length emits a counted loop with no such state. Where that assumption is not available, the generated decoder needs an explicit nesting-depth limit, and the limit should be a generation parameter rather than an accident of the target's stack size.¶
Computed literals. Section 2 of [RFC9165] notes that .plus, .cat
and .det are formally functions over the cross-product of their operand
types. A tool that expands the cross-product eagerly can be made to allocate
a large set from a small schema. A bound, and a diagnostic when it is
exceeded, should be considered by any implementation that accepts untrusted
schemas — see Section 5.7 option (d).¶
Diagnostic construction. Every cost described above is in the matcher. One is not, and the analysis that identifies the others cannot see it: the work a matcher does to build the explanation of a failure. A matcher that accumulates a record per rejected alternative does work proportional to the number of alternatives rejected, which the input controls, and it does that work on inputs that ultimately match, because every arm of a type choice that fails before the matching one is a rejection to record. The author measured a deployed CDDL validator in which this accumulator was built by interpolating a representation of the accumulator so far: a successful validation of a 108-byte input against a six-arm choice of similar arrays built and discarded 178 MB of diagnostic text, and the same validation one element longer exhausted the memory of the machine. The matching implementation was linear throughout — one read per element, no search — so the cost was invisible to reasoning about what the schema requires.¶
Two consequences for implementers, neither specific to CDDL but both exposed by CDDL's type choices. A successful validation should not pay for failure diagnostics at all, which argues for accumulating the data a diagnostic would need and rendering it only when one is emitted. And a diagnostic should never be built from the diagnostics accumulated so far, which is a self-reference that turns a linear accumulator super-linear. The reason this is worth a paragraph rather than a footnote is that the trigger is the number of arms that fail before the matching one: it is absent from the small schemas a test suite uses, and an author who reorders a choice for readability can introduce it without touching a line of the implementation.¶
Where a specification is under-determined, two conformant implementations may disagree about whether a given item is valid. For a security protocol this is is a major issue: it is a parser-differential, and parser-differentials are a well-established source of authorisation bypasses. If a gateway validates an item and forwards it, and the gateway and the endpoint resolve Section 5.3 or Section 5.4 differently, an attacker who can construct an item in the gap gets it past the check and interpreted differently at the destination.¶
Three of the questions in this document have this character directly. Section 5.3 and Section 5.4 are about what matches. Section 5.5 is about whether a schema can be read at all, which is a weaker version of the same problem. Section 5.2 is not — PEG order makes the verdict unique — but a generator that silently restricts itself to a subset it can dispatch produces a decoder that rejects valid data, which is Section 6.1.¶
The practical mitigation available today is to identify and document the behaviour: a protocol specification that carries CDDL should say which reading it intends wherever the schema exercises one of these constructions, and the authoring guidance in Section 3 exists largely so that the question never arises. G8, G9, G10, G13 and G14 between them remove every construction on which the author's implementation observed a reading-dependent verdict.¶
An any arm, a * label => any wildcard, and an unplugged socket all admit
data the schema does not constrain. This is intended behaviour rather than a
defect. The security consideration is that the boundary is easy to lose track
of: a generated decoder will present such a field to its caller as an opaque
or dynamically typed value, and the caller's validation of it is outside
anything the schema or the generator can check.¶
Two consequences. A specification should prefer a socket to any (G16), so
that extensions have a declared shape and a generator can at least report
which shapes it has been given. A specification should also keep the key types
of extension regions disjoint from the keys it constrains (G9), so that an
extension cannot claim a member the specification meant to type, which is the
[RFC9290] trap under G8, in its security form: there, an attacker chooses
the value of a specified field freely, because a wildcard absorbs the member
when the declared type rejects it.¶
A CDDL specification is inert. A tool can fetch one from a specification repository, parse it, and validate an instance against it without any part of the document being able to direct the tool to do anything else. ABNF ([RFC5234]) has the same property, and Section 3 of [RFC9165] preserves it when it embeds an ABNF grammar in CDDL: the grammar arrives as a controller, i.e. a value rather than a program.¶
The property deserves to be explicit because proposals to extend CDDL's expressive power tend towards giving it up, and will likely continue; Section 5.6 option (e) is one. A tool that evaluates author-supplied code in order to decide whether an instance is valid executes an untrusted document as a condition of reading it. That is a vulnerability found repeatedly in deserialisers that resolve external references or instantiate named types from their input.¶
A matcher that reports why an item failed, with byte offsets and the offending value, is more useful than one that returns a boolean, and the author's implementation does so. Such a report quotes input data. In a deployment where the matcher's verdict crosses a trust boundary but its diagnostics do not — a server validating a client's submission, say — the diagnostic must be treated as sensitive, and an implementation should be able to emit the verdict without the detail. This is a general consideration for validating parsers rather than anything specific to CDDL, but generated decoders inherit it by default and should allow it to be turned off.¶
This document has no IANA actions.¶
Section 5.6 proposes that the CDDL Control Operators registry established by Section 6.1 of [RFC8610] carry additional structured metadata. Acting on that proposal would require IANA action, and would be the subject of a separate document.¶
This appendix is informative. It describes one compilation model in more detail than Section 4, because the questions in Section 5 were found by building it and because the detail makes them easier to assess. Nothing here is proposed for standardisation. A different model that answers the same questions differently would be just as good a source of evidence.¶
The model is an intermediate representation (IR) between the CDDL concrete syntax tree and the consumers that need resolved semantics: a matcher, a decoder generator, an encoder generator, and a serialiser that writes precompiled tables for targets without a parser.¶
A CDDL parser naturally produces a tree that mirrors the ABNF in
Appendix B of [RFC8610]: a type containing type1s containing type2s, a
group containing group choices containing group entries, a parenthesised
type that exists only for precedence. That tree is the right input for a
formatter, a syntax highlighter, and an editor, because it is in one-to-one
correspondence with the source text.¶
It is the wrong input for a generator: the transformations a generator
needs — instantiating generics, splicing groups, collecting /=
extensions, inlining — are all many-to-one on source spans. Performing them
in place destroys the correspondence the syntax tree exists to maintain.
Performing them into a separate structure keeps both, at the cost of an
explicit provenance map.¶
The justification for performing them at all is the name-substitution sentence in Appendix C of [RFC8610], quoted in Section 4.2. It is what makes the IR the same schema with names substituted rather than a different schema, and every pass below rests on it.¶
The IR's nodes mirror matching behaviour rather than grammar. The grammar's layering carries no semantic weight and is collapsed. What remains is a small repertoire:¶
What a data item is. Any; a major type with an optional additional-information selector; a literal; a numeric range; a tag with an inner type.¶
Composition. An ordered choice, per Appendix C of [RFC8610]'s PEG semantics; a map over a group; an array over a group.¶
Constraint. A single control node carrying an operator, a target and a controller.¶
Reference. A reference to a rule.¶
Groups are represented separately from types, because [RFC8610] treats them separately and because kind inference (Section 5.5) must be able to state which a rule is. A group is an ordered list of group choices; a group choice is a list of entries; an entry carries an occurrence, a key, a body, and an effective cut flag.¶
Two representation choices are worth recording because they were both initially made the other way.¶
Occurrence is total, not optional. An absent occurrence indicator is represented as the range 1 to 1, per Section 3.2 of [RFC8610]'s "as if 1*1 were specified". Representing it as an absent value forces every consumer to re-derive the identity case, and in the author's earlier implementation that produced a recurring class of bug in which "absent" and "exactly once" were handled by different code paths.¶
The cut flag is materialised on every entry. Per Section 3.5.4 of [RFC8610] a cut is a property of the group, propagating from an earlier entry to later ones. Computing the effective cut once, during lowering, is both cheaper and safer than leaving every consumer to re-derive it — which, in the author's experience of the code that preceded this IR, means no consumer derives it at all.¶
Ordered; each depends on its predecessors. All are sound, in the sense that each rests on an explicit statement in Appendix C of [RFC8610], and all are mandatory rather than optimisations.¶
Interning. Identifiers and literals to indices; the rule set to a map. This is what turns name resolution from a repeated linear scan into a hash probe.¶
Extension collection. All /= contributions to a name merged into one
ordered choice, all //= into one ordered group, in rule order, per
Appendix C of [RFC8610].¶
Kind inference. Type or group per rule, by fixpoint over the reference graph. See Section 5.5; there is no normative algorithm, so this is currently the author's choice.¶
Generic expansion. Each distinct instantiation expanded once, memoised on the rule and its argument nodes, with a bound that reports the growing instantiation chain rather than failing silently. See Section 5.10.¶
Group splicing. Group references, ~ unwrapping and & enumerations
resolved to a fixpoint, bounded by the strongly connected components of the
reference graph. Flattening a spliced sub-group into its referrer is done
only where the occurrence is exactly once and no cut crosses the boundary,
for the reason in Section 4.2.¶
~ is resolved here and not in the pass that lowers the entry, because
Section 3.7 of [RFC8610] makes it two-valued and which value it takes
depends on its target rather than on where it is written: unwrapping a map
or an array yields a group, to be spliced into the enclosing map or array,
while unwrapping a tag yields the tagged type, usable wherever a type
is and with no tag left on the wire. The section's own example has both —
~basic-header splices a two-element group and field4: ~time is
field4: number, the prelude's time being #6.1(number). An
implementation that commits to the group reading on syntax reports the tag
case as an error on valid CDDL, which is a mistake the author made and
Section 5.12 records the remaining corner of.¶
Prelude lowering. The Appendix D of [RFC8610] prelude lowered as
CDDL, through the same passes, into the same arena, before the user's
rules. A user rule referring to tstr then resolves by the ordinary
name-lookup path, and biguint is a tag-2-wrapped byte string because
Appendix D says so.¶
Shape normalisation. The grammar's layering collapsed; occurrence made total; the effective cut materialised.¶
Two properties of the pass pipeline were particularly beneficial and are recommended to those building similar tooling.¶
Lowering is total. It always returns a schema, recording every problem as a diagnostic rather than failing. A compiler that refuses to produce output cannot drive an editor, and the same IR serves the language server and the generators. Totality is also what makes a well-formedness self-check deployable as an assertion between every pass, which is what caught several pass-ordering mistakes during development.¶
Well-formedness conditions are stated over reachable nodes. An expansion pass that substitutes into copies leaves the generic template intact so that diagnostics can still name it, so a template's body legitimately retains parameter nodes forever. Stating the condition over all nodes rather than reachable ones makes every in-place rewrite a violation and makes dead-node elimination a correctness prerequisite rather than an optimisation.¶
An unresolved name is handled by narrowing the language rather than widening it. Section 3.9 of [RFC8610] says of a socket that "it is not an error if there is no definition for a socket at all; this then means there is no way to satisfy the rule (i.e., the choice is empty)". So any unresolved name becomes a declared socket with an empty body, which matches nothing, plus a diagnostic for names not spelled as sockets. A schema with a typo then still lowers to something a validator can check and report against.¶
Analysis results live beside the nodes rather than inside them, so that optimisation passes can invalidate them wholesale instead of maintaining them incrementally.¶
Strongly connected components of the reference graph, by Tarjan's algorithm. Used by splicing for termination, by inlining, and to decide which rules must become functions.¶
Major-type sets, as an 8-bit set per node. Disjointness at this level is one bitwise AND, which is why it is computed first and separately from the refinement below.¶
First-set refinement: major type refined by integer ranges, exact string sets with an open flag, tag selectors with an inner first set, and simple-value sets. This is the lattice that Section 4.4's ladder is computed over, and it needs intersection and emptiness tests, not just equality.¶
Nullability and emptiness. Whether a node matches nothing; whether a group can match an empty sequence. The second is needed to decide whether an occurrence lower bound is satisfiable.¶
Layout, as a fixpoint over the SCCs: borrow versus own, optional versus defaulted, lifetime need. See Section 4.8 for why this must be a fixpoint.¶
Size estimates, for the inline-versus-outline decision.¶
The outputs of the planning decisions in Section 4 — a dispatch table for a choice, a key index for a map, a sequence plan for an array — are held in side tables keyed by node, not as fields on the nodes.¶
The reason is worth recording because the first design had them inline. If a plan is a node field, two structurally identical maps with different plans are unequal, which defeats the structural sharing that makes generated code small, and it makes the serialised form depend on which optimisations ran. Keeping lowering's output canonical, and plans beside it, means the serialised IR is diffable and a golden file can pin a pass's output.¶
The plan repertoire is small:¶
Dispatch: ordered trial; a table indexed by major type; a table on tag number; a table on literal value; or a key-indexed form for map-shaped arms. The ordered form is not a failure mode: it is [RFC8610]'s semantics, and it must remain available.¶
Key index: dense or sparse integer table; perfect hash over a small text key set; or a length-and-first-byte prefilter.¶
Sequence plan: fixed-arity tuple; homogeneous loop; or automaton.¶
Three categories of thing cannot be fully resolved and must be representable anyway.¶
Unknown control operators. The registry grows without the tool changing (Section 5.6), so a taxonomy with one representation per operator makes an unknown operator unrepresentable and forces an escape hatch, at which point there are two code paths for the same syntax. A single control node carrying the operator by name is uniform, and an unrecognised-but-registered operator travels through lowering and serialisation intact. Which operators a tool must act on is Section 5.7; representing all of them is free.¶
Prelude types. There is no primitive-type repertoire to enumerate:
Appendix D of [RFC8610] defines every prelude name in CDDL, in terms of
major types: uint = #0, tstr = #3, biguint = #6.2(bstr),
float16 = #7.25. A hand-maintained enumeration of them is a second copy of
Appendix D, and it goes wrong in the direction described in
Section 4.2.¶
Nested groups under an occurrence. Flattening cannot be unconditional, for the Section 3.2 of [RFC8610] reason given in Section 4.2, so nesting is permanent rather than scaffolding. It is also what makes a recursive group rule representable at all, which matters even if the language ends up forbidding one (Section 5.4), because the diagnostic has to name it.¶
Lowering is many-to-one on source spans, so provenance cannot be an
afterthought if diagnostics are a feature. Every node carries at least one
span, and nodes created by instantiation or inlining carry an instantiation
path — "via Foo<uint> at 12:4, via Bar at 3:1" — so that a mismatch inside
an expanded generic can report both the definition site and the instantiation
site. The useful enforcement mechanism is to make the arena's insert operation
require provenance, so that a pass cannot create a node without it.¶
Prelude-derived rules are marked as such, so that a diagnostic never points at a byte offset in text the author never wrote.¶
Provenance belongs in a separate section of any serialised form, so that a constrained target can load the matcher tables without the span and path data.¶
The practice that produced most of the evidence in this document is worth describing separately, because it is inexpensive and it is likely to be useful to someone reading this appendix for implementation advice.¶
Where the normative text is under-determined, the implementation does not pick a reading. It implements all of them, behind a policy selector, and the test suite runs the whole corpus under every policy and reports the disagreements. For the two questions in this document that change what matches, that means two axes: map matching greedy or searching (Section 5.3), and occurrence committed or reconsidering (Section 5.4).¶
Four properties of that arrangement turned out to matter.¶
It makes the ambiguity explicit in the code rather than implicit in one chosen reading, so that a future determination is a configuration change rather than an archaeology exercise.¶
It produces the measurement. The counts in Section 4.10 and
Section 5.3, and the Sig_structure result in Section 5.4, are differences between
policies on the same input. Without the policies there is nothing to count.¶
The readings must be checked for monotonicity, not assumed. The suite asserts that a narrower reading only ever rejects what the broadest reading accepts. That assertion found a real defect: the committed engine initially ignored cuts, which made the narrow policy accept a map the broad policy correctly rejected.¶
Two readings may be two algorithms rather than one algorithm with a flag. For occurrence they are: an automaton tracking its whole reachable state set accepts exactly when some expansion works, which is the reconsidering reading with no search written anywhere, while committing to the longest run is a different traversal that no amount of state-set bookkeeping expresses. Discovering that late is expensive; it is worth assuming at the outset that a policy axis may require two engines.¶
A fifth property is about honesty rather than mechanism. A matcher that can return "I could not decide" must have every such verdict be reachable and every undecidable construct actually produce one. The author's suite asserts both directions — every construct the matcher cannot enforce reports a caveat, and no schema in the corpus reports one — because a caveat that is unreachable is a lie, and a construct that silently skips the caveat is worse.¶
This appendix is informative. It describes the corpus and the analysis behind the quantitative claims in Section 4.10 and Section 5, so that they can be checked, reproduced, or contradicted.¶
647 CDDL blocks extracted from 65 source documents: 54 published RFCs and 11
active Internet-Drafts in the CBOR, COSE, RATS and SCITT groups. Extraction
is automated: for documents with RFCXML available, by scanning for
sourcecode and artwork elements typed as CDDL; for older text-only
documents, by de-paginating the text, segmenting into paragraphs, keeping
paragraphs that contain a rule-definition line, and arbitrating with the
parser.¶
Each block is classified by running it through the implementation. A block that parses with no unresolved references is closed; one that references rules defined in another block of the same document is a fragment. Each document also contributes a concatenation of all its blocks, which is how a closed schema is recovered from fragments that reference each other.¶
Of the 647 blocks, 255 classify as closed and 335 as fragments; 48 do not parse at all, which is the false-positive rate of the text-era paragraph heuristic rather than a defect count, and 9 are source documents that shipped an unexpanded include directive. The 590 closed and fragment blocks, plus a per-document concatenation for each of 61 documents, are what is kept.¶
The headline numbers are the closed ones. A fragment's dangling references lower to an unresolved node, and an unresolved arm is not provably disjoint from anything, so fragments systematically under-report. There are 286 closed schemas: 255 per-block files and 31 concatenations.¶
Two cautions about the denominators, both of which affect how the numbers should be read.¶
Count choice sites, not arm pairs. A pair count grows as the square of choice width: one 14-arm choice contributes 91 pairs and thirteen two-arm choices contribute 13. Pairs measure how much work a determiniser has to refuse. Sites measure how many authoring decisions a profile would reject, which is the figure that bears on Section 5.2. The two give different rankings of the obstacles, and the site ranking is the one reported in Section 4.10.¶
Blocks and concatenations are measured as separate schemas, so an obstacle present in a block is counted twice. This inflates pair counts considerably for documents with many interdependent blocks.¶
The discriminability analysis is sound in one direction only: it may fail to prove a disjointness that holds, and it must never claim one that does not. Every figure is therefore a lower bound on what a given discriminator strength could achieve with a cleverer implementation.¶
That direction is tested rather than asserted: for every pair of arms the analysis calls disjoint, no corpus input may match both, checked against the matcher. At the time of writing that is 78 disjoint pairs over 3822 decided (pair, input) checks with no double match.¶
The analysis is also pure: it computes the partition and discards it. It deliberately does not emit a dispatch table, because doing so would commit the implementation and its serialised form to a reading of Section 5.2 before the working group has taken one.¶
One concrete illustration of the lower-bound caveat, because it changes how
much weight the smallest number should carry. Getting the designated-map-key
rung above zero at all required teaching the analysis that &(eat_profile: 265)
denotes the literal 265: real CDDL names its discriminant keys with an
enumeration rather than writing the number bare, and an analysis blind to that
idiom scores every genuine instance as zero. There may be further idioms it is
still blind to, and the map rung is the rung with the most room above it.¶
The policy-divergence figures — how often the readings of Section 5.3 and Section 5.4 disagree — are measured on a smaller, hand-written corpus of 117 schemas against 54 hand-encoded CBOR inputs: 6318 decided pairs, of which the greedy map reading rejects 3 that the searching reading accepts, the committed occurrence reading rejects 5, and the two together reject 8, or 0.13%.¶
Those schemas were written to provoke the constructs under discussion, which makes the measurement sharp and makes its sample small. The IETF corpus is an order of magnitude more CDDL by volume, and the author's sweep over it finds the divergences falling on the occurrence axis and not on the map axis, but that result is not a credible replacement, because the 54 CBOR inputs were written for the hand-written schemas and mostly fail to match a corpus schema for reasons no policy is answerable for. A divergence count over the corpus understates the question rather than settling it.¶
Closing that gap needs CBOR inputs generated per corpus schema, which the author has not done. Anyone wishing to put a number in front of the working group for Section 5.3 and Section 5.4 should treat that generator as the prerequisite, and should treat the 0.15% figure as what it is: a measurement on a corpus designed to exhibit the phenomenon, which bounds neither how common nor how rare it is in deployed schemas.¶
What the hand-written measurement does establish, and what is not sample
dependent, is that the divergences are not confined to contrived schemas.
The map cases are {a: int, b: int} and {a: int, * tstr => any} against a
map whose keys arrive in the other order — schemas anyone might write. A
one-pass decoder for those is correct on all the data an encoder that happens
to share its key order produces, and silently wrong on the rest. That is the
worst available failure mode: cheap to satisfy by accident, and expensive to
discover.¶
The questions in this document were found by implementing a CDDL compiler against the published corpus, and most of them are questions the authors of [RFC8610], [RFC9165] and [RFC9682] had already anticipated in the text, in several cases explicitly, as with Section 3.5.3 of [RFC8610]'s warning about pathological non-determinism and Section 2 of [RFC9165]'s observation that not all tools will be able to evaluate every operator. The precision of those documents is what made it possible to locate the gaps at all.¶
[RFC9880]'s Appendix A is used in Section 5.3 as evidence that the cut-scoping rules cannot be read literally. It is cited because it is careful: its authors were managing cuts by hand and were defeated by a cut in a different rule, which is the clearest demonstration available that the specification and not the schema needs attention.¶
This analysis would have been impossible without the assistance of Claude Code. While every issue raised has been carefully human-checked, the author is in no doubt that Claude found and classified issues that he would not have noticed.¶