Skip to content

feat: refuse an over-bound value at encode in every backend (#656) - #717

Merged
Andste82 merged 14 commits into
mainfrom
feat/encode-bounds-656
Oct 10, 2026
Merged

Andste82 merged 14 commits into
mainfrom
feat/encode-bounds-656

Conversation

@Andste82

@Andste82 Andste82 commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Every backend now refuses a value the caller put past its schema bound at encode, before it is written, using the corelib's argument category. The bounds are a string/blob maxlen, an array count at every level, an array element's maxlen, and the declared width of an integer, enum or bitfield. Before this, the only guard was an accidental MAX_SIZE overflow, which a single over-bound value in a small message never reaches. So the same input was refused, written unchecked, or silently clamped or masked, depending on the backend.

The rule, where each check lives, the clamp contract and the opt-out are in the new ARCHITECTURE §9.6.1.

Commits

One commit per language, plus the shared commits:

commit
3f85fbf test(conformance): per-variant gap tables and the clamp contract in check_encode_bounds
f912575 feat(rust)
e66129b feat(zig)
c6010bd feat(go)
ce15bcc feat(dart)
5bf9377 feat(typescript)
f1f7080 feat(python)
76e7cb5 feat(java)
82ba8f0 feat(kotlin)
c1ce902 feat(csharp)
9fb24c2 feat(cpp)
c85759c feat(c)
5e56656 docs(generator): the shared bound note (generator.BoundDoc) states the encode refusal; the fixed-capacity maxlen note no longer claims "never truncated", which FixedString contradicts
fb1800e docs(architecture): §9.6.1, plus the §9.6 and §12 text that still described buffer-full or open gaps

Corelib PRs this needs

These must be merged first. Then drop the ci: pin commit (.github/corelib-refs) and re-run CI against corelib main:

Rust and Zig need no corelib change. No corelib holds a limit: a bound reaches the corelib only as a call argument, and only where the corelib alone knows the measured quantity, e.g. a string's UTF-8 length on a UTF-16 runtime.

Measured cost

tests/bench/run.sh --rows <rows>, vehicle_telemetry, before -> after, per language. Decode Ir/op is unchanged on every row. .data/.bss are unchanged on every footprint row.

row metric before after
c (footprint) .text ARMv6-m / ARMv7-m / RV32IMC 5594 / 5588 / 6134 B 5606 (+12) / 5592 (+4) / 6158 (+24) B
c encode Ir/op 25974 26491 (+2.0 %)
cpp-c-cpp (footprint) .text ARMv6-m / ARMv7-m 8694 / 8296 B unchanged
cpp-c-cpp-dyn (footprint) .text ARMv6-m / ARMv7-m 15632 / 14370 B 15834 (+202) / 14602 (+232) B; opt-out: 15632 / 14370
cpp-c-cpp-dyn encode Ir/op 33335 33437 (+0.3 %)
cpp-cpp encode Ir/op 11904 11546 (-3.0 %)
cpp-cpp-static / -unbounded encode Ir/op 10588 / 8496 10588 / 8490
rust-rs-no-std (footprint, heapless) .text thumbv6m 10465 B 10465 B (no guards)
rust-rs-no-std-dyn (footprint) .text thumbv6m 12135 B 12455 B (+320, 18 guards); opt-out: 12135
rust-rs-no-std-dyn encode Ir/op 9864 10078 (+2.2 %)
rust-rs encode Ir/op 9731 9573 (-1.6 %)
rust-rs-static / -unbounded encode Ir/op 9630 / 6850 9630 / 6856 (+0.09 %)
go encode Ir/op 18495 18605 (+0.59 %)
go-unbounded encode Ir/op 13156 13156
java encode Ir/op 17022 17363 (+2.0 %)
kotlin encode Ir/op 17256 17538 (+1.63 %)
csharp encode Ir/op 29201 29413 (+0.73 %)
ts-bigint / ts-long / ts-number encode Ir/op 585966 / 578382 / 595638 591557 (+0.95 %) / 583737 (+0.93 %) / 600996 (+0.90 %)
python-native encode Ir/op 127486 129129 (+1.29 %; the width as a writer argument was +3.66 %)
python (pure) encode Ir/op 1076634 1087834 (+1.04 %)
dart encode Ir/op 24592 24713 (+0.49 %)
zig encode Ir/op 9135 9330 (+2.1 %)
zig-unbounded encode Ir/op 8258 8270 (+0.15 %)

Each language measured its own rows against the preparation commit. A full tests/bench/run.sh run and the regenerated results.txt come separately.

The clamp contract

The encoder never clamps. A fixed-capacity container that clamps on assignment, before any encoder runs, keeps that as its documented contract, and no guard is emitted for it:

  • C++ FixedString / FixedBytes / InlineVector (allow_dynamic: false)
  • Zig sofab.FixedArray(T, N)
  • C's blob length and array/wrapper count companions, which are clamped to the capacity at encode

A string clamp never cuts inside a UTF-8 character: FixedString cuts at the last character boundary at or below maxlen. Rust heapless containers refuse on assignment instead. A C char[maxlen + 1] string that fills its member without a terminator is refused. check_encode_bounds.py's CLAMP_CONTRACT asserts the clamped value, a mid-character cut included.

Opt-out (footprint profiles only)

  • corelib: c-cpp: SOFAB_DISABLE_ENCODE_BOUNDS, used by C and by C++ through sofab::ENCODE_BOUNDS
  • corelib: rs-no-std with allow_dynamic: true: the generated crate's disable_encode_bounds feature, off by default

Tests

  • go test ./..., go vet ./... and gofmt (go 1.27) are clean.
  • check_encode_bounds.py --self-test passes.
  • Every variant's KNOWN_GAP is empty.
  • Each language commit adds backend unit tests, and its conformance suite was run green against its corelib branch. Each corelib PR extends that corelib's own suite.

Known gap, follow-up: the shared driver has no cell for an integer/enum/bitfield array element past its declared width (e.g. 300 in array<u8>). corelib-dart#105, corelib-py#175/#176 and the backend unit tests cover it today.

Closes #656

…heck_encode_bounds (#656)

Preparation for the per-language #656 changes, so each backend edits only
its own lines:

- KNOWN_GAP and the STORAGE_BLOCKED _block calls hold one line per variant
  (zig no longer shares the C/C++ cast line, rust no longer shares the
  serde and heapless lines).
- CLAMP_CONTRACT, one line per variant: a bounded container that clamps on
  assignment (C++ FixedString/InlineVector, Zig FixedArray, C companions)
  does so by documented contract. Such a case must encode, and decode must
  read back exactly the clamped value: a string cut to maxlen at a UTF-8
  character boundary, a blob or array cut to its bound.
- --self-test covers the contract: a clamping model passes every clampable
  case; one that cuts inside a character, or skips an array's clamp, turns
  exactly those cases red.

No variant's outcome changes: every table holds what it held.
With String/Vec storage (corelib rs, and rs-no-std with allow_dynamic: true)
serialize() now refuses a value past its schema bound with
sofab::Error::Argument before that field is written: a string or blob over
its maxlen (UTF-8 bytes), an array over its count, an array element over its
element maxlen, at any depth (nested structs, matrix rows, union options).
encode() therefore never returns bytes for such a value. Each guard is a
per-field `if x.len() > N { return Err(sofab::Error::Argument); }` -- no
static helper, no corelib change needed (none of corelib-rs or
corelib-rs-no-std is touched).

Nothing is emitted where the type guarantees the bound: heapless
String<N>/Vec<T, N> (rs static, rs-no-std static, rs-no-std no_std: false)
cannot hold more than N, and every narrow integer, enum and bitfield is
stored in a Rust type of exactly its declared width.

Footprint opt-out: a rs-no-std crate with dynamic storage declares the Cargo
feature `disable_encode_bounds` (off by default); every guard there carries
`#[cfg(not(feature = "disable_encode_bounds"))]`. Documented in
docs/generator/rust.md.

Tests: TestRustEncodeRefusesOverBound pins every guard, its position, the
cfg and the Cargo feature per storage mode, and no guard on unbounded fields
or heapless storage; union/sparsity tests updated; the missing-else lint
test covers the guards. check_encode_bounds.py: KNOWN_GAP empty for rust,
rust-static, rs-no-std, rs-no-std-dynamic, rs-no-std-std; the remaining
STORAGE_BLOCKED reasons now say the type guarantees the bound/width. The
rust conformance suite builds the probe with disable_encode_bounds and
asserts the guards are gone (built-in negative control).

Measured (tests/bench/run.sh, raw readings, corelib rs 5199c44,
rs-no-std 7d128af), before -> after:
  rust-rs             encode Ir/op 9731 -> 9573, decode 22647 -> 22647
  rust-rs-static      encode 9630 -> 9630, decode 16104 -> 16104
  rust-rs-unbounded   encode 6850 -> 6856 (+0.09%), decode 21165 -> 21165
  rust-rs-no-std      .text thumbv6m 10465 -> 10465 (no guards)
  rust-rs-no-std-dyn  .text thumbv6m 12135 -> 12455 (+320 B, 18 guards);
                      with disable_encode_bounds 12135; encode Ir 9864 -> 10078
A single joined guard per struct was measured too (12463 B) and rejected.

Refs #656
serialize() now refuses a value past its schema bound with
error.InvalidArgument (the corelib's code for a bad encode call) before that
field is written, so encode() returns nothing for it:

- string/blob over maxlen: one per-field `if (x.len > N)` guard; the slice
  length is the UTF-8 byte length, no pass over the data;
- a slice-backed array over count (wrapper arrays of string/blob/struct/
  union, nested rows incl. native rows), and every string/blob element over
  its maxlen, guarded inside the existing element loop; union options too.

A native count:N array is sofab.FixedArray(T, N): set()/init() keep the
first N elements, so it clamps at assignment and gets no guard. That is the
documented clamp contract: the driver's CLAMP_CONTRACT for zig now holds
au_count_plus_1, au_count_plus_2 and n_arr_count_plus_1. Strings are never
clamped, so no UTF-8 cut exists on this target. No scalar width guard: every
Zig field type is exactly the declared width (u8, i16, and the i8/u8 an
enum/bitfield implies); the STORAGE_BLOCKED reason now says so.

The encode()/serialize() doc comments promise error.InvalidArgument only
where a bound is reachable (replacing the old error.BufferFull wording).

No corelib change: every guard is a per-field comparison with a schema
literal; nothing schema-independent is emitted.

Tests: TestZigEncodeRefusesOverBound pins every guard shape and the
no-guard cases (FixedArray, unbounded); existing union/array shape tests
updated. check_encode_bounds: KNOWN_GAP[zig] = (), 22 cases, 17 pass
(3 by clamp contract), 5 storage-blocked. Negative control: removing the
`s` and the `as` element guards from the generated probe turns exactly
s_over_1, s_over_60, s_over_utf8_80, s_over_midchar and
as_elem_over_maxlen red. tests/conformance/zig/run.sh PASS against
corelib-zig main 4071af3.

Ir/op (tests/bench/run.sh, before -> after, corelib-zig 4071af3):
  zig            encode 9135 -> 9330 (+2.1%), decode 22227 -> 22227
  zig-unbounded  encode 8258 -> 8270 (+0.15%), decode 18609 -> 18609
The zig encode delta was reproduced by stripping only the guards from the
same generated file (9135 vs 9330). About 70 Ir are the ~23 executed
comparisons; the rest is LLVM inlining: the larger
VehicleTelemetry.serialize no longer inlines writeSequenceEnd,
writeSequenceEndKeep, writeArraySigned and EnergySources.serialize.
@branchHint(.cold) on the guards changes nothing (9330), and folding the
top-level guards into one condition costs more (9503).

Refs #656
A string or blob past its maxlen, and an array past its count -- at every
level a count is declared, nested rows and array<string>/array<blob>
element maxlen included, union options too -- is now refused at encode
with sofab.ErrArgument (CORELIB_PLAN 6.3 InvalidArgument) before any byte
of the message is returned as a success (ARCHITECTURE 9.6).

The bound lives in the generated code only: Serialize emits one per-field
guard, `if len(x) > N { e.RejectArgument(); return }`, inside the field's
write branch where it has one, so a field at its default pays nothing.
The corelib is handed only the verdict (Encoder.RejectArgument records the
sticky ErrArgument; Encode, EncodeTo and Flush report it). Go strings are
byte strings, so len() is the UTF-8 byte length maxlen counts; no corelib
string API change is needed.

No scalar guard: the Go storage type of an integer, enum or bitfield is
exactly its declared width (uint8, int16, int8-backed enum, uint8-backed
bitfield), so no value past it can be held. The driver's STORAGE_BLOCKED
reason for those cells now says so; KNOWN_GAP[go] is empty.

Needs sofa-buffers/corelib-go#151 (exports Encoder.RejectArgument).

Tests: generators/golang/encode_bounds_test.go pins every guard and its
placement (one per declared bound, none for undeclared ones or scalars)
and, with SOFAB_GO_CORELIB, drives an over-bound value per bound through
the harness (refused with ErrArgument) and an at-bound one (round trips).
Conformance tests/conformance/go/run.sh: PASS; encode bounds 17 of 22
pass, 5 storage-blocked, KNOWN_GAP empty. Negative control: removing the
blob, array<string> element and nested-array guards from the generated
code fails exactly b_over_1, b_over_60, as_elem_over_maxlen and
n_arr_count_plus_1.

Measured (tests/bench/run.sh --rows go,go-unbounded, Ir/op):
  go            encode 18495 -> 18605 (+0.59%), decode 45056 -> 45056
  go-unbounded  encode 13156 -> 13156,          decode 39526 -> 39526

Refs #656
serialize() now refuses a value past what the schema declares with the
encoder's InvalidArgument category (sofab.SofabException with
SofabError.invalidArgument, CORELIB_PLAN 6.3) before it is returned:

- string/blob maxlen: the Inline destination holds the UTF-8 bytes, so
  its length is compared with the maxlen literal directly;
- native array count, wrapper array count at every nesting level, each
  string/blob element's maxlen and each matrix row's count;
- u8/u16/u32/i8/i16/i32 width and the width an enum or bitfield
  declaration implies, with the same comparison the decode side applies
  (widthCond / declaredWidthCond); nothing for 64-bit kinds, bool, floats
  and unbounded fields;
- the element width of a narrow integer, enum or bitfield array (native
  field or matrix row): the Int64 storage is wider than the width, so the
  write calls corelib-dart's writeUnsignedArrayInRange /
  writeSignedArrayInRange with the declared width as two int literals,
  the same pair the decode side hands the destination; the corelib
  refuses an element outside it in the varint loop it already runs.

Every guard is one compare against a schema literal, emitted per field
inside the write branch (a field omitted at its default pays nothing),
throwing a const exception: no allocation, no extra pass, no static
helper. The harness reports a refused encode as exit 1 instead of an
unhandled exception; only the encode work (encode, both streamencode
arms, the encode half of recode) is wrapped, so a SofabException out of
a decode verb still surfaces as a crash. encode()/encodeTo() document
the refusal.

The dart variant's KNOWN_GAP in check_encode_bounds.py is now empty:
22 of 22 cases pass, none storage-blocked.

Corelib: needs sofa-buffers/corelib-dart#105 (the in-range writers
writeUnsignedArrayInRange/writeSignedArrayInRange).

Measured with tests/bench/run.sh --rows dart, Ir/op:
  encode 24592 -> 24713 (+0.49 %); decode 39094 -> 39090 (unchanged).
  An optional ElemRange argument on the existing writers measured 25279
  (+2.79 %). Dedicated writers with plain int bounds measured 24891, so
  the optional argument itself (its null test and field loads, not the
  element compare) cost about 1.6 %; checking the count on the promoted
  Int64List length instead of a separate count read saved another
  ~0.7 % (24891 -> 24713). The corelib therefore takes dedicated writers
  with plain int bounds.

Refs #656
A value past its schema bound is now refused at encode with
SofabError(ARGUMENT) before it is written, in all three int64 modes:

- string maxlen: the bound is passed to the corelib's
  writeString(id, s, maxlen), which refuses on the UTF-8 length it
  already computes for the header (no second pass, no allocation). This
  also covers array<string> elements.
- blob maxlen, array count (native, wrapper, nested rows, nested struct
  arrays): one per-field compare against the schema literal before the
  write.
- u8/u16/u32/i8/i16/i32, enum and bitfield: the member is a number (a
  wide bitfield a bigint), wider than the declared width, so the
  decoder's own width comparison is emitted before the write. A negative
  unsigned value is already refused by writeUnsigned. Typed-array
  elements, 64-bit values, booleans and floats cannot leave their width
  and get nothing.

The generated encode() doc comments now say ARGUMENT instead of
BUFFER_FULL for an over-bound value. check_encode_bounds: KNOWN_GAP is
empty for typescript, typescript-long and typescript-number (22/22 each,
nothing blocked). The wrapper-cap leg of run.sh produces its over-maxlen
input through the unbounded twin message, since the bounded encoder now
refuses it.

Needs sofa-buffers/corelib-ts#203 (writeString maxlen).

Measured (tests/bench/run.sh, Ir/op, baseline 3f85fbf + corelib-ts main
vs this commit + corelib-ts#203):
  ts-bigint encode 585966 -> 591557 (+0.95%), decode 792856 -> 792854
  ts-long   encode 578382 -> 583737 (+0.93%), decode 786731 -> 786728
  ts-number encode 595638 -> 600996 (+0.90%), decode 782146 -> 782155
The vehicle_telemetry schema gets 24 compare guards and 4 maxlen
arguments, several inside per-element struct serialize; the rows run at
V8's baseline tier, where each compare costs a property load and a
branch.

Refs #656
@Andste82
Andste82 force-pushed the feat/encode-bounds-656 branch 3 times, most recently from 0489175 to e967f4e Compare October 10, 2026 12:27
A value past its schema bound -- a string or blob over maxlen (UTF-8
bytes), an array over count (nested rows and array<string> elements
included), an integer, enum or bitfield outside its declared width,
as a field or as an element of a native array -- is now refused at
encode with SofaArgumentError, the corelib's InvalidArgument, and
encode() returns nothing. A scalar, string, blob or array count is
refused before any byte of the field is written; an array element is
refused where the writer's own per-element range check reaches it,
after the header and the elements before it -- serialize() raises, so
encode() hands back nothing of that message.

The bound is the schema literal, emitted per field, and rides the
corelib-py call. A maxlen or count is an argument:
write_string_bounded(id, s, maxlen) (the UTF-8 length exists only
there), write_bytes_bounded, write_{bool,float32,float64}_array_bounded,
and the cap of the integer array writers. A declared integer width is a
type and goes in the writer's name: write_u8 .. write_i32 for a narrow
integer, enum or bitfield, write_u8_array(id, values, cap) ..
write_i64_array for a native integer array (u64/i64 only when it has a
count; -1 is no count). A field with no bound calls the plain writer,
unchanged. A wrapper array has no writer that takes it whole, so its
count is the one generated `if _n > N: raise SofaArgumentError(...)`,
on the length the element loop now binds once instead of calling len()
per element.

The width numbers come from one helper (declaredWidth) for both
directions: the decode side's destination table (bindScalarWidth,
bindElemWidth) and the encode side's writer choice (widthBounds,
typedWidth).

