Skip to content

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

Merged
jfallows merged 12 commits into
developfrom
claude/model-json-extensions-rwf73s
Aug 16, 2026
Merged

jfallows merged 12 commits into
developfrom
claude/model-json-extensions-rwf73s

Conversation

@jfallows

Copy link
Copy Markdown
Contributor

Description

Adds JsonModelExtFactorySpi/JsonModelExt/JsonModelExtContext/JsonModelExtHandler, the JSON-model analog of AvroModelExtFactorySpi — lets a provider install its own additional pipeline stage(s) into model: json's decode pipeline via ServiceLoader, discovered per schema/config through the existing generic ModelInfo.extensions() mechanism ($defs/models/model/allOf in the aggregated JSON schema). No behavior changes for configs that install no extension.

Building and exercising this against a real consumer (a decode-time field-disclosure extension) surfaced four latent bugs, all invisible until a live decode pipeline with an installed, value-substituting extension was exercised for the first time:

  • model-json's own schema patch wrongly closed options.value to provider extensions (additionalProperties: false) — model-avro's own schema patch has no such restriction; this one was inconsistent with it.
  • JsonModelDecoderPipeline conflated destination-buffer-sizing padding (decodePadding(), extension-inclusive) with the catalog's own source-side framing-byte skip count (extension-exclusive) — a new prefix() method separates the two, matching how AvroModelDecoderPipeline already keeps them apart.
  • common-json's JsonStream.into(JsonGeneratorEx) had no structured-delivery opt-out, unlike its into(JsonSink) sibling — a value-substituting stage needs one, since byte-preserving delivery splices bytes a substitute doesn't have. New into(JsonGeneratorEx, Map<String, ?>) overload mirrors JsonEx.createSink's existing config-bag convention.
  • TestBindingFactory (the type: test binding backing every k3po *IT.java test engine-wide) never handled ModelStatus.OVERFLOW from a model's own pipeline — a value whose transformed size exceeds the fixed model buffer spun forever against an already-full destination window with no exception. It also hardcoded every call's source-side flags to "complete message," so a value split across multiple DATA frames presented each continuation frame to the model as a spurious fresh restart, and destination-fill state reset on every call instead of persisting across frames. This is the same class of bug independently surfaced and fixed by PR fix(model-avro): fold installed extensions into the encoder pipeline too #2383 for the encode direction.

JsonTransformable also picks up the same self-bounded generic type parameter PR #2383 gave AvroTransformable, so JsonModelHandlerImpl.extend() no longer needs to cast the result of an installed extension's transform() back to JsonStream.

Test plan

  • ./mvnw clean verify -pl runtime/model-json,runtime/common-json — unit tests, JsonModelIT (10 tests), checkstyle, license — all pass
  • ./mvnw clean verify -pl runtime/engine — 208 tests including HalfDuplexIT/SimplexIT/DuplexIT (the k3po ITs exercising TestBindingFactory's DATA-frame semantics), all pass
  • ./mvnw clean verify -pl runtime/model-avro,runtime/model-protobuf,runtime/binding-kafka — broader regression sweep (395+ tests) against the TestBindingFactory fix, all pass
  • Confirmed the TestBindingFactory fix resolves a real, previously-latent regression in two existing JsonModelIT fragmented-schema-rejection tests before landing the final version

Fixes # (none — surfaced while building JsonModelExtFactorySpi for issue #1682, not tied to a specific bug report)


Generated by Claude Code

claude added 12 commits August 15, 2026 00:27
…peline 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
…ons.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.
Picks up test(engine): apply the configured value model as decoder on
reply direction too (#2381) -- required for JsonModelExtDisclosureIT to
exercise decode-time disclosure through a live engine via type: test.
…lled 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.
… 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.
…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.
…/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
…extensions-rwf73s

# Conflicts:
#	runtime/engine/src/test/java/io/aklivity/zilla/runtime/engine/test/internal/binding/TestBindingFactory.java
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
… 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
…r 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
… 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.
@jfallows
jfallows merged commit b0f704f into develop Aug 16, 2026
42 checks passed
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.

2 participants