Skip to content

feat(binding-kafka): stream value transforms directly into the cache, delete convertedFile - #2461

Merged
jfallows merged 11 commits into
developfrom
claude/zilla-plus-pii-status-nfzbgr
Aug 31, 2026
Merged

jfallows merged 11 commits into
developfrom
claude/zilla-plus-pii-status-nfzbgr

Conversation

@jfallows

@jfallows jfallows commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Description

On both the produce path (KafkaCacheClientProduceFactory) and the populate path (KafkaCacheServerFetchFactory), a cache entry's raw value bytes were written into logFile's value region unconditionally, per DATA fragment, as they arrived. Only at FIN did a configured value model's transform run — once, over the complete raw value read back out of logFile — writing its output into a separate per-segment file, convertedFile. Downstream fetch/cursor logic redirected reads to convertedFile's content whenever an entry had a valid convertedPosition().

The gap (#1688): a value model configured to transform sensitive content (e.g. a redaction/tokenization/encryption model for regulated fields) still left the original, untransformed bytes sitting at rest in the .log segment file, even though the API layer never served them.

This closes that gap by making the value's own on-disk field the transform's only destination:

  • KafkaCacheModel.transform(...) becomes genuinely incremental — callable once per DATA fragment as bytes stream in (UNDERFLOW/COMPLETE/REJECTED), rather than once at FIN over an already-fully-buffered value, with a small carry-over buffer retaining any unconsumed tail across fragments.
  • KafkaCacheEntry's value field is widened to reuse the existing KafkaCachePaddedValue struct (already used for paddedKey), so the entry's own value region can be reserved up front and finalized in place once a transform's real output length is known — mirroring how paddedKey already handles a transformed key.
  • The transform's output now streams directly into that reservation as fragments arrive, on both paths — plaintext never touches logFile when a value model is configured. The populate path additionally has to pre-claim a header-extraction envelope's scratch space before headers are known (fragments arrive well before FIN), solved by reserving a combined headers-worst-case + trailers-sized block up front and reusing it in place at finalize time.
  • convertedFile is deleted entirely — the file format, its KafkaCacheSegment plumbing, the cursor's value-splicing step, and the now-dead convertedPosition field on KafkaCacheEntry — along with refreshing runtime/binding-kafka/AGENTS.md's stale KafkaPipeline section (already-removed classes from an earlier refactor) with a description of the current transform/envelope architecture.

Filter semantics are unaffected: no KafkaFilterCondition implementation reads an entry's value, only its key/headers.

Test plan

  • Test-first throughout: each stage added/updated unit tests before implementation and confirmed they failed for the right reason first (a compile failure against a not-yet-generated flyweight accessor, or a runtime assertion against the old convertedFile-based behavior).
  • New/updated coverage in KafkaCacheModelTest (incremental transform: multi-fragment completion, reset-on-FIN/reject, UNDERFLOW-at-FIN treated as REJECTED) and KafkaCachePartitionTest (padded-value round trip, hash-reservation sizing unaffected by value padding, direct-streaming + multi-fragment + overflow-abort for both the produce and populate paths, proving via byte-scan that raw plaintext never appears in logFile).
  • KafkaCacheSegmentTest gained a filesystem check confirming no *.converted file exists after freeze().
  • ./mvnw clean verify -pl runtime/binding-kafka: 406 integration tests (all k3po ITs) + unit tests, 0 failures, checkstyle/license clean, JaCoCo coverage checks met — run after every stage, and again after rebasing onto latest develop.

Fixes #1688


Generated by Claude Code

claude added 11 commits August 31, 2026 03:22
transformValue.padding(...) was called with the first DATA fragment's own
length instead of the value's declared length, at both the produce-path and
populate-path reservation sites. Harmless for framing-only padding, but wrong
for any length-proportional bound, and load-bearing groundwork for #1688,
whose incremental transform needs the reservation sized from the full value.
Widen KafkaCacheModel with a fragment-wise transform() overload driven by
the caller's own DATA-frame flags, so a value model can be fed one DATA
fragment at a time instead of only once over an already-fully-buffered
value. Fixes the previous hardcoded FLAGS_INIT|FLAGS_FIN and unconditional
per-call reset() along the way, and retains any unconsumed tail internally
across UNDERFLOW so callers never manage a combined buffer themselves.

Ground-work for #1688: streaming a value transform's output directly into
the cache entry as bytes arrive, rather than only after the whole value is
already sitting in the log file, requires the model to be drivable
incrementally in the first place. The whole-value convenience overload is
kept for existing callers and now delegates to the new one.
…ePaddedValue

Replace KafkaCacheEntry's flat valueLen+value fields with the existing
KafkaCachePaddedValue struct (already used by convertedFile), mirroring how
paddedKey already works for the key side. Both write paths now reserve the
value's own padding region up front alongside its bytes, sized from a
valuePaddingMax the caller computes once and threads through newHeadIfNecessary
and the entry writers, kept out of the unrelated hash-file sizing term. The
populate path is brought in line with the produce path's reserve-then-write
shape for its value region, needed for either path to stream directly into
that reservation.

The transform's own output still lands in convertedFile unchanged at this
stage; this is a pure container reshape, verified by the existing
convertedFile-asserting test passing unmodified. Ground-work for #1688.
…ile (#1688)

Both the produce path (KafkaCacheClientProduceFactory) and the populate path
(KafkaCacheServerFetchFactory) now feed a value model transform's output
directly into the entry's own paddedValue reservation, per DATA fragment, via
KafkaCacheModel's incremental transform API. Raw wire bytes are never written
to logFile when a value model is configured -- eliminates the gap where
untransformed plaintext previously sat at rest in the segment's log file
before being copied into convertedFile.

The produce path already appends real headers immediately (known at Start),
so only its value-region writes needed to move to the incremental streaming
shape. The populate path is trickier: headers aren't known until
writeEntryFinish, but a composed extractHeaders-style transform's envelope
must be claimed before the first writeEntryContinue call. writeEntryStart now
reserves a worst-case headers+trailers+scratch region up front (reusing the
same trailersSizeMax-sized bytes as both the envelope's scratch during the
value drive and the entry's own final trailers), and writeEntryFinish writes
the real (smaller) headers/trailers in place, folding the leftover into the
entry's own trailing paddingLen/padding fields.

convertedFile is no longer written by either path; convertedPosition stays -1
for every entry with a value model configured. Deleting convertedFile and its
supporting infrastructure entirely is a follow-up.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CzxN4tJLhiHQ8ikNeuN8WS
KafkaCacheModel now retains cross-fragment state (a one-shot INIT flag plus a
carry buffer) between writeEntryContinue/writeProduceEntryContinue calls, so a
value or key transform abandoned mid-flight (INIT seen, no FIN reached) must
be reset before the same model instance processes another value.

This matters most for KafkaCacheServerFetchFanout, whose transformKey/
transformValue instances persist across a fetch reconnect: without a reset,
a value fetched right after reconnecting could have its first fragment
mistaken for a continuation of the value abandoned when the prior connection
dropped. Wire the reset into the reply-end/reply-abort/initial-reset handlers,
covering both the reconnect and disconnect outcomes. KafkaCacheClientProduceFactory's
per-stream cleanupClient gets the same reset for consistency, even though its
model instances are discarded along with the stream.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CzxN4tJLhiHQ8ikNeuN8WS
convertedFile has been dead weight since the previous commit: neither the
produce path nor the populate path writes to it anymore, and
convertedPosition is always -1. Remove it outright rather than leaving
unreachable infrastructure behind -- this cache is a local, ephemeral,
regenerable artifact, so there's no persisted-format compatibility concern.

- Delete KafkaCacheSegment's convertedFile field, its use in both
  constructors, its accessor, and its freeze()/delete()/onClosed() calls
- Delete KafkaCacheFile.Converted and its EXT_CONVERTED/FORMAT_CONVERTED_FILE
  constants
- Delete KafkaCacheCursorFactory's nextConvertedEntry() and its dispatch
  branch -- the entry's own paddedValue already holds the transformed bytes,
  so cursor iteration needs no value-splicing step anymore
- Delete the now-dead convertedPosition field from KafkaCacheEntry (internal.idl)
  and every FIELD_OFFSET_CONVERTED_POSITION/NO_CONVERTED_POSITION reference
- Add a filesystem check to KafkaCacheSegmentTest confirming no *.converted
  file exists after freeze()
- Rewrite runtime/binding-kafka/AGENTS.md's stale KafkaPipeline/KafkaEvent/
  KafkaSink section (already-removed classes from an earlier refactor) with a
  short description of KafkaCacheModel's incremental transform API and the
  reserve/stream/finalize write protocol this effort introduced

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CzxN4tJLhiHQ8ikNeuN8WS
…ad of re-reading it from disk

writeProduceEntryContinue and writeEntryContinue re-derived valuePaddingMax
on every call from its on-disk marker position. A transform whose output
grows past the raw value's declared length legitimately writes into that
same marker position, so a later fragment in the same value read back
corrupted data -- producing a wrong reservedMax, a wrong finalized
paddingLen, and a misplaced headers region that could crash the engine
worker thread.

The real HTTP-to-Kafka produce path splits a value across an INIT-flagged
empty-payload fragment, one or more payload fragments, and a FIN-flagged
empty-payload fragment, so the corrupting write and the later misread land
in different calls. Both callers now compute valuePaddingMax once at Start
and pass it through explicitly on every subsequent fragment instead.

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

Every production caller already named this buffer transformBuffer at the
call site; only KafkaCacheModel's own field/parameter name still used
scratch, which reads as placeholder/debug scaffolding rather than a named
production role.

Also add a root AGENTS.md directive on identifier naming (avoid
scratch/tmp-style placeholder names and avoid restating the type or
enclosing class) and on preferring self-describing code over comments.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01CzxN4tJLhiHQ8ikNeuN8WS
…r early completion

KafkaCacheModel's fragment-wise state machine reset itself (started=false)
the moment a pipeline reported COMPLETE, regardless of whether the caller's
own frame flags carried FIN. A self-delimiting value model -- a JSON-view
protobuf encode, for example -- can correctly recognize its own input is
complete from content alone (a closing brace) before the caller's own FIN
fragment arrives. The real HTTP-to-Kafka produce mapping still always
follows with a separate, genuinely empty FIN-flagged fragment; with state
already reset, KafkaCacheModel treated that trailing fragment as the start
of a brand new, invalid empty value and rejected it.

That spurious rejection on a well-formed payload then reached
markEntryDirty -> findAndMarkDirty, whose index lookup found nothing for
the entry, and an unguarded `assert dirtyEntry != null` (a no-op without
-ea) let the null through into entry.offset(), crashing the whole engine
worker thread rather than just failing the one request.

KafkaCacheModel now remembers an early completion and reports UNDERFLOW
until the caller's own FIN fragment actually arrives, absorbing it without
re-invoking the pipeline instead of starting a new value from zero bytes.

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

Reproduces the DATA fragmentation pattern from the real HTTP-to-Kafka
produce mapping (empty INIT declaring deferred length, a payload
fragment, an empty FIN) through a live engine with a real protobuf
value model, covering the valuePaddingMax and early-completion fixes
end-to-end rather than only at the unit level.
…dow carries no new bytes

AvroPipelineImpl and JsonPipelineImpl each left their parser positioned
at end-of-datum after an earlier call already reported COMPLETED (both
formats can recognize their own end before the caller's FIN arrives),
but never reset that state. A subsequent, genuinely empty final window
for the same datum re-entered the pump instead of being recognized as
already finished, and fell through to STARVED (avro) or REJECTED
(json) -- both violating the documented contract that a terminal
status is unambiguous once last is true. Track completion and answer
a matching trailing empty window with COMPLETED again, without
re-driving the parser.

Added regression coverage at the pipeline level (common-avro,
common-json) and through the model-avro decoder wrapper. Verified
common-protobuf does not share the defect: its explicit starved-state
tracking already drives a genuinely empty final window through to
COMPLETED.
@jfallows
jfallows merged commit 1fef2d8 into develop Aug 31, 2026
43 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.

Support length-changing model transforms in kafka cache storage's produce path

2 participants