You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "jordepic (via GitHub)" <gi...@apache.org> on 2026/08/17 02:25:25 UTC
[PR] Improve arrow-avro transport-bounded datum decoding [arrow-rs]
jordepic opened a new pull request, #10713:
URL: https://github.com/apache/arrow-rs/pull/10713
# Which issue does this PR close?
- Closes #10712.
# Rationale for this change
Kafka and similar transports already provide an external boundary for each Avro datum. The existing `Decoder::decode` path requires per-record framing, which forces bare-Avro consumers to prepend and copy a synthetic prefix or scan the schema merely to find the end of an already bounded datum.
Sparse nullable records also currently materialize placeholder values recursively for every null row. For union-like schemas with several nullable nested records, this repeats the same child traversal for long null runs.
# What changes are included in this PR?
- Add `Decoder::decode_datum` to decode exactly one unframed datum using the active writer schema and return the number of bytes consumed.
- Defer trailing nullable child placeholders and materialize them in bulk before the next non-null value or batch flush.
- Add a Criterion case modeling three sparse nullable nested event records with 100-row runs.
The deferred state is internal to the record decoder. Output remains ordinary Arrow arrays and child lengths are aligned before flush.
# Are these changes tested?
Yes.
- `cargo test -p arrow-avro --all-features`: 475 unit tests passed; 26 doc tests passed; 1 doc test ignored.
- `cargo clippy -p arrow-avro --all-targets --all-features -- -D warnings`
- `cargo fmt --all -- --check`
Criterion on an Apple M1 Max, comparing this branch to the saved `main` baseline for a complete 10,000-row batch:
| Benchmark | main median | this PR median | Change |
|---|---:|---:|---:|
| Sparse nullable nested records | 820.16 us | 581.44 us | -29.2% time / +41.3% throughput |
Command:
```shell
cargo bench -p arrow-avro --bench decoder -- 'SparseNested\(Struct\)/10000' --baseline main
```
The motivating downstream isolated benchmark decodes 8,192 Kafka-bounded Nexmark messages into Arrow, with polling, query execution, and sink work excluded. It measured:
- Direct one-datum decoding alone: 2.336M to 2.749M rows/s (+17.7%).
- Direct datum decoding plus deferred null runs: 2.336M to 4.712M rows/s (2.02x).
- A separate best-of-three final run: 4.768M rows/s (209.7 ns/row), 2.69x the Java RowData result.
The harness, methodology, profiles, and results are documented in the [StreamFusion optimization note](https://github.com/datafusion-contrib/StreamFusion/blob/5ed8a29/docs/optimizations/avro-one-datum-null-runs.md), with the integration in [StreamFusion commit 5ed8a29](https://github.com/datafusion-contrib/StreamFusion/commit/5ed8a2960d28318361f8fed474b279cb72f11f0b).
# Are there any user-facing changes?
Yes. `Decoder` gains the non-breaking public `decode_datum` method for externally framed, single-datum payloads. Existing framed decoding behavior is unchanged.
AI assistance disclosure: Codex was used to help port the implementation from StreamFusion, draft tests and the benchmark, and prepare the issue and PR text. The resulting code and all reported outputs were reviewed before submission, and I take responsibility for the contribution.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5434912548
Merging would be great, thank you Andrew!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "kinshuk-bb (via GitHub)" <gi...@apache.org>.
kinshuk-bb commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5336780735
@jordepic is there currently a way to convert multiple Avro Datums in a single .avro to a RecordBatches directly? A Raw Binary Encoded Avro
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "kinshuk-bb (via GitHub)" <gi...@apache.org>.
kinshuk-bb commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5350382931
@jordepic thank you! i was relying on adding framing just to decode to be sure i wouldn't face issues. will try this out now. An addition to the cargo docs that this is directly possible now would be great.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jecsand838 (via GitHub)" <gi...@apache.org>.
jecsand838 commented on code in PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#discussion_r3833146137
##########
arrow-avro/src/reader/mod.rs:
##########
@@ -736,6 +741,31 @@ impl Decoder {
Ok(total_consumed)
}
+ /// Decode exactly one unframed Avro datum with the active writer schema.
+ ///
+ /// This is intended for transports such as Kafka where the message boundary is external to
+ /// Avro. It returns the number of datum bytes consumed, allowing the caller to ignore transport
+ /// payload bytes after the first datum when its format contract requires that behavior.
+ /// Consecutive unframed datums can be decoded by repeatedly passing the unconsumed suffix.
+ /// If the current batch is full, this method returns `Ok(0)` until [`Self::flush`] is called.
+ ///
+ /// The decoder must already have the desired active fingerprint, and this method does not
+ /// inspect or switch framing fingerprints.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the datum is incomplete, malformed, or incompatible with the active
+ /// writer schema.
+ pub fn decode_datum(&mut self, data: &[u8]) -> Result<usize, AvroError> {
+ if self.remaining_capacity == 0 {
+ return Ok(0);
+ }
Review Comment:
The new unframed mode may make `Ok(0)` too ambiguous. An empty record or a record containing only `null` fields is a valid datum that consumes zero bytes but still appends one row. The same result currently means the batch was already full and no row was appended. A caller that interprets zero as flush and retry can therefore duplicate a successfully decoded row.
I'd recommending giving batch-full a distinct outcome such as `AvroError::BatchFull` or something along those lines:
```rust
if self.capacity == 0 {
return Err(AvroError::BatchFull);
}
// A successful zero-width datum remains unambiguously Ok(0)
let consumed = self.active_decoder.decode(data, 1)?;
self.capacity -= 1;
Ok(consumed)
```
##########
arrow-avro/src/reader/record.rs:
##########
@@ -717,9 +719,61 @@ impl Decoder {
inner.append_null()?;
}
Self::Union(u) => u.append_null()?,
- Self::Nullable(_, null_buffer, inner) => {
+ Self::Nullable(_, null_buffer, _, pending_nulls) => {
Review Comment:
This defers child placeholders, but each null still calls `NullBufferBuilder::append(false)`, so long null runs retain one bitmap write per row. The non-null path also calls the large `append_nulls` dispatcher when `pending_nulls == 0`.
Could we defer both the validity suffix and child placeholders behind one helper?
```rust
#[inline]
fn materialize_pending(
validity: &mut NullBufferBuilder,
values: &mut Decoder,
pending: &mut usize,
) -> Result<(), AvroError> {
let count = *pending;
if count == 0 {
return Ok(());
}
values.append_nulls(count)?;
validity.append_n_nulls(count);
*pending = 0;
Ok(())
}
```
Null branches would only increment `pending_nulls`. Before a non-null/default value or flush, call this helper; after successfully decoding a value, call `validity.append_non_null()`. This makes long and all-null runs bulk operations and avoids zero-count dispatch on dense nullable data.
##########
arrow-avro/src/reader/record.rs:
##########
@@ -717,9 +719,61 @@ impl Decoder {
inner.append_null()?;
}
Self::Union(u) => u.append_null()?,
- Self::Nullable(_, null_buffer, inner) => {
+ Self::Nullable(_, null_buffer, _, pending_nulls) => {
null_buffer.append(false);
- inner.append_null()?;
+ *pending_nulls += 1;
+ }
+ }
+ Ok(())
+ }
+
+ /// Append a run of null placeholders, deferring nullable children until their next value or
+ /// flush so sparse record subtrees can be materialized in bulk.
+ fn append_nulls(&mut self, count: usize) -> Result<(), AvroError> {
+ if count == 0 {
+ return Ok(());
+ }
+ match self {
+ Self::Null(size) => *size += count,
+ Self::Boolean(values) => values.append_n(count, false),
+ Self::Int32(values) | Self::Date32(values) | Self::TimeMillis(values) => {
+ values.resize(values.len() + count, 0)
+ }
+ Self::Int64(values)
+ | Self::Int32ToInt64(values)
+ | Self::TimeMicros(values)
+ | Self::TimestampMillis(_, values)
+ | Self::TimestampMicros(_, values)
+ | Self::TimestampNanos(_, values) => values.resize(values.len() + count, 0),
+ Self::Float32(values) | Self::Int32ToFloat32(values) | Self::Int64ToFloat32(values) => {
+ values.resize(values.len() + count, 0.0)
+ }
+ Self::Float64(values)
+ | Self::Int32ToFloat64(values)
+ | Self::Int64ToFloat64(values)
+ | Self::Float32ToFloat64(values) => values.resize(values.len() + count, 0.0),
+ Self::Binary(offsets, _)
+ | Self::String(offsets, _)
+ | Self::StringView(offsets, _)
+ | Self::BytesToString(offsets, _)
+ | Self::StringToBytes(offsets, _) => {
+ for _ in 0..count {
+ offsets.push_length(0);
+ }
+ }
+ Self::Record(_, children, _, _) => {
+ for child in children {
+ child.append_nulls(count)?;
+ }
+ }
+ Self::Nullable(_, null_buffer, _, pending_nulls) => {
+ null_buffer.append_n_nulls(count);
+ *pending_nulls += count;
+ }
+ other => {
+ for _ in 0..count {
+ other.append_null()?;
+ }
Review Comment:
The catch-all calls `append_null()` `count` times, re-running the full `Decoder` match for every placeholder. Consequently, nullable arrays, maps, fixed values, UUIDs, enums, decimals, custom primitives, and REE do not receive the intended bulk optimization.
Perhaps add direct bulk arms where possible? for example:
```rust
Self::Uuid(values) => {
values.resize(values.len() + 16 * count, 0);
}
Self::Fixed(width, values) => {
values.resize(values.len() + (*width as usize) * count, 0);
}
Self::Enum(values, _, _) => {
values.resize(values.len() + count, 0);
}
Self::Decimal128(_, _, _, builder) => {
builder.append_value_n(0, count);
}
Self::Decimal256(_, _, _, builder) => {
builder.append_value_n(i256::ZERO, count);
}
Self::RunEndEncoded(_, len, inner) => {
inner.append_nulls(count)?;
*len += count;
}
```
For offset-backed types, we could reserve `count` offsets before pushing repeated zero lengths. I would also make the match exhaustive and keep any necessarily per-row union handling explicit, so future variants cannot silently fall back to a slower implementation. This could always be looked into as a follow-up.
##########
arrow-avro/src/reader/mod.rs:
##########
@@ -736,6 +741,31 @@ impl Decoder {
Ok(total_consumed)
}
+ /// Decode exactly one unframed Avro datum with the active writer schema.
+ ///
+ /// This is intended for transports such as Kafka where the message boundary is external to
+ /// Avro. It returns the number of datum bytes consumed, allowing the caller to ignore transport
+ /// payload bytes after the first datum when its format contract requires that behavior.
+ /// Consecutive unframed datums can be decoded by repeatedly passing the unconsumed suffix.
+ /// If the current batch is full, this method returns `Ok(0)` until [`Self::flush`] is called.
+ ///
+ /// The decoder must already have the desired active fingerprint, and this method does not
+ /// inspect or switch framing fingerprints.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the datum is incomplete, malformed, or incompatible with the active
+ /// writer schema.
+ pub fn decode_datum(&mut self, data: &[u8]) -> Result<usize, AvroError> {
+ if self.remaining_capacity == 0 {
+ return Ok(0);
+ }
+ let consumed = self.active_decoder.decode(data, 1)?;
+ self.remaining_capacity -= 1;
+ self.awaiting_body = false;
+ Ok(consumed)
+ }
Review Comment:
I'd recommend we avoid adding a second public decoding method and instead select the input grammar when building the decoder.
A decoder should generally consume one stable wire format for its lifetime, and this follows existing arrow-rs patterns such as `arrow_json::StructMode`, IPC’s `DictionaryHandling`, and the Avro writer’s construction-time choice between `AvroSoeFormat` and `AvroBinaryFormat`.
I suggest replacing `decode_datum` with:
```rust
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DecoderMode {
#[default]
Framed,
UnframedDatum,
}
```
Then expose:
```rust
pub fn with_decoder_mode(mut self, mode: DecoderMode) -> Self {
self.decoder_mode = mode;
self
}
```
`Decoder::decode` can dispatch internally:
```rust
pub fn decode(&mut self, data: &[u8]) -> Result<usize, AvroError> {
match self.mode {
DecoderMode::Framed => self.decode_framed(data),
DecoderMode::UnframedDatum => self.decode_unframed(data),
}
}
```
##########
arrow-avro/src/reader/record.rs:
##########
@@ -276,7 +276,8 @@ enum Decoder {
#[cfg(feature = "avro_custom_types")]
RunEndEncoded(u8, usize, Box<Decoder>),
Union(UnionDecoder),
- Nullable(NullablePlan, NullBufferBuilder, Box<Decoder>),
+ /// Nullable value plus trailing null placeholders not yet materialized in the child decoder.
+ Nullable(NullablePlan, NullBufferBuilder, Box<Decoder>, usize),
Review Comment:
Adding `pending_nulls` as a fourth positional field makes the nullable state transitions difficult to audit across `append_null`, `append_nulls`, `append_default`, `decode`, and `flush`.
Could this state be represented by a named structure?
```rust
struct NullableDecoder {
plan: NullablePlan,
validity: NullBufferBuilder,
values: Box<Decoder>,
pending_nulls: usize,
}
```
A `materialize_pending()` method on this structure would centralize the invariant and ensure every transition updates the child, validity bitmap, and pending count consistently. If `append_nulls` is made exhaustive, `append_null()` could also delegate to `append_nulls(1)`, removing the duplicated per-variant implementation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5375510675
@alamb would you mind rerunning this guy?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5417220628
Sorry @alamb silly clippy formatting issue, could we give it another go?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5350191435
@kinshuk-bb Yes, for raw binary Avro containing multiple back-to-back datums encoded with the same known writer schema, this PR supports decoding them directly into RecordBatches without adding framing. Configure a Decoder with that writer schema, repeatedly call decode_datum on the remaining byte slice, advance by the returned consumed-byte count, and call flush whenever batch_is_full (plus once at the end). Each call decodes exactly one datum and leaves subsequent datums untouched.
If by `.avro` you mean a standard Avro object-container file, that is already supported today: ReaderBuilder::build reads the container header/schema and iterates over RecordBatches. The new method is specifically for raw datum streams/messages without an object-container header or per-record framing.
I am adding explicit coverage for concatenated raw datums and batch boundaries to make this use case clear.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5427546649
Sorry about the CI issues @alamb , I hope all should be well now and it can be rerun
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#discussion_r3866963639
##########
arrow-avro/src/lib.rs:
##########
@@ -64,6 +65,45 @@
//! # Ok(()) }
//! ```
//!
+//! ## Quickstart: unframed Avro datums *(runnable)*
+//!
+//! Kafka messages and other transports can contain bare Avro records without an OCF header,
+//! single-object prefix, or schema-registry framing. When the writer schema is already known,
+//! register it, select its fingerprint and [`reader::DecoderMode::UnframedDatum`], and call
+//! [`reader::Decoder::decode`] once per record. The returned byte count also supports
+//! consecutive datums in one buffer.
+//!
+//! ```
+//! use arrow_array::{Array, Int64Array};
+//! use arrow_avro::reader::{DecoderMode, ReaderBuilder};
+//! use arrow_avro::schema::{AvroSchema, SchemaStore};
+//!
+//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+//! let schema = AvroSchema::new(
+//! r#"{"type":"record","name":"Event","fields":[{"name":"id","type":"long"}]}"#
+//! .to_string(),
+//! );
+//! let mut store = SchemaStore::new();
+//! let fingerprint = store.register(schema)?;
+//! let mut decoder = ReaderBuilder::new()
+//! .with_writer_schema_store(store)
+//! .with_active_fingerprint(fingerprint)
+//! .with_decoder_mode(DecoderMode::UnframedDatum)
+//! .build_decoder()?;
+//!
+//! // Two consecutive records, {id: 7} and {id: 42}, in Avro zigzag encoding.
+//! let mut remaining: &[u8] = &[0x0e, 0x54];
+//! while !remaining.is_empty() {
+//! let consumed = decoder.decode(remaining)?;
Review Comment:
nice
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5350353265
@jecsand838 if you have any time to take a look in the next few days I'd greatly appreciate it! This is a really big win for StreamFusion and any other system trying to beat out avro processing from the JVM!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5350416604
@kinshuk-bb Addressed in 92a421091: the crate-level documentation now includes a runnable example decoding consecutive bare Avro datums directly with `Decoder::decode_datum`, and the reader/module/builder docs plus README now explicitly list unframed binary datums as a supported format.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5331168960
FYI @jecsand838 -- could you help review this PR?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5441384600
Thank you @jordepic and @jecsand838
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on code in PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#discussion_r3833317066
##########
arrow-avro/src/reader/mod.rs:
##########
@@ -736,6 +741,31 @@ impl Decoder {
Ok(total_consumed)
}
+ /// Decode exactly one unframed Avro datum with the active writer schema.
+ ///
+ /// This is intended for transports such as Kafka where the message boundary is external to
+ /// Avro. It returns the number of datum bytes consumed, allowing the caller to ignore transport
+ /// payload bytes after the first datum when its format contract requires that behavior.
+ /// Consecutive unframed datums can be decoded by repeatedly passing the unconsumed suffix.
+ /// If the current batch is full, this method returns `Ok(0)` until [`Self::flush`] is called.
+ ///
+ /// The decoder must already have the desired active fingerprint, and this method does not
+ /// inspect or switch framing fingerprints.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the datum is incomplete, malformed, or incompatible with the active
+ /// writer schema.
+ pub fn decode_datum(&mut self, data: &[u8]) -> Result<usize, AvroError> {
+ if self.remaining_capacity == 0 {
+ return Ok(0);
+ }
+ let consumed = self.active_decoder.decode(data, 1)?;
+ self.remaining_capacity -= 1;
+ self.awaiting_body = false;
+ Ok(consumed)
+ }
Review Comment:
good suggestion!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jordepic (via GitHub)" <gi...@apache.org>.
jordepic commented on code in PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#discussion_r3833397754
##########
arrow-avro/src/reader/mod.rs:
##########
@@ -736,6 +741,31 @@ impl Decoder {
Ok(total_consumed)
}
+ /// Decode exactly one unframed Avro datum with the active writer schema.
+ ///
+ /// This is intended for transports such as Kafka where the message boundary is external to
+ /// Avro. It returns the number of datum bytes consumed, allowing the caller to ignore transport
+ /// payload bytes after the first datum when its format contract requires that behavior.
+ /// Consecutive unframed datums can be decoded by repeatedly passing the unconsumed suffix.
+ /// If the current batch is full, this method returns `Ok(0)` until [`Self::flush`] is called.
+ ///
+ /// The decoder must already have the desired active fingerprint, and this method does not
+ /// inspect or switch framing fingerprints.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the datum is incomplete, malformed, or incompatible with the active
+ /// writer schema.
+ pub fn decode_datum(&mut self, data: &[u8]) -> Result<usize, AvroError> {
+ if self.remaining_capacity == 0 {
+ return Ok(0);
+ }
+ let consumed = self.active_decoder.decode(data, 1)?;
+ self.remaining_capacity -= 1;
+ self.awaiting_body = false;
+ Ok(consumed)
+ }
Review Comment:
Implemented in 2a5f2d925. The public decode_datum method is gone; ReaderBuilder::with_decoder_mode now selects DecoderMode::Framed (default) or DecoderMode::UnframedDatum at construction, and Decoder::decode dispatches internally. Updated the crate/module/builder docs, runnable example, README, and existing unframed tests to use the single decoding entry point.
##########
arrow-avro/src/reader/record.rs:
##########
@@ -717,9 +719,61 @@ impl Decoder {
inner.append_null()?;
}
Self::Union(u) => u.append_null()?,
- Self::Nullable(_, null_buffer, inner) => {
+ Self::Nullable(_, null_buffer, _, pending_nulls) => {
null_buffer.append(false);
- inner.append_null()?;
+ *pending_nulls += 1;
+ }
+ }
+ Ok(())
+ }
+
+ /// Append a run of null placeholders, deferring nullable children until their next value or
+ /// flush so sparse record subtrees can be materialized in bulk.
+ fn append_nulls(&mut self, count: usize) -> Result<(), AvroError> {
+ if count == 0 {
+ return Ok(());
+ }
+ match self {
+ Self::Null(size) => *size += count,
+ Self::Boolean(values) => values.append_n(count, false),
+ Self::Int32(values) | Self::Date32(values) | Self::TimeMillis(values) => {
+ values.resize(values.len() + count, 0)
+ }
+ Self::Int64(values)
+ | Self::Int32ToInt64(values)
+ | Self::TimeMicros(values)
+ | Self::TimestampMillis(_, values)
+ | Self::TimestampMicros(_, values)
+ | Self::TimestampNanos(_, values) => values.resize(values.len() + count, 0),
+ Self::Float32(values) | Self::Int32ToFloat32(values) | Self::Int64ToFloat32(values) => {
+ values.resize(values.len() + count, 0.0)
+ }
+ Self::Float64(values)
+ | Self::Int32ToFloat64(values)
+ | Self::Int64ToFloat64(values)
+ | Self::Float32ToFloat64(values) => values.resize(values.len() + count, 0.0),
+ Self::Binary(offsets, _)
+ | Self::String(offsets, _)
+ | Self::StringView(offsets, _)
+ | Self::BytesToString(offsets, _)
+ | Self::StringToBytes(offsets, _) => {
+ for _ in 0..count {
+ offsets.push_length(0);
+ }
+ }
+ Self::Record(_, children, _, _) => {
+ for child in children {
+ child.append_nulls(count)?;
+ }
+ }
+ Self::Nullable(_, null_buffer, _, pending_nulls) => {
+ null_buffer.append_n_nulls(count);
+ *pending_nulls += count;
+ }
+ other => {
+ for _ in 0..count {
+ other.append_null()?;
+ }
Review Comment:
Addressed in 2a5f2d925. append_nulls now matches Decoder exhaustively and has direct bulk arms for arrays/maps/strings with reserved offsets, fixed values, UUIDs, enums, all decimal widths, duration builders, custom primitive/temporal types, nested records, and run-end encoding. Union handling remains explicitly per-row where required, and append_null simply delegates to append_nulls(1).
##########
arrow-avro/src/reader/mod.rs:
##########
@@ -736,6 +741,31 @@ impl Decoder {
Ok(total_consumed)
}
+ /// Decode exactly one unframed Avro datum with the active writer schema.
+ ///
+ /// This is intended for transports such as Kafka where the message boundary is external to
+ /// Avro. It returns the number of datum bytes consumed, allowing the caller to ignore transport
+ /// payload bytes after the first datum when its format contract requires that behavior.
+ /// Consecutive unframed datums can be decoded by repeatedly passing the unconsumed suffix.
+ /// If the current batch is full, this method returns `Ok(0)` until [`Self::flush`] is called.
+ ///
+ /// The decoder must already have the desired active fingerprint, and this method does not
+ /// inspect or switch framing fingerprints.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if the datum is incomplete, malformed, or incompatible with the active
+ /// writer schema.
+ pub fn decode_datum(&mut self, data: &[u8]) -> Result<usize, AvroError> {
+ if self.remaining_capacity == 0 {
+ return Ok(0);
+ }
Review Comment:
Addressed in 2a5f2d925 with AvroError::BatchFull for unframed decoding when capacity is exhausted. A successful zero-width datum still returns Ok(0), and the new regression test covers both an empty record and a record containing only a null field, including flushing and decoding another row without duplication.
##########
arrow-avro/src/reader/record.rs:
##########
@@ -717,9 +719,61 @@ impl Decoder {
inner.append_null()?;
}
Self::Union(u) => u.append_null()?,
- Self::Nullable(_, null_buffer, inner) => {
+ Self::Nullable(_, null_buffer, _, pending_nulls) => {
Review Comment:
Implemented in 2a5f2d925. NullableDecoder::materialize_pending now bulk-materializes child placeholders and the validity suffix together, while null branches only increment pending_nulls. Non-null/default paths skip the bulk dispatcher when no nulls are pending and append validity only after the value succeeds. Added a regression test that verifies neither bitmap nor child values are touched during a 64-row null run.
##########
arrow-avro/src/reader/record.rs:
##########
@@ -276,7 +276,8 @@ enum Decoder {
#[cfg(feature = "avro_custom_types")]
RunEndEncoded(u8, usize, Box<Decoder>),
Union(UnionDecoder),
- Nullable(NullablePlan, NullBufferBuilder, Box<Decoder>),
+ /// Nullable value plus trailing null placeholders not yet materialized in the child decoder.
+ Nullable(NullablePlan, NullBufferBuilder, Box<Decoder>, usize),
Review Comment:
Implemented in 2a5f2d925 with a named NullableDecoder containing plan, validity, values, and pending_nulls. Its materialize_pending method owns the shared invariant, and append_null, bulk append, defaults, decoding, and flush all transition through that representation consistently.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Improve arrow-avro decoding for one-record messages [arrow-rs]
Posted by "jecsand838 (via GitHub)" <gi...@apache.org>.
jecsand838 commented on PR #10713:
URL: https://github.com/apache/arrow-rs/pull/10713#issuecomment-5333770915
> FYI @jecsand838 -- could you help review this PR?
Absolutely! I'll have time tonight / tomorrow morning to review this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org