Skip to content

fix(model-avro,binding-kafka): reserve enough Kafka cache capacity for values that expand during decode - #2377

Merged
jfallows merged 1 commit into
developfrom
claude/zilla-issue-2302-7wu9ht
Aug 14, 2026
Merged

jfallows merged 1 commit into
developfrom
claude/zilla-issue-2302-7wu9ht

Conversation

@jfallows

@jfallows jfallows commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

AvroModelExtHandler (the SPI a model extension plugs into the avro model's decoder pipeline with) had no way to declare that its transform can expand a decoded value beyond the untransformed input's length. The Kafka local cache's converted-value (JSON view) capacity reservation in KafkaCachePartition relied solely on schema-shape padding (JSON syntax overhead — field names, punctuation), so an installed extension whose substitute value is longer than the original field silently overran the reserved region. The only guard was assert convertedPadding - length >= 0, compiled out in production, so the overflow corrupted the mmap'd converted-value file and surfaced later as an unrelated IndexOutOfBoundsException on a subsequent read.

This surfaced from a value-expanding extension — one whose substitute value's length doesn't derive from the original field's length (e.g. a fixed-length replacement) — long enough to exceed the reserved capacity for a short original field, crashing a live engine on fetch.

Changes

  • AvroModelExtHandler: add a default padding(AvroSchema schema) method (returns 0), so an extension that can expand a value overrides it to declare the maximum additional bytes.
  • AvroModelHandler/AvroModelHandlerImpl: sum every installed extension's padding(schema) contribution into the decode padding estimate (decodePadding), cached per schema id alongside the existing JSON-syntax padding.
  • KafkaCachePartition: replace the disabled assert convertedPadding - length >= 0 in both the fetch-path (writeEntryFinish) and produce-path (writeProduceEntryContinue) converted-value writers with a real runtime bounds check. On violation, the cache entry is marked CACHE_ENTRY_FLAGS_ABORTED (the same mechanism already used for invalid-key entries) instead of writing past the reserved capacity, so a mis-declaring extension degrades to a skipped entry rather than corrupting the cache file.

Test plan

  • New unit test AvroModelDecoderPipelineTest.shouldIncludeExtensionPaddingContribution, confirmed failing to compile against the prior AvroModelExtHandler (no such method to override), then green after implementing
  • New unit test AvroModelExtHandlerTest.shouldReportNoPaddingByDefault, covering the new default method
  • ./mvnw clean verify -pl runtime/model-avro — 34 unit tests + 6 k3po ITs, checkstyle, license headers, JaCoCo coverage all pass
  • ./mvnw clean verify -pl runtime/binding-kafka — 395 k3po ITs pass, no regressions
  • Verified live: rebuilt a downstream image consuming this branch's AvroModelExtHandler.padding() override for a value-expanding extension, ran an end-to-end docker compose scenario that previously crashed the engine on fetch — now returns a stable result across repeated fetches with no engine errors

Fixes #1681


🤖 Generated with Claude Code

https://claude.ai/code/session_01GKWELiLVoasTwsuvaXg2Y3

@jfallows
jfallows force-pushed the claude/zilla-issue-2302-7wu9ht branch from 074b355 to 089c0a2 Compare August 14, 2026 16:45
…r values that expand during decode

AvroModelExtHandler had no way to declare that its transform can expand a
decoded value beyond the untransformed input's length. The Kafka local
cache's converted-value capacity reservation (KafkaCachePartition) relied
solely on schema-shape padding (JSON syntax overhead), so a substitute value
longer than the original field -- e.g. a fixed-length replacement whose size
doesn't derive from the input -- silently overran the reserved region: the
only guard was an assert disabled in production, corrupting the mmap'd
converted file and surfacing later as an unrelated IndexOutOfBoundsException
on read.

Add a default AvroModelExtHandler.padding(schema) method, sum every
installed extension's contribution into AvroModelHandlerImpl's decode
padding, and replace the disabled assert in KafkaCachePartition's converted-
value writer with a real bounds check that aborts the cache entry instead
of writing past its reserved capacity.
@jfallows
jfallows force-pushed the claude/zilla-issue-2302-7wu9ht branch from 089c0a2 to 6d50329 Compare August 14, 2026 16:55
@jfallows jfallows changed the title fix(model-avro,binding-kafka): account for model-extension value expansion in cache padding fix(model-avro,binding-kafka): reserve enough Kafka cache capacity for values that expand during decode Aug 14, 2026
@jfallows
jfallows merged commit 9afee82 into develop Aug 14, 2026
42 checks passed
jfallows added a commit that referenced this pull request Aug 16, 2026
…peline stages (#2385)

* feat(model-json): add JsonModelExtFactorySpi for provider-supplied pipeline stages

Mirrors model-avro's AvroModelExtFactorySpi (#2376/#2377): a generic,
business-agnostic extension point so an installed module can contribute
its own pipeline stage to the json model without the engine or model-json
knowing anything about what that stage does.

- JsonTransformable in common-json (JsonStream now extends it), the
  narrower supertype an extension appends stages to without depending on
  JsonStream's fuller terminal-bearing API
- JsonModelExt/JsonModelExtContext/JsonModelExtFactorySpi/JsonModelExtHandler
  in model-json's new io.aklivity.zilla.runtime.model.json.ext package;
  JsonModelHandlerImpl folds every discovered extension's stage into the
  decode stream ahead of the model's own validator/extractor stages, in
  discovery order. Encode never folds extensions in: it is the write path
  into the broker and must preserve the full, undisclosed value.
- JsonModelExtHandler.padding(schema) (default 0) lets an extension declare
  the maximum additional bytes its transform may add to a decoded value, so
  KafkaCachePartition's existing bounds check (already generic across
  models) reserves enough converted-value capacity regardless of which
  model triggered the shortfall
- A deployment with zero installed extensions pays nothing: the fold is a
  no-op and the assembled pipeline carries no extra stage

Fixes #1682

* fix(model-json): allow provider-supplied model-ext properties in options.value

json.schema.patch.json closed options.value with additionalProperties:
false at the top level, so no ModelExtInfo-contributed property (the
existing per-model extension point, already used successfully by
model-avro's own schema patch, which carries no such restriction) could
ever validate against a model:json options block -- any add to
$defs/models/model/allOf from a separate schema patch is rejected
outright by this branch's own closure, regardless of what that branch
itself permits.

Drop the blanket additionalProperties:false, matching model-avro's
schema shape; the enclosing $defs/models/model schema already closes
via unevaluatedProperties:false, so undeclared keys are still rejected
once every contributing allOf branch is considered together.

* fix(model-json,common-json): decode pipeline correctly supports installed extensions

Two latent bugs, both invisible until a value model extension actually
substitutes a value through a live decode pipeline:

- JsonModelDecoderPipeline computed its source-side "skip this many
  bytes of catalog framing" prefix by calling the handler's decodePadding,
  which folds in every installed extension's own padding contribution
  (destination-sizing, for a value an extension may expand) -- not the
  catalog's own framing-byte count. Once an extension contributes
  non-zero padding, that count got skipped from the actual input instead,
  truncating the value before the parser ever saw it. Split out a
  dedicated prefix() on JsonModelHandlerImpl (catalog framing only,
  mirroring model-avro's own prefix()/decodePadding() split) and pointed
  the decoder at it.

- JsonStream's generator-owning into(JsonGeneratorEx) terminal always
  requests byte-preserving delivery, so a value that substitutes content
  (rather than reproducing the parsed input) gets asked for the original
  source bytes it does not have -- the substitute source implementations
  installed models are expected to supply do not exist as bytes at all.
  into(JsonSink) already exposes a structured-delivery opt-out via
  JsonEx.createSink's config param; add the matching config-taking
  into(JsonGeneratorEx, Map) overload so the repeatedly-invoked,
  re-targeted terminal a decode pipeline needs can opt out the same way.
  model-json's decode pipeline now requests structured delivery once any
  extension is installed, unchanged otherwise.

* fix(engine): TestBindingFactory correctly drives ModelPipeline across fragments

TestBindingFactory's model transform loop only ever handled ModelStatus.OK
and COMPLETE, leaving ModelStatus.OVERFLOW unhandled entirely -- a value
whose transformed size exceeded modelBuffer's fixed capacity spun forever
against an already-full destination window (silent livelock, no exception).
Now OVERFLOW drains modelBuffer downstream before continuing, delivering
values of any size across as many chunks as needed.

The loop also hardcoded every call's source-side flags to INIT|FIN, so a
value split across multiple onXData invocations presented each continuation
frame as a fresh, complete message to the model -- a stateful pipeline mid
value saw a spurious restart and rejected it as malformed. Source flags now
start at the DATA frame's own actual flags and drop INIT after the first
call, matching how the frame was really fragmented.

Destination accumulation (total bytes produced, whether an OVERFLOW drain
has already happened) now lives in a per-direction ModelTransformState field
instead of a call-local variable, so it persists correctly across separate
onXData invocations for the same logical value instead of resetting on
every call -- and nothing is flushed downstream until the transform session
actually concludes (COMPLETE or REJECTED), matching ModelPipeline's
all-or-nothing contract for a value that only turns out invalid once its
terminal event fires.

* fix(common-json,model-json): self-bound JsonTransformable to avoid a cast

JsonTransformable.transform(JsonTransform) returned the narrower
JsonTransformable supertype, so any caller extending a concrete stream
type (JsonModelHandlerImpl.extend(), folding each installed model
extension's stage into the decode stream) had to cast the result back to
JsonStream to keep building on it.

JsonTransformable now takes a self-bounded type parameter
(T extends JsonTransformable<T>) and returns T instead, mirroring
common-avro's AvroTransformable fix: JsonStream extends
JsonTransformable<JsonStream>, and JsonModelExtHandler.transform() is
generic over the caller's own concrete stream type, so extend() no
longer needs the (JsonStream) cast.

A functional interface with a generic abstract method can't be a lambda
target, so the one JsonModelExtHandler lambda in JsonModelDecoderPipelineTest
(the "drop a field" test double) becomes an anonymous class -- matching
every other JsonModelExtHandler implementation already written that way.

* feat(model-json): split JsonModelExtHandler.transform() into decode()/encode()

model-json's own extension SPI conflated a pipeline decoding the
canonical value into the view delivered to a reader with one encoding
a caller's value into its canonical form under a single transform()
method, and the encoder pipeline never folded installed extensions in
at all. Splitting into decode()/encode() default methods (mirroring
model-avro's AvroModelExtHandler) lets an extension apply to either
direction independently, and lets the encoder pipeline fold installed
extensions in the same way the decoder pipeline already does.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XC96PuggqzqgyXmhUuXEH5

* wip(model-json): mirror model-avro's ModelExt composition test coverage

Adds TestUppercaseJsonModelExtFactorySpi (test-only JsonModelExtFactorySpi,
mirroring TestUppercaseAvroModelExtFactorySpi merged into develop) plus the
matching json.ext.yaml config, JsonFunctions k3po repeat() helper, 24 paired
client/server .rpt scripts under specs/model-json.spec, and 6 new JsonModelIT
test methods covering apply-on-decode/encode, overflow-drain at 100k, and
reject via JsonPipeline.Status.REJECTED.

Fixes a real bug found in the process: JsonModelHandlerImpl's encode-path
newPipeline() didn't force JsonSink.Delivery.STRUCTURED once an extension is
installed, unlike the decode path -- a substituted value has no original
source bytes to splice, so the terminal generator's default byte-preferring
delivery mode crashed the engine worker (UnsupportedOperationException from
getVerbatim()) the moment an extension substituted a value during encode.

Status: NOT yet green. Three of the six new JsonModelIT methods still fail
-- the reply-direction (decode) scenarios show zero events reaching the
extension for the reply value, and the encode-direction 100k scenario stops
short after a couple of transformed characters. Root cause not yet isolated.

Also merged origin/develop (TestBindingFactory reassembly + reply-direction
decode fixes, avro's own now-complete ModelExt composition test suite this
work mirrors). That merge exposed two pre-existing model-json.spec IT
failures unrelated to this change (shouldRejectJsonStrictMissingRequired
Fragmented, shouldRejectJsonAdditionalPropertyFragmented) -- confirmed by
isolated re-run -- caused by the engine's corrected frame reassembly timing
not matching the JSON spec scripts' expected streamed pre-reject output.
Not yet fixed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XC96PuggqzqgyXmhUuXEH5

* fix(model-json.spec): update fragmented reject scripts for structured delivery

Installing any JsonModelExtFactorySpi makes JsonModelHandlerImpl's exts
list non-empty for every model:json pipeline in the same JVM, forcing
STRUCTURED (canonical re-serialization) delivery globally rather than
byte-preserving splice -- not just for bindings that reference the
extension. Adding TestUppercaseJsonModelExtFactorySpi's test-scope
registration therefore changed the exact streamed pre-reject byte output
of two pre-existing scenarios that predate any extension: a KEY_NAME
event now commits "id": as one atomic re-serialized unit rather than
splicing the raw partial input, and a trailing comma before a still-
pending sibling property is no longer speculatively emitted.

Confirmed via isolated toggling of the extension's META-INF/services
registration that this is the actual cause (both tests pass with it
absent, fail identically with it present) -- not a stale rebuild.
Updated client.sent.json.strict.missing.required.fragmented (partial
output "{\"id\":" instead of "{\"id\"") and
client.sent.json.additional.property.fragmented (partial output
"{\"id\":42,\"status\":\"OK\"" instead of ...\"OK\",\" with a trailing
comma) to the real structured-delivery output, verified against a live
run. Also drops the ENGINE_BUFFER_SLOT_CAPACITY override on JsonModelIT's
shared EngineRule -- unlike AvroModelIT's own dedicated instance, this
one is shared by every test method in the class, including these two,
so it was an unnecessary and risky change to make just for the new ext
scenarios.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XC96PuggqzqgyXmhUuXEH5

* fix(model-json): resolve schema-id-0 ambiguity and buffer capacity for ext tests

json.ext.yaml's test catalog had no explicit numeric id, defaulting to 0 --
colliding with CatalogHandler.NO_SCHEMA_ID. JsonModelDecoderPipeline treats
schemaId == NO_SCHEMA_ID as "no schema resolved" and rejects outright, so
every reply-direction decode (which resolves via resolve(subject, version),
falling back to the catalog's own configured id when the subject isn't
dynamically registered) was rejected before ever reaching the installed
extension. Adding id: 1 (matching avro.ext.yaml's own convention) fixes it:
shouldApplyExtensionOnDecode and shouldApplyExtensionOnEncode now pass.

Restores JsonModelIT's ENGINE_BUFFER_SLOT_CAPACITY override (removed in the
previous commit): confirmed via a full local run that it doesn't affect the
two fragmented-reject tests after all -- their scripts declare an 8192-byte
window, well under either the 32768-byte default or the 65536-byte override,
so neither clamps it. The 100k-scale scenarios do need it: without it, the
reply-direction test crashed the engine worker with an IndexOutOfBoundsException
in TestBindingFactory's own reply-window drain (limit beyond maxLimit) --
this override eliminates that crash.

Status: shouldApplyExtensionOnDecode, shouldApplyExtensionOnEncode, and both
reject scenarios now pass -- 4 of 6 new tests green, no crashes, no
regressions in the rest of the suite (verified via full clean install).
The two 100k-scale scenarios (shouldDrainExtensionOverflowOnDecode/EncodeAcrossMultipleFrames)
still fail: the extension's captured buffer ends up with 165,535 characters
instead of 100,000 -- exactly 65,535 (2^16-1) more, matching the buffer slot
boundary -- pointing to a duplication interaction between the engine's own
slot-drain/resume cycling and the extension's own SUSPENDED/resume handling
for a value whose transformed output spans multiple frames. Not yet
isolated to a single root cause; separate from the schema-id and delivery-
mode fixes above.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01XC96PuggqzqgyXmhUuXEH5

* fix(model-json): re-capture, not append, deferred string fragments in test ext

JsonSource#getStringView() delivers the value's whole decoded-so-far
prefix on every fragment of a deferred (over-window) string, not a
delta -- confirmed against JsonExtractor's own handling of the same
contract. TestUppercaseJsonModelExtFactorySpi's onTargetString wrongly
treated each fragment as an increment to append, duplicating the
already-captured prefix on the final fragment. Re-capture (overwrite)
on every fragment instead, matching JsonExtractor's established
pattern, fixing the two 100k-scale drain scenarios.

---------

Co-authored-by: Claude <[email protected]>
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.

Declare AvroModelExtFactorySpi and wire provider-supplied pipeline stages in avro model

2 participants