Hugo Wikström Nattviken · proj@nattviken.com Draft, 2026-11-27
A QR code holds at most 2,953 bytes in binary mode and 4,296 characters in alphanumeric mode. Deployed designs for carrying structured data through one — the EU Digital COVID Certificate (HC1) and SMART Health Cards (SHC) — compress without a dictionary and therefore operate far below the achievable bound. We describe hZqr, which combines a measured, clustered dictionary library with a compact header and a radix-45-family payload encoding, and we evaluate it against those designs on 136 held-out documents drawn from seven payload families. hZqr produces a median of 746 QR characters where HC1 produces 1,450 and SHC 2,541 — factors of 1.94 and 3.41 — and fits 132 of 136 documents into a single symbol against 128 and 126. On FHIR JSON the full stack reaches QR version 9 where both deployed designs reach version 22.
The larger contribution is methodological, and most of it is negative. A proposed hexadecimal pre-transform enlarges every one of 2,560 documents tested. CBOR confers no benefit over minified JSON once either is compressed. Dictionary selection by measured saving beats selection by document type even on the types the names were chosen for. Crossing the design dimensions rather than measuring them one at a time shows they are not additive: the better a structure layer performs alone, the more of its work the dictionary has already done, so an elaborate typed encoding loses to simply omitting field names. And four of our own published figures were wrong — a structure layer measured at 35 % without a dictionary is worth 8.3 % with one and a working decoder; an overall saving of 31 % was 24.8 % after deduplication; and a summary table mislabelled which of its own measurements was which. We report the corrections and their sizes, because the size of the correction is the finding. We further show that the dictionary size cap the library was built under was folklore and costs a median 9.8 %, that a shortlist must score containment rather than similarity, and that confidentiality is achievable at exactly zero expansion while issuer authentication is not. All figures are measured on held-out data with the selection and evaluation sets disjoint.
Keywords — QR codes, dictionary compression, Brotli, HL7 FHIR, constrained channels, protocol compression
The two-dimensional symbol defined by ISO/IEC 18004 is a channel with a hard ceiling. At the largest version and the weakest error correction a QR code carries 2,953 bytes in binary mode, or 4,296 characters in alphanumeric mode. Everything placed in that channel competes for the same budget, and every byte not spent on content is spent on framing.
Two deployed designs carry structured health data through this channel. The EU Digital COVID Certificate encodes a CBOR Web Token, deflates it, and renders the result in Base45 (RFC 9285). SMART Health Cards deflates a JSON Web Signature, renders it in base64url, and maps each character to two decimal digits so the symbol can use numeric mode. Neither uses a compression dictionary.
That omission is the subject of this work. A dictionary trained on the kind of document being sent converts repeated structure — field names, terminology URIs, boilerplate — from transmitted bytes into shared prior knowledge. The cost is that both parties must hold the dictionary; the benefit, as we measure below, is a factor of three to four against the deployed alternatives.
Scope. hZqr addresses two channels. The first is the QR symbol, where the alphabet and the symbol version are the binding constraints and the measurements in this paper are taken. The second is device-to-device communication over a link whose protocol messages are themselves compressible and repetitive. The dictionary and header machinery is identical; only the final alphabet layer differs, and for a byte-transparent link it is omitted entirely, which removes the 3 % alphabet overhead described in §5.
Contributions.
QR alphanumeric mode encodes two characters into 11 bits from a 45-symbol alphabet. A character therefore costs 5.5 bits and carries at most log₂ 45 = 5.4919. Base45 maps two bytes to three characters, carrying 16/3 = 5.3333 bits per character and wasting 2.89 % of the channel. Binary mode wastes nothing but requires the scanner to handle the byte segment and any ECI declaration correctly, which is not uniformly true in the field.
Brotli (RFC 7932) accepts a raw dictionary that functions as an LZ prefix: back-references may point into it as though it preceded the data. Zstandard accepts trained dictionaries that additionally carry entropy tables. Deflate accepts a preset dictionary bounded by its 32 kB window, and the zlib container records an Adler-32 of that dictionary in the header, giving a dictionary identity check the other two formats lack.
An LZ prefix cannot be extended in place. Growing a dictionary shifts every back-reference distance and silently invalidates every previously encoded message. Dictionaries are therefore immutable, versioned artefacts, and this property, not compression ratio, dominates their governance.
7,906 documents in 29 evaluable families, after deduplication: HL7 FHIR R4 instance examples in JSON and XML, system XML, a generated catalogue of 1,000 document types, and 1,672 documents harvested from public APIs and repositories — JSON Schema, OpenAPI, npm and PyPI metadata, GBFS bicycle-share feeds, weather forecasts, RSS and Atom, Wikipedia summaries, SVG, GeoJSON, CSV, Markdown and plain text.
Every family contributes 16 documents to a held-out set, which is divided into a selection half and a validation half. The greedy selection in §3.4 sees only the selection half. Every figure reported for the final library is computed on the validation half, which nothing that chose what to ship has seen. This separation was introduced after observing that selecting 400 candidates against a few hundred documents and then scoring on the same documents is selection on test data.
Documents are represented by the set of their 70 most frequent identifier-like tokens, with Jaccard distance. 400 cluster centres are chosen by farthest-first traversal; every training document is assigned to its nearest centre; and one 32 kB Brotli raw dictionary is built per cluster by concatenating members round-robin in ascending size order, so that the cap is filled with a spread of document sizes rather than the first few large ones.
Farthest-first maximises coverage, not utility, and deliberately seeds outliers. It is therefore a candidate generator, not a selector, and the curve it produces is a lower bound on what better candidate generation would reach.
A document's payload under a library S is min(no-dictionary, min over S), because an encoder measures its options and takes the best. Selection is greedy facility location over the measurement matrix, which is within (1 − 1/e) of optimal for this objective and yields the entire size-versus-saving curve from a single matrix.
Greedy maximises total bytes saved and therefore starves a family with few documents however compressible it is. A per-family dictionary is admitted on top of the greedy library when, on the selection half, it beats the library by more than 5 %. §7.4 reports what this is worth.
The shipped library is 81 dictionaries, 2.53 MB, reducing the median payload on the validation half from 920 B to 728 B (20.8 %) and reaching 88.6 % of what all 401 candidates could attain, across 33 payload families. 30 of the 81 carry a structure transform chosen by measurement; 50 carry none; one carries markup-split-v1.
Two cautions attach to that headline. It is after the deduplication of §7.5, where the same pipeline previously reported 31.0 % — the difference is leakage, not regression. And it is not comparable to the 24.8 % reported before the weather corpus was split across eight providers: the median is taken over families, and the number of families changed. Per family almost everything improved; the aggregate did not, and the two should not be read as a trend.
Against 299 held-out documents, a library of 71 content-clustered dictionaries reduced the median payload to 330 B where a pre-existing library of 1,000 type-named profiles reached 662 B, at one quarter of the storage. Restricting the comparison to the 83 held-out documents whose types the type-named library was built for — its home ground — the clustered library still won, 486 B against 590 B.
That comparison confounds two variables: the clustered dictionaries average 28.0 kB and the type-named 9.1 kB. The honest claim is that a library of 71 large clustered dictionaries beats one of 1,000 small type-named dictionaries at a quarter of the storage, not that clustering beats naming at matched size.
Saturation. With 400 candidates, greedy ran dry after 139 dictionaries; 95 % of the attainable gain was reached at 64, 99 % at 108, 99.9 % at 128. The marginal value per dictionary falls by a factor of 240 across that range: 22.0 bytes each for the first eight, 0.00 for the hundredth through the hundred-and-twenty-eighth. An earlier run with 150 candidates appeared to saturate at 52; that was a property of the candidate generator, not of the corpus, and is reported here because it changed the recommended library size.
The library was built under a 32 kB cap per dictionary, a figure inherited from a source comment attributing it to Brotli's LZ window. Brotli's window at quality 11 is 4 MB, so the cap was a third of a number that was itself mistaken. Because raising it costs storage and nothing else, this is the cheapest unexamined parameter in the design, and it is the largest unclaimed gain we have measured.
Building each payload family's dictionary at twelve caps from 32 kB to 2,048 kB and measuring held-out documents against each gives a median improvement of 9.8 % and a mean of 18.5 % across 17 families. The spread matters more than the average: FHIR JSON improves 56.2 % and GeoJSON 2.6 %, and the knee — the smallest cap within one per cent of that family's best — ranges from 48 kB to 2,048 kB, a factor of 43. A single global cap is therefore the wrong instrument at any value.
Two of our predictions were refuted. We expected the assembly order to matter and tried descending size, typical-document-last and typical-document-first against the shipped ascending round-robin; all three were worse. And we expected structured data to keep benefiting from a larger dictionary while prose flattened early. The opposite holds: plain text is the best earner per kilobyte, and the driver is document size, not structure — a family of 4 kB documents has more to gain than a family of 400 B documents whatever is inside them.
A sizing policy outperforms a cap. Allocating clamp(5 % of available training material, 32 kB, 256 kB) buys a median 1.9 % for 1.99 MB of dictionaries, where reaching every family's measured best costs 18.86 MB. It also beats greedy marginal allocation at equal storage, which is not the expected result: greedy allocation is optimal when the marginal-return curves are convex, and these are not. Several families are flat for three successive caps and then drop, so greedy spends its budget on the families that improve soonest rather than on those that improve most.
None of this is shipped. It is reported because the parameter was folklore, and because a reader deciding how to size their own library should have the curve rather than our cap.
HZ1:R<K><ID>[.<V>]: is 13 alphanumeric characters, 71.5 QR bits, carrying 18 bits of information — 25 % efficient. Measured over 64 held-out documents it was 4.0 % of the printed string at the median and 22.8 % at worst, which is to say it costs most where the system performs best.
The dictionary identity is an 8-bit slot field. Values 0–251 name fixed library dictionaries; 252 introduces a 14-bit field, 253 a 24-bit serial, 254 a 32-bit serial, and 255 is reserved. Within the 14-bit field the first 256 values are themselves reserved for undefined functions, leaving 16,128 private dictionary serials at the cheapest tier.
The format version is not transmitted. It is a property of the dictionary, which the receiver looks up; re-stating it in every message restates what is already known.
Two implementation hazards were found by building it. First, in a radix encoding the leading digit is not under the encoder's control, and the QR alphanumeric alphabet contains a space at index 36; a leading or trailing space survives neither trimming nor transcription. Removing the space gives a 44-symbol alphabet at a cost of 0.59 %. Second, header widths of 8, 32 and 40 bits are all congruent to 0 modulo 8, so a decoder that infers the header width from the total bit length must additionally verify that the tag agrees with the width it is trying; without that check a reserved payload decodes as a nonexistent dictionary, silently.
Rather than encoding bytes pairwise, the header bits and the payload bits are converted as one integer into base 44, with a sentinel bit above the header so that leading zero bytes survive and the payload length is recovered from the bit length with no length field.
This recovers most of the 2.89 % Base45 discards and lets the header share the payload's rounding instead of paying its own. Not all of it: the alphabet is 44 symbols rather than 45, because QR's alphanumeric table places a space at index 36 and in a radix encoding the leading digit is not ours to choose — a leading or trailing space survives neither trimming, nor copy-paste, nor a scanner that strips whitespace. Dropping it costs 0.59 % of the character capacity, so the net recovery measured against Base45 on the same payloads is 2.3 %.
The cost is interoperability: the result is no longer RFC 9285, no off-the-shelf decoder reads it, and the conversion is bignum arithmetic over the whole message — irrelevant for payloads under a few kilobytes that are always read whole, and not irrelevant above that.
Over 64 held-out documents this framing moves 27 to a lower QR version and raises the largest payload that fits a single version-40-L symbol from 2,855 to 2,930 bytes.
The header described above carries a dictionary slot in a variable-width field with escape tiers for privately registered dictionaries. That design has a defect we found only by implementing it. Header widths of 8, 32 and 40 bits are all congruent to 0 modulo 8, so for any given total bit length several are arithmetically plausible, and a decoder that infers the width from the length must additionally verify that the tag agrees with the width it is trying. Without that check a reserved payload decodes as a dictionary that does not exist — silently, with no error.
Replacing the variable field with a flat 24-bit identifier removes the ambiguity rather than guarding it: one width, one modulo check, no tags to cross-check. The identifier denotes a combination — a dictionary, a transform and a codec — so the codec and the dictionary version leave the wire entirely, the latter because a new dictionary becomes a new identifier rather than a version bump of an old one.
Measured on the 64 held-out documents of §6:
| form | median characters | documents dropping ≥1 QR version | documents made worse |
|---|---|---|---|
HZ1:R<K><ID>: + Base45 | 326 | — | — |
| 8-bit slot, packed | 310 | 22/64 | 0 |
| 24-bit flat, packed | 314 | 18/64 | 0 |
The wider identifier costs 2.9 characters and gives back 4 of the 22 version improvements. Nothing gets worse, and the single-symbol ceiling still rises from 2,855 to 2,926 bytes. We judge an entire class of silent misdecode, in what will eventually be four independent implementations, worth more than four documents' worth of version improvement — but the trade should be stated rather than assumed.
A dictionary is trained on the bytes one implementation emits and matched against the bytes another emits. When the two disagree the dictionary does not fail; it quietly stops matching, and the symptom presents as "compression got worse" rather than as a bug. This failure mode has no analogue in ordinary serialisation work, where a disagreement surfaces as a parse error.
Writing a second implementation of the transform layer and asserting it against the first over generated vectors found three divergences, none of which would have raised an exception:
json.loads("1.0") is a float in Python while JSON.parse("1.0") is the number 1 in JavaScript with no float-ness left to detect. The two could not agree. The resolution carries each number's source text verbatim — both runtimes can produce it exactly — which removes number formatting from the format altogether and, as a side effect, fixes silent precision loss above 2⁵³ in any JavaScript decoder.sorted() is code-point order; JavaScript's default comparator is UTF-16 code-unit order. They differ above the Basic Multilingual Plane, so {"":1,"😀":2} sorts one way in one language and the other way in the other.Each was found by a vector file and a trap case chosen for it, not by use. A conformance vector set that omits the cases where implementations plausibly differ proves nothing, and the three above are offered as a starting list for anyone specifying a comparable format.
136 held-out documents, seven payload families, nine encodings, error correction level L. The hZqr rows were measured against an earlier 63-dictionary library; the shipped 87-dictionary library is better on every family measured, so these rows are conservative. QR versions measured with qrencode and read back from the rendered symbol rather than computed from the capacity tables.
| encoding | median QR characters | vs hZqr | fits one symbol |
|---|---|---|---|
| uncompressed, byte mode | 3,062 | 4.10× | 57/136 |
| deflate + Base45 | 1,427 | 1.91× | 128/136 |
| hexadecimal + deflate + dictionary | 2,210 | 2.96× | 121/136 |
| HC1 (CBOR + deflate + Base45) | 1,450 | 1.94× | 128/136 |
| SHC (deflate + base64url + numeric) | 2,541 | 3.41× | 126/136 |
| Brotli, no dictionary | 1,209 | 1.62× | 130/136 |
| hZqr, long header | 775 | 1.04× | 130/136 |
| hZqr, compact header, packed base-44 | 746 | 1.00× | 132/136 |
Uncompressed, 58 % of these documents do not fit in a QR code at all.
Median QR version on the four families with n = 30:
| family | deflate | HC1 | SHC | Brotli, no dict | hZqr |
|---|---|---|---|---|---|
| FHIR JSON | 22 | 22 | 23 | 20 | 9 |
| catalogue JSON | 22 | 22 | 23 | 20 | 16 |
| system XML | 21 | 21 | 22 | 19 | 16 |
| FHIR XML | 22 | 22 | 23 | 20 | 17 |
Codec selection. Against identical 32 kB dictionaries on 32 held-out documents, Brotli at quality 11 produced 57,542 bytes in total; Zstandard at level 19 produced 63,381 (+10.1 %), at level 22 with --ultra 63,356, and with --patch-from 63,405. Enlarging Brotli's window to 2²⁴ changed nothing, which is expected at a 32 kB dictionary and indicates that Zstandard's deficit is not a window effect. We attribute it to Brotli's mandatory 120 kB static dictionary, which Zstandard has no counterpart to.
Implementation cost. The compiled Brotli decoder is 55.7 kB against an encoder of 686.9 kB, a ratio of 12. A conforming decoder must additionally embed the 120 kB static dictionary, which dominates its footprint on constrained targets. The asymmetry suits this application: encoding occurs where the symbol is produced, decoding where it is read.
A proposal under consideration was to convert the document to hexadecimal before compressing. Across 2,560 documents in two corpora and three codecs, every document grew: by a median of 20.4 % under Brotli on one corpus and 34.6 % on the other. Hexadecimal doubles the symbol count while halving the information per symbol, which leaves the entropy nominally unchanged but moves every match length and back-reference distance into longer codes and destroys the byte-aligned structure Brotli's context modelling assumes. As a transport alphabet it costs a further 33.3 % of QR capacity against Base45.
The instinct behind the proposal was nonetheless partly correct. A table mapping field names to short codes is worth −18.4 % on FHIR; not transmitting the field names at all is worth −35.0 %. The saving comes from the table, not from hexadecimal.
HC1's CBOR encoding produced 1,450 median characters against 1,427 for minified JSON through the same deflate and Base45 — marginally worse. CBOR removes the quoting and punctuation that deflate removes for free and adds length prefixes that do not compress. The deployed certificate's advantage over naive JSON is its compression and its alphabet, not its serialisation.
hZqr's schema layer, which omits field names known to both parties, contributed nothing on FHIR: a library with the layer and one without produced identical medians. Schema inference succeeded for 0 of 32 FHIR resource types, in two failure modes — 17 cases of mixed types, which are FHIR's choice elements and union references, and 15 cases of a field inferred as required that a real document omitted, which is FHIR's near-universal optionality. Neither is recoverable from samples at any sample count; both are stated in the resource's StructureDefinition.
The prize behind the fix is smaller than we first reported, and it shrank twice.
§7.1 measured that not transmitting field names is worth 35 % — without a dictionary. Training one dictionary per arrangement on documents in that same arrangement, which is what the pipeline actually does, the structure layer is worth 18.3 % on top of the dictionary: the dictionary already encodes the field names as shared prior knowledge, so about half of the structural saving has been collected before the layer runs. Grouping values by field path buys nothing further on FHIR — 189 B against 188 B — because each document is one deeply nested record with no rows to transpose.
Both of those were measured with one-way proxies. A proxy emits the values and assumes the receiver already knows the shape, which is true only if the shape never varies; in FHIR it varies constantly through optional elements, choice types and arrays of differing length. Implementing a codec that actually decodes — 84 of 84 held-out documents round-tripping — the structure layer is worth 8.3 %, and the difference is the shape stream, 46 bytes of a 211-byte payload, which a proxy never pays for.
So the figure fell 35 % → 18.3 % → 8.3 %, and at no point did the code get worse. Each step was a measurement becoming honest: first the dictionary entered the comparison, then the decoder did.
Greedy facility location maximises total bytes saved and therefore allocates against document volume, not against compressibility. On the validation half, short comment records obtained 33.3 % from the best of 53 utility-selected dictionaries and 45.4 % from a single dictionary of their own, a swing of 12.1 points, and a dedicated dictionary for them survives the admission test in the shipped library.
Two more dramatic examples — weather forecasts at 57.2 points and bicycle-share feeds at 39.9 — are withdrawn. Both were measured before the deduplication of §7.5, and both families consist of documents that are near-copies of one another; after a near-duplicate-aware split, weather has no evaluable held-out documents at all and bicycle-share falls from 90.7 % to 8.3 %. The starvation effect is real and the mechanism is not in doubt, but this corpus cannot quantify it on the families where it looked largest.
The converse holds equally. FHIR JSON obtained 68.5 % from the utility library and only 20.7 % from a single dictionary of its own, because the library contains several specialised FHIR clusters and one per-family dictionary is too broad. Allocation per format is therefore not an alternative to utility allocation but a floor beneath it: broad heterogeneous families need several dictionaries that only measurement can find, and narrow homogeneous families need one that only a guarantee will give them.
A dictionary measured against near-copies of its training data reports a ratio no new document will see. An audit of the corpus found 92 byte-identical duplicates, one validation document with a byte-identical twin in training, and two families whose documents are 0.95-similar to one another — which were precisely the two families producing the largest reported savings. One RSS document compressed from 15,218 bytes to 24 at a similarity of 1.00: the same feed harvested twice under different URLs.
The pipeline now drops exact duplicates and admits a document to the held-out set only if its token-set similarity to every remaining training document is below 0.90. A family whose documents are all near-copies therefore yields no held-out documents and is reported as unevaluable rather than scored against its own twins.
| before | after | |
|---|---|---|
| overall median saving | 31.0 % | 24.8 % |
| bicycle-share feeds | 90.7 % | 8.3 % |
| weather forecasts | 55.8 % | unevaluable |
| CSV | 11.2 % | 0.0 % |
| FHIR JSON | 74.4 % | 65.7 % |
Six percentage points of the headline figure were leakage. We report the before-and-after rather than only the corrected number, because the magnitude of the correction is itself the finding: a compression result measured on a harvested corpus without deduplication should be assumed inflated until shown otherwise.
Crossing the structure layer, the dictionary and the alphabet on 84 held-out documents across 28 resource types, with every arrangement given a dictionary trained on itself:
| structure | no dictionary | with dictionary |
|---|---|---|
| plain | 1084 | 339 |
| keys-dropped | 695 | 278 |
| typed by inferred schema | 588 | 292 |
Main effects, each with the others at their best: the dictionary is worth 68.7 %, the structure layer 45.7 %, the alphabet 3.0 %.
The interaction is the result. Typing the values beats merely dropping the field names by ten points when there is no dictionary — 45.7 % against 35.9 % — and loses to it by four points when there is one, 14.0 % against 18.1 %. Sixty-nine per cent of what the typed layer achieves has already been collected by the dictionary before it runs, against forty-nine per cent for the simpler layer.
A dictionary is shared prior knowledge about bytes and a schema is shared prior knowledge about structure; in a document whose structure is repeated bytes, they describe the same redundancy. The typed layer additionally damages the dictionary, because replacing enum strings with indices and constants with nothing removes exactly the byte sequences the dictionary was built from.
The engineering consequence is the opposite of the intuitive one: with a dictionary present, the right structure layer is the simplest one.
The codec, as the fourth dimension. On the same documents, with each arrangement given a dictionary trained on itself:
| codec | plain, no dict | plain + dict | shape, no dict | shape + dict |
|---|---|---|---|---|
| brotli -q11 | 739 | 240 | 604 | 224 |
| zstd -19 | 884 | 256 | 759 | 236 |
| zlib -9 | 867 | 242 | 734 | 228 |
A hypothesis failed here that is worth recording. Brotli's lead is widely attributed to its mandatory 120 kB static dictionary of natural-language and web vocabulary, of which a shape stream and a value stream contain far less. If that were the explanation the gap should collapse under the transform. It narrowed from +6.9 % to +5.4 % — 1.5 points, the right direction and nowhere near enough.
More usefully: zlib is 1.0 % behind brotli once a dictionary is present. That corrects a figure we quoted earlier, which compared brotli with a dictionary against zlib without one. At a third of the decoder footprint, and with DICTID giving it the in-stream dictionary identity check brotli lacks, zlib is a live option for an embedded reader rather than a concession.
All four dimensions, each measured with the others at their best: the dictionary 67.5 %, the structure layer 35.9 % alone and 18.3 % on top of a dictionary — 8.3 % once a codec that actually decodes pays for the shape stream — the codec 1.0 %, the alphabet 3.0 %. They are not additive.
An earlier version of this table read "18.3 % alone and 6.7 % on top of a dictionary". Both labels were wrong. 18.3 % is E10's figure for the structure layer on top of a dictionary, which E12's crossed design independently measured at 18.1 %; the figure without a dictionary is 35.9 %. The 6.7 % has no measured source anywhere in the experiments and should never have been published. It is recorded here rather than quietly removed, because a mislabelled summary row that contradicted its own experiment's cells is the same failure mode as §7.5 and reached further.
Automatic profile selection requires a cheap pre-filter: scoring 81 — or 1,000 — dictionaries by running the codec with each is not available at packing time, so each profile carries a signature of key names and frequent words, and only a shortlist is measured for real.
The mechanism was inert, and repairing the obvious fault did not revive it. The shipped index carried no signatures at all, so the shortlist was always empty. Rebuilding them exposed a second fault in the scorer. Signatures are now read off the dictionaries themselves — a Brotli raw dictionary is the concatenated training bytes — which changes the size of the sets being compared from one document's key names to roughly fifty documents'. Jaccard similarity is defined on that ratio,
J(a, b) = |a ∩ b| / (|a| + |b| − |a ∩ b|),
so with |b| ≫ |a| the denominator is dominated by the dictionary's breadth and set size decides the ranking rather than the match. A dictionary is penalised for knowing more than the single document in hand. Containment asks the question a shortlist actually asks:
C(doc, profile) = |doc ∩ profile| / |doc|.
Ground truth here is measured rather than judged: for each document, Brotli is run with all 81 catalogue dictionaries and the smallest output defines the right answer. Over 22 documents, recall at a shortlist of 16 is 86 % for containment against 45 % for Jaccard, and containment produces no empty shortlist where Jaccard produces seven.
The lesson generalises past this system. A similarity measure between a query and a corpus summary is not the same object as a similarity measure between two documents, and substituting one for the other fails quietly — the shortlist is merely empty, which reads as "the feature does not work" rather than as a wrong formula.
A QR code is readable by anyone holding a phone, so every self-contained payload type described above is plaintext to a bystander. Carrying prescription or credential data therefore requires encryption, under a constraint the channel imposes rather than invites: the payload must not grow, because a symbol that no longer fits one QR code has lost the property the entire design exists to provide.
Zero expansion admits only a cipher that is a permutation of the message space. Over a variable-length message that means a wide-block tweakable pseudorandom permutation; an authentication tag, a transmitted nonce and a wrapped key each cost bytes, and there is no fourth option.
This is not a novel situation but a standardised one. IEEE 1619.2-2025, Wide-Block Encryption for Shared Storage Media, specifies EME2-AES for precisely this shape of problem, and its own rationale states the trade we arrive at independently: it favours fixed-size blocks without expansion, and offers an optional expansion mode where tamper detection is required. The constraint and its consequence are therefore the standard's position as well as ours — confidentiality is available at zero expansion, and detection is not.
This excludes RSA, and not marginally. An RSA ciphertext is the size of the modulus whatever the input; OAEP padding costs 2·hashlen + 2 = 66 bytes before anything else; and RSA-4096, the only modulus large enough to hold a median payload directly, caps the message at 446 bytes, below our median of 504. For real payloads RSA means hybrid encryption and a 256-byte wrapped key, 56 % of the median. X25519 with ChaCha20-Poly1305 costs 60 bytes, password-derived AES-GCM 44 bytes, and a length-preserving symmetric construction zero.
We specify hZqr-E1 as two layers, each with one responsibility:
write: M = Feistel(K_code, P) then C = M ⊕ pad read: P = Feistel⁻¹(K_code, C ⊕ pad)
The outer layer is a one-time pad as long as the payload, distributed with the profile's key. A pad used once is information-theoretically secure and length-preserving. The inner layer is a four-round unbalanced Feistel network keyed by a user-supplied code, with HMAC-SHA256 as the round function.
The choice of primitive is dictated by portability rather than preference. HMAC-SHA256 is the only keyed primitive present in Python's standard library, Node's node:crypto, Android's javax.crypto.Mac and a short portable C++ file. Python has no AES, which excludes HCTR2 and EME2 — both of which additionally require GF(2¹²⁸) arithmetic — and the NIST FF1/FF3 constructions. Selecting the primitive on the weakest implementation is what keeps four implementations in byte-for-byte agreement, and a disagreement in this layer does not raise an exception: it decrypts to garbage and presents as a wrong password. Four rounds rather than three because Luby–Rackoff yields a strong pseudorandom permutation, secure under chosen ciphertext, only at four, and a printed symbol can be photographed and modified at leisure.
A one-time pad is optimally secure and perfectly malleable: flipping a ciphertext bit flips exactly the corresponding plaintext bit. An adversary who cannot read a prescription can still alter a dose. Measured over 293 catalogue documents compressed with a matching dictionary:
| adversary action | pad alone | permutation | both |
|---|---|---|---|
| flip one chosen bit | 90/293 accepted | 0/293 | 0/293 |
| flip eight chosen bits | 0/293 | 0/293 | 0/293 |
| reuse one key across two codes | reveals P₁ ⊕ P₂ | no | no |
"Accepted" means the modified payload still decompressed and was therefore taken by a reader. The permutation eliminates the single-bit case because any change randomises the entire plaintext, which the plaintext's own redundancy then rejects: 0 of 40,000 random byte strings survived decompression, bounding that redundancy at ≥ 16.9 bits. The composition also degrades gracefully under the operator's worst plausible error, pad reuse, where a bare pad surrenders P₁ ⊕ P₂ and the composition does not.
| the adversary holds | work to recover the plaintext |
|---|---|
| neither the code nor the pad | information-theoretically impossible |
| the 50-bit code, not the pad | information-theoretically impossible |
| the pad, not the code | 2⁵⁰ scrypt evaluations |
The first two are not computational claims. For a 504-byte payload there are 2⁴⁰³² candidate pads, of which approximately 2⁴⁰¹⁵ decrypt the observed ciphertext to a byte string that decompresses; unbounded computation yields astronomically many equally consistent plaintexts and no means of discrimination. Holding the code without the pad gains nothing at all, which is worth stating as a design property: the pad carries the entire secrecy, and the code exists solely to resist the party that has the pad.
The third case is the only computation, and its cost is dominated by the key derivation — measured at 120 ms per scrypt evaluation at N = 2¹⁵, r = 8, which is 681 times the cost of the Feistel inversion. Assuming memory-bandwidth-bound scrypt at 8,736 evaluations per second on a 3.35 TB/s part, a 50-bit code requires 2,042 GPU-years, two years on a thousand GPUs and 7.5 days on a hundred thousand. Raising the code to 64 bits multiplies that by 16,384 at no cost in bytes or latency, whereas raising scrypt to N = 2¹⁷ multiplies it by four and quadruples a mobile client's memory requirement. Entropy is the cheap parameter; key-derivation cost is not.
The construction supplies confidentiality and tamper diffusion. It supplies no issuer authentication whatever: any party holding the key can produce a symbol that decodes correctly, and a verifier cannot distinguish it from a genuine one. This is a consequence of the constraint, not an oversight — a signature is incompressible evidence and must be transmitted.
A clinical suite therefore pays for what it needs: RSA-2048-OAEP wrapping an AES-256-GCM key together with an RSA-PSS-2048 signature, 544 bytes, which reduces the largest document a single QR code can carry from 2,929 to 2,385 bytes.
The choice of signature algorithm is constrained by deployed PKI rather than by cryptographic preference, and we were able to establish that constraint only partly. SITHS end-entity certificates are documented as RSA 2048–4096, which sets an RSA-PSS-2048 signature at 256 bytes; mobile SITHS is documented as also supporting ECDSA on P-256, whose signature is approximately 72 bytes DER-encoded. We found no primary specification stating what eIDAS qualified certificates require. We therefore report the RSA case as the conservative bound, and note that an ECDSA path, where the verifier's chain admits one, reduces the signature by a factor of three and a half. Ed25519 is not in evidence in either chain. An implementer must verify this against current Inera documentation: it is the one assumption in this section that we did not measure.
A signature-only variant costs 260 bytes under RSA, or approximately 76 under ECDSA, and merits separate consideration: a prescription that must be provably issued but whose contents are not secret from the holder of the paper does not require encryption at all.
Distributing a key also has a privacy cost that caching would reduce but not remove: a decoder that cached a key would read offline thereafter, so the issuing server would observe the first use and not every scan — still more than the other self-contained types disclose, and a property that belongs in the user-facing comparison rather than in a footnote. No decoder caches yet, so at present the server observes every read.
hZqr-E1 is implemented and carried on the wire as a fifth payload type, HZ1:E<KEYID>:, in which the six-character key id replaces both the codec letter and the profile identifier; the codec, profile, transform and dictionary move into the key record the decoder fetches. The consequence is that the encrypted form of a profile payload is one character shorter than the readable one — measured at 317 against 318 characters on a FHIR bundle — because the Base45 body is length-identical and the header loses a character. Against a self-contained packed payload, whose header carries no identifier at all, the same envelope costs five characters. A side effect of moving the profile identifier off the wire is that the kind of document is no longer legible from the symbol, which removes a leak the earlier design accepted.
Three key-distribution suites are implemented, distinguished by what can be withdrawn rather than by cipher strength: one in which the record holds no secret and the password is the entire key, one in which the record holds thirty-two secret bytes and deletion revokes every code under it, and one in which the record holds a one-time pad bound to a single payload. The key record is served publicly, necessarily — a decoder unable to resolve it cannot decode — so the password, which the issuing server never holds, is the only component that withholds the content from a reader who has both the symbol and a network. We therefore treat encryption without a password as obfuscation with revocation, and the implementation refuses it.
The corpus is not a sample of what is placed behind QR codes; it is a sample of what is freely available, and it is dominated by FHIR and XML because those are published in bulk. Families with few validation documents — plain text, CSV, PyPI — are reported for the shape of their behaviour and support no quantitative claim. Weather forecasts have none at all after deduplication.
No signatures are counted anywhere. HC1 and SHC carry COSE and JWS respectively, roughly 100–300 incompressible bytes, and hZqr carries none. Including them would widen the reported margin while raising a question this work does not answer.
All measurements are at error correction level L. A printed clinical artefact would plausibly require M or Q; the ranking is unaffected but every fits-in-one-symbol count would fall.
The hexadecimal encoding evaluated in §6 and §7.1 is a reconstruction from a written description, not from a reference implementation.
Dictionary selection is oracular: each document is measured against the whole library and the best taken. At this scale this is what an encoder does in practice — 784 ms single-threaded over 55 dictionaries, measured — so the oracle is realistic at this scale, and was not at the 1,000-profile scale it replaced.
A printed symbol must remain decodable for as long as the artefact it is printed on survives. Three properties follow and are not negotiable. Dictionaries are immutable: an LZ prefix cannot be extended without invalidating every message already encoded against it. Dictionaries are versioned, and every version is retained. Dictionaries are published independently of any implementation, so that a symbol printed today decodes without an account and without this particular server existing.
Encryption initially violated the third property, and the violation was the reason to change the construction rather than to qualify the property. We therefore specify two encrypted forms. In the fetch-free form the codec, the profile identifier, the dictionary version and a per-code salt are carried in the header, and the key is derived from a password the reader already holds; no record is stored and no request is made, so the third property holds unconditionally. The cost is six or seven characters of header and the return of the document-kind leak that moving the profile identifier off the wire had removed.
In the key-record form the symbol resolves a record held by the issuing server. Caching would reduce that dependency to a single fetch but cannot remove it, and a decoder that has not fetched before the key server ceases to exist is permanently unable to read the symbol; nor can the key be rotated, since for a printed artefact the key is its readability. What the dependency buys is revocation and an opaque envelope. Deployments that require the unconditional guarantee should use the fetch-free form, and deployments that require withdrawal should not.
The password is a property of the profile rather than of the code: a reader is provisioned once and thereafter decodes without interaction. The derivation is split accordingly, with the memory-hard step salted by the profile and cached, and a per-code salt mixed in by a single HMAC. A shared memory-hard derivation across a profile's codes is not a weakening, since those codes share a password and compromising one compromises all; the per-code salt exists to keep identical documents from producing identical symbols, which the key-record form, having no nonce, cannot avoid.
Admission to the fixed library should require evidence rather than assertion: a candidate dictionary demonstrating, on documents it was not trained on, an improvement over the dictionaries that already exist. The escape tiers of §5.2 exist so that the long tail need not be permanent — a dictionary serving a quarter of a byte on average and two hundred bytes to its own users belongs behind a private serial, downloaded by those who need it, rather than carried forever by everyone.
Compression for constrained symbolic channels is dominated by the dictionary, and the dictionary is dominated by how it is chosen — and, we now find, by how large it is allowed to be. That is the engineering result. The methodological one is that we were wrong four times, three of them in the same direction, and each time the error was a measurement that flattered the layer under test: a structure layer measured without the dictionary it would compete with, a corpus measured without deduplication, a transform measured with a proxy that never paid for what a decoder must send. The fourth was different in kind and travelled further: a summary table that mislabelled which of its own measurements was which, and a figure in it with no measured source at all, reproduced from the paper onto the project's public pages. Selecting by measured saving on held-out data outperforms selecting by document type even on the types the names were chosen for, and the deployed health-QR designs — which select no dictionary at all — leave a factor of three to four unclaimed.
Framing is worth pursuing and is second-order: the complete header and alphabet work recovers 3.7 %, against the dictionary's factor of 3.7 on matching content. Its value is not only in bytes — the flat identifier of §5.4 removes a silent-misdecode class from every future implementation, which is worth more than the characters it costs. The largest unclaimed item remains the schema layer of §7.3, generated from specification rather than inferred from examples — but measured fairly, against a dictionary trained on the same arrangement, it is worth about 18 %, not the 35 % a dictionary-free measurement suggests, and the elaborate typed encoding it was designed to enable is measurably worse in combination than simply not transmitting the field names (§7.6). The difference is the dictionary doing the structure layer's work before it runs. It is the kind of error that only appears when the dimensions are crossed rather than measured one at a time, and it is why this paper reports a factorial rather than a list of improvements.
Two results arrived after the factorial and point in opposite directions about how much is left. The dictionary size cap was never measured, only inherited from a mistaken comment, and measuring it returns a median 9.8 % for storage alone — so the dominant layer was not even being operated at its own optimum. Against that, confidentiality turns out to be available at exactly zero expansion, while issuer authentication is provably not: a signature is incompressible evidence, and a channel this narrow cannot carry one for free. For a printed clinical artefact that is the binding limitation, and it is arithmetic rather than engineering.
Implementation, corpora manifests, every measurement script and the per-document results for each experiment are in the project repository under research/, E01 through E17. Each experiment directory states the claim tested, the method, the provenance of its corpus, the results, what the experiment does not show, and the commands that reproduce it.