SofaArgumentError is imported only where a generated guard raises it.
The encode() docstrings say what is refused. Driver: KNOWN_GAP for
python and python-pure is empty; nothing is storage-blocked, no clamp
contract.

Needs sofa-buffers/corelib-py#175 (the *_bounded writers for strings,
blobs and bool/float arrays) and sofa-buffers/corelib-py#176 (the
width-typed integer writers, which replace the integer *_bounded
writers #175 had added; none of them was released), both engines;
against a corelib without them the generated code fails with an
AttributeError.

Measured, tests/bench/run.sh --rows python,python-native (Ir/op,
vehicle_telemetry), main vs this commit with corelib-py#176 @ e863410:

  python         encode  1,076,634 -> 1,087,834  +1.04%
  python         decode  1,980,549 -> 1,980,829  +0.01%
  python-native  encode    127,486 ->   129,129  +1.29%
  python-native  decode    430,935 ->   432,544  +0.37%

Decode code is unchanged; the native decode delta is the rebuilt
extension's layout. Alternatives measured: the width as an argument
of *_bounded writers +3.66% native encode (each extra argument is
unpacked on every native call); generated if/raise guards +8.7%;
optional parameters on the plain writers +2.9% without element widths
but +1.2% on every unbounded call.

Tests: encode_bounds_test.go pins every bound position (scalars of both
signs, enum, bitfield, string, blob, native and wrapper arrays, native
arrays' element widths incl. enum/bitfield/row/union elements, struct
arrays, array-of-array rows, nested struct, union options default and
forced) and that unbounded/64-bit fields call the plain writer, and runs
the generated module against the corelib on the pure engine and on the
native one, each run checking sofab.IMPL (the native run is skipped out
loud where sofab._speedups is not built). Conformance suite PASS on both
engines, 22/22 encode-bound cases each.

