Skip to content

feat(reader): apply ManifestAugmentingReader in ResultReaderFactory - #35

Merged
vikrantpuppala merged 1 commit into
mainfrom
feat/reader-manifest-augmenter
May 20, 2026
Merged

vikrantpuppala merged 1 commit into
mainfrom
feat/reader-manifest-augmenter

Conversation

@vikrantpuppala

@vikrantpuppala vikrantpuppala commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

augment_schema_with_manifest was already in the kernel on ResultReaderAdapter, attaching Databricks-specific per-column metadata (databricks.type_name, databricks.type_text, precision, scale, interval kind) from the SEA ResultManifest onto the result schema's fields. Bindings consume these to recover the precise server-reported type for columns whose Arrow shape collapses (VARIANT → Utf8, intervals → Interval, GEOMETRY/GEOGRAPHY → Utf8).

But the augmenter was only reachable through ResultReaderAdapter (the Arrow-FFI shape); the live execute path uses the kernel's own ResultReader trait directly, so the metadata never reached ResultStream::schema() consumers.

Surfaced when the Python connector (databricks-sql-python#793) added VARIANT detection via field.metadata[b"databricks.type_name"] and saw empty metadata everywhere — VARIANT columns kept reporting as string rather than variant.

Fix

Introduce ManifestAugmentingReader — a thin wrapper implementing the kernel's ResultReader trait. Exposes the augmented schema via schema() and re-projects each emitted RecordBatch onto that schema so batch.schema() carries the metadata too.

Wired at ResultReaderFactory::create_reader rather than at the call site (SeaRestTransport::execute_and_read). create_reader is the single seam every consumer goes through — sync execute, async submit/await_result, all of metadata_v0's list_* — so any future caller automatically benefits without having to remember to wrap. create_reader is split into a thin public wrapper that calls a new private create_inner_reader (does the CloudFetch / inline / empty selection) and wraps the result once.

Pass-through when manifest = None so paths without column info (test mocks, edge cases) don't change shape.

Test plan

  • cargo +stable fmt --all -- --check clean
  • cargo clippy --all-targets -- -D warnings clean
  • cargo test --workspace — 382 lib + 15 metadata wiremock + all integration suites pass
  • Two new unit tests for ManifestAugmentingReader (metadata-attached + pass-through paths)
  • End-to-end: rebuilt the wheel and ran the comparator (databricks-driver-test#304) — VARIANT columns now report as variant end-to-end, closing 3 comparator diffs.

This pull request and its description were written by Claude Code.

@vikrantpuppala
vikrantpuppala force-pushed the feat/reader-manifest-augmenter branch from 6670bab to 6627b6e Compare May 19, 2026 11:02
@vikrantpuppala vikrantpuppala changed the title feat(reader): wire ManifestAugmentingReader into execute_and_read feat(reader): apply ManifestAugmentingReader in ResultReaderFactory May 19, 2026
@gopalldb

Copy link
Copy Markdown
Collaborator

Important

I1. RecordBatch::try_new failure on re-projection is documented as a data_loss error, but is also effectively unreachable — worth either upgrading to Error::internal or testing the failure path

reader/mod.rs:505-513:
let columns: Vec<arrow_array::ArrayRef> = batch.columns().to_vec();
RecordBatch::try_new(self.schema.clone(), columns)
.map(Some)
.map_err(|e| {
crate::kernel_error::Error::data_loss()
.message(format!("manifest reproject: {e}"))
})

augment_schema_with_manifest preserves field types, order, and count (it only mutates Field::metadata()). So the only way RecordBatch::try_new fails here is if the inner reader returned a batch whose array
count/types don't match its own declared schema — i.e. a bug in the inner reader, not a data-shape issue with the augmentation.

Two thoughts:

  1. data_loss is the wrong code. This isn't data corruption / partial response from the server; it's a kernel-internal invariant violation. Error::internal is more honest. The user-facing message "manifest
    reproject: ..." hints at the internal-bug nature already.
  2. The failure path has no test. If someone refactors augment_schema_with_manifest to (say) skip a column when the manifest has fewer entries than the batch's schema, this code silently starts hitting the
    failure path with no test coverage. Suggestion: add a unit test where the inner schema's column count diverges from the augmented schema — verify the right error code, message, and that the error propagates
    (doesn't panic).

Not blocking; the case is exceptional. Worth a one-line follow-up.

I2. The wrapper allocates per next_batch call — fine, but worth a doc note

Every next_batch allocates:

  1. Vec of length num_columns (the to_vec() at reader/mod.rs:506).
  2. A new RecordBatch struct (the try_new).

For CloudFetch streams with thousands of small batches, this is N small allocations. The Vec reuses the column Arcs (no data copy), but the Vec itself is fresh per call.

Performance: in practice, the per-batch overhead is dominated by the network fetch + Arrow IPC decode upstream of this. The augmentation overhead is microseconds per batch. ✓

Suggestion: add a one-line doc note acknowledging the per-batch Vec allocation. Sets expectations for future maintainers who profile and wonder if there's a no-op path when manifest = None:

/// The pass-through path (manifest = None) still re-projects to
/// self.schema even though self.schema is identical to the
/// inner's schema. Could be optimised to skip the rebuild in the
/// None case if it ever matters for perf.

Or — if you want to actually optimize — store an Option for the augmented schema and skip the rebuild when it's None. ~10 LOC; saves the per-batch Vec + try_new for the manifest-less path.
Probably not worth doing today.

Smaller comments

S1. ManifestAugmentingReader::new returns Result but the only failure path is inner.schema()?

reader/mod.rs:483-491:
pub(crate) fn new(
inner: Box<dyn ResultReader + Send>,
manifest: Option<&ResultManifest>,
) -> Result {
let schema = inner.schema()?;
let schema = match manifest {
Some(m) => ResultReaderAdapter::augment_schema_with_manifest(&schema, m),
None => schema,
};
Ok(Self { inner, schema })
}

inner.schema() is the only fallible call — augment_schema_with_manifest is infallible. Constructor returns Result only because of that one ?. Fine; the alternative (panic on schema fetch failure) is worse.

S2. metadata_v0's list_* path goes through Transport::list_* which all call execute_and_read — covered automatically

The PR description claims metadata_v0's list_* methods benefit too. Verified: every Transport::list_catalogs / list_schemas / list_tables / list_columns / list_primary_keys / list_foreign_keys /
list_functions / list_procedures implementation in client/sea.rs ultimately calls execute_and_read → create_reader → augmentation. ✓

So metadata results (which already get JDBC-shape reshape via PR #33) also get manifest metadata attached. The two stack cleanly — ThriftReshapingReader wraps ManifestAugmentingReader wraps the inner reader.
Worth verifying this stacking order is what we want; the order is: from_reader(ThriftReshapingReader(create_reader(...))), so the augmenting reader is the inner of the two, and Thrift reshape happens on top
of augmented batches.

That means: after PR #33's reshape, the augmented metadata is still present on the inner Arrow arrays but the outer batch's Field objects are the JDBC-shape ones constructed in thrift_shape::GET__SCHEMA,
which don't include databricks.
metadata. Possibly a regression for metadata queries: if a wrapper queries m.list_columns(...) and reads field.metadata() expecting to find databricks.type_name, it'll be
empty because the outer reshape rebuilt the schema from scratch.

Worth verifying: is this a real issue or is the metadata only needed on the execute-path (not metadata-path)? The PR description points at the connector's VARIANT detection on execute results — fine for that
case. But if metadata list_columns is supposed to also surface databricks.type_name, the Thrift reshape is the bug.

Suggestion: confirm with the connector folks whether m.list_columns(...) results need the databricks.* metadata on the column fields. If yes, follow-up on PR #33's reshape_columns to copy through manifest
metadata onto the JDBC-shape TYPE_NAME column (or onto field-level metadata of the appropriate output column). Not in scope for this PR.

S3. Test helper reuse — MockReader::new(vec![batch])

The tests use MockReader::new(vec![batch]) which presumably already exists in the test module. ✓ No new helpers needed for the two new tests.

S4. PR description's "single insertion point" framing

The doc comment at reader/mod.rs:74-83 and the PR description both lean on "single insertion point." Worth noting in code that the other create_reader-like path is ResultReaderAdapter::new (Arrow-FFI shape,
public). That path also augments the schema (it was the original site). So strictly: there are now two places augmentation happens — ResultReaderAdapter::new and ManifestAugmentingReader::new — but they
share the same augment_schema_with_manifest helper, so the metadata-attachment behavior is consistent.

Not a bug. Just worth knowing for whoever maintains this in a year: "augmentation happens at two sites, both call augment_schema_with_manifest."

S5. ResultManifest is passed as Option<&ResultManifest> — borrow lifetime is fine

The constructor borrows manifest: Option<&ResultManifest> and never stores it (only the derived schema is stored). The augmented schema is a fresh SchemaRef, so there's no lifetime entanglement between the
wrapper and the manifest. ✓ Standard "consume in the constructor, store the derived value" pattern.

S6. next_batch re-projection happens unconditionally even when manifest was absent

When manifest = None, self.schema is just the inner reader's schema — identical content. The RecordBatch::try_new rebuild creates an identical batch (same data, same schema). Cheap (Arcs reused) but
unnecessary. See I2 — could skip the rebuild in this case.

`augment_schema_with_manifest` was added on `ResultReaderAdapter`
to attach Databricks-specific per-column metadata
(`databricks.type_name`, `databricks.type_text`, precision, scale,
interval kind) from the SEA `ResultManifest` onto the result
schema's fields. Bindings consume these to recover the precise
server-reported type for columns whose Arrow shape collapses
(VARIANT → Utf8, intervals → Interval, GEOMETRY/GEOGRAPHY → Utf8).

But the augmenter was only reachable through ResultReaderAdapter
(the Arrow-FFI shape); the live execute path uses the kernel's own
ResultReader trait directly, so the metadata never reached
ResultStream::schema() consumers.

Surfaced when the Python connector
(databricks-sql-python#793) added VARIANT detection via
`field.metadata[b"databricks.type_name"]` and saw empty metadata
everywhere — VARIANT columns kept reporting as `string` rather
than `variant`.

Fix: introduce ManifestAugmentingReader — a thin wrapper implementing
the kernel's ResultReader trait. Exposes the augmented schema via
schema() and re-projects each emitted RecordBatch onto that schema
so batch.schema() carries the metadata too.

Wired at ResultReaderFactory::create_reader rather than at
SeaRestTransport::execute_and_read: create_reader is the single
seam every consumer goes through, so any future caller (beyond
the current execute_and_read path) automatically benefits without
having to remember to wrap. Split create_reader into a thin
public wrapper that calls create_inner_reader (does the
CloudFetch vs inline vs empty selection) and wraps the result
once.

Pass-through when manifest = None so paths without column info
(test mocks, edge cases) don't change shape.

Two new unit tests cover metadata-attached + pass-through paths.

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
@vikrantpuppala
vikrantpuppala force-pushed the feat/reader-manifest-augmenter branch from 6627b6e to ab099c6 Compare May 20, 2026 05:26
@vikrantpuppala

Copy link
Copy Markdown
Collaborator Author

Thanks for the careful pass. Addressed in ab099c6:

  • I1 (error code) ✅ Changed the rebuild failure to Error::internal() with a sharper message that names the invariant violation. You're right — data_loss is for actual data corruption / partial server response, not an internal-shape mismatch.

    Skipped the regression test. The failure requires constructing a BadReader whose declared schema() lies about its next_batch() output, which exercises RecordBatch::try_new more than ManifestAugmentingReader. Happy to add if you'd rather.

  • S4 (two augmentation sites) ✅ Added a doc note on create_reader calling out ResultReaderAdapter::new as the other site that runs the same helper. Should keep future maintainers from being confused.

  • I2 / S6 (per-batch alloc + None pass-through cost) Skipping — the per-batch Vec<ArrayRef> of Arcs is microseconds and dwarfed by upstream I/O / Arrow decode. Happy to revisit if a profile flags it.

  • S2 (stacking with ThriftReshapingReader) Real interaction worth calling out. The order is from_reader(ThriftReshapingReader(create_reader(augmented_inner))), so when metadata_v0::list_columns runs, the databricks.* metadata that the augmenter attached to the underlying SHOW result is not visible on the outer JDBC-shape Field objects (TYPE_NAME, TABLE_CAT, …) because the reshape rebuilds the schema from GET_COLUMNS_SCHEMA.

    I think that's actually correct in this case: the JDBC-shape columns are named differently from the SHOW columns the manifest describes, so copying databricks.type_name for the SHOW columnType field onto the JDBC TYPE_NAME field would be semantically wrong. The precise per-row type info that consumers want is already in the TYPE_NAME value, not in field metadata. Open to revisiting if a concrete connector use case shows up.

  • S1 / S3 / S5 observations, no action.

Final state: 382 lib + 15 metadata wiremock + all integration suites still pass.

@vikrantpuppala
vikrantpuppala merged commit 73cde68 into main May 20, 2026
vikrantpuppala added a commit that referenced this pull request May 20, 2026
Consolidates `ManifestAugmentingReader` (PR #35) into a new
`ResultPostProcessor` that owns every per-batch transform the kernel
does on the way out to consumers, in a single pass:

- manifest-driven metadata attachment
  (`databricks.type_name` / `type_text` / precision / scale /
  interval kind);
- optional compact-JSON stringification of `List` / `LargeList` /
  `FixedSizeList` / `Map` / `Struct` columns, opted into per session
  via `ResultConfig::complex_types_as_json`.

A single `Option<BatchTransform>` closure captures the active
transforms at construction time. When neither is active, `next_batch`
is true pass-through (no `RecordBatch::try_new` rebuild). When at
least one is active, both run in one fused walk so we never pay
multiple rebuilds for the same upstream batch.

The JSON format mirrors the Thrift wire form the server emits when
`complexTypesAsArrow=false` — what PySQL's Thrift backend and JDBC's
`DatabricksArray.toString()` / `DatabricksMap.toString()` /
`DatabricksStruct.toString()` already deliver to callers today.
Bindings that surface a flat-text view (PySQL when
`_use_arrow_native_complex_types=False`, future JDBC kernel
migration) flip the flag; ADBC and Arrow-native consumers leave it
off and pay no cost.

Verified e2e against pecotesting: default path returns native Arrow
complex shapes, JSON-on path returns the expected compact JSON
including nested ARRAY<STRUCT>.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
vikrantpuppala added a commit that referenced this pull request May 25, 2026
Consolidates `ManifestAugmentingReader` (PR #35) into a new
`ResultPostProcessor` that owns every per-batch transform the kernel
does on the way out to consumers, in a single pass:

- manifest-driven metadata attachment
  (`databricks.type_name` / `type_text` / precision / scale /
  interval kind);
- optional compact-JSON stringification of `List` / `LargeList` /
  `FixedSizeList` / `Map` / `Struct` columns, opted into per session
  via `ResultConfig::complex_types_as_json`.

A single `Option<BatchTransform>` closure captures the active
transforms at construction time. When neither is active, `next_batch`
is true pass-through (no `RecordBatch::try_new` rebuild). When at
least one is active, both run in one fused walk so we never pay
multiple rebuilds for the same upstream batch.

The JSON format mirrors the Thrift wire form the server emits when
`complexTypesAsArrow=false` — what PySQL's Thrift backend and JDBC's
`DatabricksArray.toString()` / `DatabricksMap.toString()` /
`DatabricksStruct.toString()` already deliver to callers today.
Bindings that surface a flat-text view (PySQL when
`_use_arrow_native_complex_types=False`, future JDBC kernel
migration) flip the flag; ADBC and Arrow-native consumers leave it
off and pay no cost.

Verified e2e against pecotesting: default path returns native Arrow
complex shapes, JSON-on path returns the expected compact JSON
including nested ARRAY<STRUCT>.

Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
vikrantpuppala added a commit that referenced this pull request May 25, 2026
## Summary

Adds an opt-in kernel feature that converts complex columns (`ARRAY` /
`MAP` / `STRUCT`, plus VARIANT / GEOMETRY / GEOGRAPHY pass-through) into
compact JSON `Utf8` strings, byte-for-byte matching what the Databricks
server emits on the Thrift wire when `complexTypesAsArrow=false` and
what JDBC's `DatabricksArray.toString()` / `DatabricksMap.toString()` /
`DatabricksStruct.toString()` produce.

Also folds `ManifestAugmentingReader` (PR #35) into a new
`ResultPostProcessor` that owns *every* per-batch transform the kernel
does on the way out, in a single pass.

## Why

Two consumers already produce the same byte-for-byte JSON today:

- **JDBC**'s `DatabricksArray.toString()` / `DatabricksMap.toString()` /
`DatabricksStruct.toString()` (~200 LOC of hand-rolled serialization).
- **The Python connector's Thrift backend**, where the server
stringifies server-side when `complexTypesAsArrow=false`.

The new SEA-family paths (PySQL native SEA backend, kernel backend)
don't have this path. The Thrift vs Kernel comparator currently surfaces
5 diffs in the `COMPLEX_TYPES_DISABLED` suite from exactly this gap.

Putting the JSON serialization in the kernel means **one
implementation**, **one source of truth on the format**, and every
binding that wants the flat-text view (PySQL, JDBC's eventual kernel
migration, future Go / Node) opts in without re-implementing it. ADBC
leaves the flag off and pays no cost.

## What's in this PR

### Design doc — \`docs/designs/complex-types-json-stringify.md\`

- Problem statement + why per-binding implementations are the wrong
factoring.
- API shape (session-level bool, no wire change).
- JSON format rules (compact, JDBC-matching) per Databricks type.
- Why one consolidated post-processor instead of stacked wrappers.
- Migration shape per binding.

### Implementation

- \`src/config.rs\`: \`ResultConfig::complex_types_as_json\` (default
\`false\`).
- \`src/reader/post_processor/mod.rs\`: \`ResultPostProcessor\` with
\`Option<BatchTransform>\`. Constructor inspects upstream schema +
manifest + options once and picks the closure shape (none /
re-project-only / fused-walk). Hot path is one \`match\` per batch.
- \`src/reader/post_processor/json.rs\`: pure per-type encoder
(\`append_json\`) handling primitives, decimals, dates/timestamps,
binary→base64, intervals, ARRAY/MAP/STRUCT recursion, and
VARIANT/GEOMETRY/GEOGRAPHY metadata-driven pass-through.
- \`src/reader/mod.rs\`: \`ResultReaderFactory\` now wraps with
\`ResultPostProcessor\`; the old \`ManifestAugmentingReader\` is gone
(folded in).
- \`src/session.rs\`: \`result_to_post_process_options(...)\` plumbs the
flag from \`ResultConfig\` into the factory.

### Performance shape

- Single \`next_batch\` indirection regardless of how many transforms
are active.
- Pass-through (no manifest + no JSON) is genuinely free — no
\`RecordBatch::try_new\`, no \`Vec<ArrayRef>\` rebuild.
- Manifest-only path: one cheap re-project reusing upstream
\`ArrayRef\`s.
- Both transforms active: one fused walk emits the new \`RecordBatch\`
in one pass.

## Test plan

- [x] 13 unit tests in \`json.rs\` covering each primitive, ARRAY / MAP
/ STRUCT recursion, escape rules, NaN / Inf handling, empty containers,
VARIANT pass-through, GEOMETRY quoting.
- [x] 8 integration tests in \`post_processor/mod.rs\` covering:
pass-through path, manifest-only path, JSON path for List / Map /
Struct, null handling, JSON-off doesn't touch complex columns.
- [x] \`cargo +stable fmt --all\` clean.
- [x] \`cargo clippy --all-targets -- -D warnings\` clean.
- [x] Full lib + integration suite passes (\`cargo test\`).
- [x] \`cargo test --test v0_execute_e2e -- --ignored\` against
pecotesting: 11/11 pass, including new
\`complex_types_as_json_flag_stringifies_complex_columns\` verifying:
- Default flag → server returns native \`List\` / \`Map\` / \`Struct\`.
- Flag on → kernel rewrites them to \`Utf8\` carrying \`[1,2,3]\`,
\`{\"k1\":\"v1\",\"k2\":\"v2\"}\`, \`{\"a\":\"foo\",\"b\":1}\`, and
nested \`[{\"a\":\"x\",\"b\":1},{\"a\":\"y\",\"b\":2}]\`.
- [ ] Follow-up: comparator \`THRIFT_VS_KERNEL_COMPLEX_DISABLED\` suite
(in \`databricks-driver-test\`) — should drop from 5 diffs to 0 once the
connector flips the flag.

## Migration

- Default \`false\`: kernel behaviour unchanged for existing consumers.
- PySQL connector will flip the flag when
\`_use_arrow_native_complex_types=False\` (follow-up in
\`databricks-sql-python\`).
- JDBC: when it migrates to the kernel, can drop its ~200 LOC of Java
JSON serialization.
- ADBC: leaves the flag off, no change.

This pull request and its description were written by Claude Code.

---------

Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
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