Refs #656
serialize now refuses a value past its schema bound with the corelib's
argument category, SofabException(SofabError.ARGUMENT), before the field
is written; encode() wraps it as it wraps every IOException, and no bytes
are returned. Each guard is a per-field comparison against the schema
literal, emitted on the write it protects (an omitted default field costs
nothing):

- string / array<string> element over maxlen (UTF-8 bytes): the bound
  rides the corelib call, OStream.writeString(id, s, maxlen), which
  compares inside the measuring pass it already runs -- no second pass,
  no allocation;
- blob / array<blob> element over maxlen: a length guard;
- array over count, at every nesting level (row guards on nested rows,
  wrapper arrays on the list the loop runs over);
- u8/u16/u32/i8/i16/i32, enum and bitfield held in a long: the same
  width comparison the decode store emits (widthTest, shared). 64-bit
  kinds and primitive-array elements (held in their declared width's own
  primitive) need none.

Union options carry the same guards. serialize/encode/encodeTo document
the refusal. SofabError joins the qualifier list (a field of that name
is escaped). The conformance suite writes its over-maxlen decode input by
hand, since the encoder no longer produces it; check_encode_bounds:
KNOWN_GAP[java] is empty, 22/22 cases pass, nothing storage-blocked.

Needs sofa-buffers/corelib-java#127 (writeString(id, text, maxlen)).

Measured (tests/bench/run.sh --rows java, Ir/op, before = corelib main
50a84b3, after = corelib-java#127):
  encode 17022 -> 17363 (+2.00%), decode 31730 -> 31723 (-0.02%).
The encode increase is the guards that run: vehicle_telemetry fills ~50
bounded values per message (16 scalars: 86 Ir, 21 array/blob lengths:
124 Ir, 11 strings: 35 Ir, each measured by removing that class of
guard), about 5-6 Ir per guard. One-operation width tests ((x & ~0xFFL)
!= 0, (byte) x != x) measured -32 Ir and were not taken, to keep the
decode side's comparison shape; a shorter throw site measured no change.

The serialize of every struct and union class documents the refusal
(@throws SofabException with ARGUMENT) whenever it can refuse, including
through a nested struct, union or struct/union array element.

Refs #656
A value past its schema bound is refused at encode with
SofabException(SofabError.ARGUMENT) before the field writes a byte, the
encode half of the bounds the decoder enforces (ARCHITECTURE 9.6):

- string over maxlen (field, union option, array<string> element, nested
  rows): the bound rides on the new corelib overload
  OStream.writeString(id, text, maxlen), which judges the UTF-8 byte
  length inside its own measuring pass (no second pass, no allocation);
- blob over maxlen (field and array element): a per-field size compare;
- array over count, nested rows included: a per-field size compare ahead
  of the write, and ahead of the frame for a wrapper array;
- scalar enum (held in Int) and bitfield (held in ULong) outside their
  declared width: the decode side's own comparison, on the member.
  u8/i16 and every other integer, and enum/bitfield array elements, are
  held at exactly their declared width, so nothing is emitted for them.

Nothing is clamped. Every guard is a per-field compare against the
schema literal; no schema-independent helper is emitted. SofabError is
now a qualifier the class body uses, so it joins ktQualifiers and the
reserved-name fixture. The generated encode/encodeTo KDoc states the
refusal. check_encode_bounds: KNOWN_GAP[kotlin] is empty; u8_over,
i16_over, i16_under stay blocked because the type is the declared width.

Needs sofa-buffers/corelib-kotlin-mp#59 (writeString with maxlen).

Measured (tests/bench/run.sh --rows kotlin, JDK 21, Ir/op):
  encode 17256 -> 17538 (+282, +1.63%); decode 32779 -> 32780.
  Split, same generator with every guard emission disabled but the
  bounded writeString(id, s, maxlen) calls kept: encode 17325 (an
  independent rerun gave 17311). The bounded string writes cost about
  +57..+69 Ir (+0.3..0.4%). The guards cost the remaining 213..239 Ir.
  On the VehicleTelemetry payload 22 guards run per encode: 15 field
  guards, 4 cell_mv row guards and 3 ecu_sigs element guards, so about
  10..11 Ir each. Moving every throw construction into one cold private
  function left encode at 17551, so the throw-site bytecode is not the
  cost, and no cheaper guard shape was found. The per-field check is
  what the rule requires; decode is unchanged.

Refs #656
Serialize (and so Encode/EncodeTo) now refuses a value past its schema bound
with SofabException(SofabError.Argument) before the message is returned:

- string maxlen: the bound is passed to corelib-cs's new
  WriteString(id, text, maxlen), which compares the UTF-8 length in the pass
  that already measures the value (a C# string's UTF-8 length is only known
  inside the transcoder); also for array<string> elements;
- blob maxlen, array count (every nesting level, incl. bool/List arrays and
  union options), blob element maxlen: a per-field `if (len > N) throw`
  against the schema literal, emitted before the write;
- no scalar width guard: the C# storage type already is the declared width
  (byte, short, enum : sbyte, [Flags] enum : byte via enumBacking /
  bitfieldBacking), so no over-width value can be assigned.

The generated harness reports a refused encode as "encode error" with exit 1
on both encode verbs instead of an unhandled exception. EncodeTo's doc
comment states what encode refuses. check_encode_bounds: KNOWN_GAP[csharp]
is now empty; the five scalar cells stay STORAGE_BLOCKED with the reason
that the type guarantees the width.

Needs sofa-buffers/corelib-cs#118 (WriteString(id, text, maxlen)).

Measured (tests/bench/run.sh --rows csharp, corelib-cs 0014aef -> #118):
encode 29201 -> 29413 Ir/op (+0.73%), decode 70166 -> 70166 (held, <0.3%).

Refs #656
A string or blob longer than its maxlen, or an array with more elements
than its count (nested rows, array<string>/array<blob> elements and
struct-array counts included), is now refused by the generated
serialize() wherever the member is a growable std::string /
std::vector: a per-field guard returns through the corelib's
OStreamImpl::rejectArgument(), which latches InvalidArgument, so
encode() returns no bytes, encodeTo() returns 0 and a caller's stream
reports !ok(). The corelib is handed no bound.

- Static storage (FixedString / FixedBytes / InlineVector, the
  allow_dynamic: false default of corelib: c-cpp and the opt-in of
  corelib: cpp) carries the bound as its capacity and clamps on
  assignment: no guard, a documented contract (CLAMP_CONTRACT). A level
  that falls back to std::vector (a counted array of maxlen-less
  strings) keeps its guard.
- Scalars, enums and bitfields are stored in their declared fixed-width
  type, so nothing is emitted for them; the driver's STORAGE_BLOCKED
  reason now says the type guarantees the width.
- corelib: c-cpp (footprint) writes each check as
  `if (sofab::ENCODE_BOUNDS && ...)`; SOFAB_DISABLE_ENCODE_BOUNDS
  compiles them all out. corelib: cpp has no opt-out.
- The harness encode verb exits non-zero on a refusal (an empty
  encode() from a non-default message), and appends string elements with
  push_back so an InlineVector drops, not overwrites, past its capacity.
- Generated docs of encode()/encodeTo()/serialize() say what is refused
  and what clamps; docs/generator/cpp.md documents both behaviours and
  the opt-out.

check_encode_bounds.py: KNOWN_GAP is empty for cpp, cpp-static, c-cpp
and c-cpp-static; the static variants hold all 11 string/blob/array
cells to the clamp contract.

Needs sofa-buffers/corelib-cpp#153 (rejectArgument, UTF-8-safe
FixedString clamp, InlineVector::push_back drops past N) and
sofa-buffers/corelib-c-cpp#194 (the same plus sofab::ENCODE_BOUNDS).

Measured (tests/bench/run.sh, 3f85fbf + corelib main vs this commit +
the corelib branches):

  Ir/op encode / decode
  cpp-cpp            11904 -> 11546 (-3.0%) / 28116 -> 28254 (+0.5%)
  cpp-cpp-static     10588 -> 10588         / 21322 -> 21325
  cpp-cpp-unbounded   8496 ->  8490         / 21663 -> 21663
  cpp-c-cpp          32983 -> 32983         / 40862 -> 40862
  cpp-c-cpp-dyn      33335 -> 33437 (+0.3%) / 52167 -> 52164

  .text (checks on / -DSOFAB_DISABLE_ENCODE_BOUNDS), .data/.bss unchanged
  cpp-c-cpp     ARMv6-m   8694 ->  8694 /  8694
  cpp-c-cpp     ARMv7-m   8296 ->  8296 /  8296
  cpp-c-cpp-dyn ARMv6-m  15632 -> 15834 / 15632 (+202 B, 18 guards)
  cpp-c-cpp-dyn ARMv7-m  14370 -> 14602 / 14370 (+232 B)

rejectArgument is cold and out of line in both corelibs: inlined at the
18 guard sites it cost cpp-cpp +4.4% encode (GCC stopped inlining
writeIntArray<uint16_t> into serialize) and the -dyn row 300 B.

Refs #656
The C target encodes through descriptors inside corelib-c-cpp, so the
string check lives there (corelib-c-cpp#194): sofab_object_encode reads a
string member bounded by its own char[maxlen + 1] storage, which the
descriptor already carries as the field size, and refuses a value that fills
it without a terminator with SOFAB_RET_E_ARGUMENT. Before, the member was read
with strlen, past the field. The generated code carries no guard and no
bound; nothing schema-specific is emitted for this.

- Blob length and array/holder count companions past the capacity keep being
  clamped by the corelib at encode: the documented clamp contract. The
  driver's CLAMP_CONTRACT line for c lists those six cells; KNOWN_GAP[c] is
  empty. The scalar cells stay STORAGE_BLOCKED, now with the true reason: the
  fixed-width C type guarantees the declared width.
- The member notes say what encode does: a string is refused, a companion past
  its capacity is clamped. They are rendered by the C backend instead of the
  shared BoundDoc, whose "never truncated" is true of the decoder only.
- The project harness hands encode what a caller's over-bound value would
  look like: an over-long JSON string is stored as its first cap bytes with
  no terminator (encode refuses it; terminating it at maxlen would hide the
  over-long value and could cut inside a UTF-8 character), and a blob or
  array stores at most its capacity but sets the length companion to the
  JSON length unclamped (saturated only at the companion's C type). So the
  clamp the conformance cells observe is the encoder's, not the harness's.
- docs/generator/c.md: "Bounds at encode", with the
  SOFAB_DISABLE_ENCODE_BOUNDS opt-out (a corelib switch; the project
  Makefile's CFLAGS reach the corelib sources).

Tests: encodebounds_test.go pins that the encode path emits no check, the
notes, the harness's unterminated string store and unclamped length
companions, and builds the project against the corelib with and without
-DSOFAB_DISABLE_ENCODE_BOUNDS: the string refusal, and the encoder's clamp of
a blob length and of array, array<string> and nested array counts.
Negative controls on a scratch corelib copy:
- refusal removed from object.c: the driver fails exactly s_over_1,
  s_over_60, s_over_utf8_80, s_over_midchar and as_elem_over_maxlen; the
  opt-out test fails its checks-on case.
- blob clamp removed: the driver fails b_over_1 and b_over_60; the opt-out
  test fails its blob check in both builds.
- array/holder count clamps removed: the driver fails au_count_plus_1,
  au_count_plus_2, as_count_plus_1 and n_arr_count_plus_1; the opt-out test
  fails its three count checks in both builds.

Measurements (tests/bench/run.sh --rows c, corelib main b031f3b vs
corelib-c-cpp#194), .text of generated code + corelib, SofaBuffers symbols:
  ARMv6-m        5594 -> 5606 (+12), opt-out 5606
  ARMv7-m+fp.dp  5588 -> 5592 (+4),  opt-out 5592
  RV32IMC        6134 -> 6158 (+24), opt-out 6156
  .data/.bss 0/0 unchanged. The growth is the bounded loop replacing the
  strlen call, which the bench excludes as libc; the image no longer links
  strlen (92 B in newlib-nano for ARMv6-m).
  Ir/op encode 25974 -> 26491 (+2.0%), decode 54510 unchanged.

Needs sofa-buffers/corelib-c-cpp#194.

Refs #656
The shared field note (generator.BoundDoc) described only the decode
verdict. Every backend now refuses an over-bound value at encode, so the
growable-storage note says so: "... is INVALID, never truncated: encode
refuses it."

The fixed-capacity maxlen note claimed "never truncated", which is false
for C++ FixedString/FixedBytes: they clamp on assignment (at a UTF-8
character boundary for a string) by contract. It now says only what holds
for every fixed-capacity container (C++ clamps, Rust heapless refuses on
assignment): the field never holds a longer value, and a longer one on
the wire is INVALID.

Also drops the _CAST reason from check_encode_bounds.py: after the
per-language commits no variant uses it any more.
New section 9.6.1 states the rule (every schema bound binds the encoder
as it binds the decoder; an over-bound value is refused with the
corelib's argument category before it is written, never clamped by the
encoder), the four places a check lives (a generated per-field guard
against the schema literal; a bound passed to a corelib call as an
argument where only the corelib knows the measured quantity; a corelib
hook that only latches the error; C's descriptor-driven check), the
clamp contract of assignment-clamping containers with its UTF-8
boundary rule, the SOFAB_DISABLE_ENCODE_BOUNDS / disable_encode_bounds
opt-out of the footprint profiles, and a per-language table with the
measured cost.

The bounded-buffer bullet of 9.6 no longer says an over-bound value is
reported as buffer-full, and the section 12 entry of
check_encode_bounds.py reflects that every KNOWN_GAP is empty.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(generated encode): an over-bound value of a bounded element must be refused at encode, not written or clamped

1 participant