Skip to content

fix: reconstruct protobuf schema fields in linear time#7766

Merged
Xuanwo merged 3 commits into
mainfrom
xuanwo/fix-linear-schema-reconstruction
Jul 14, 2026
Merged

fix: reconstruct protobuf schema fields in linear time#7766
Xuanwo merged 3 commits into
mainfrom
xuanwo/fix-linear-schema-reconstruction

Conversation

@Xuanwo

@Xuanwo Xuanwo commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Why

Schema decoding currently rebuilds a tree from flat protobuf fields by calling mut_field_by_id for every child. Each lookup traverses the partially built tree, making wide schemas O(N²). The same conversion is used by raw file schema decoding and dataset manifest decoding; on the 65,536-physical-column fixture the lookup dominated profiles.

Solution

Build fields into an input-ordered arena, resolve unique parent IDs through an ID-to-node map, then materialize children in reverse arena order. Valid schemas preserve root and child order with O(total fields) time and memory. Malformed duplicate IDs retain the legacy first depth-first parent match; missing or forward parents now return errors through TryFrom<&Fields> and TryFrom<FieldsWithMeta>.

The reader, manifest, transaction, and Python protobuf boundaries now propagate this error (ValueError in Python). Wide/deep correctness coverage and a Criterion scaling benchmark cover 1,024 through 65,536 physical columns.

Read-path impact

Raw/self-describing opens still fetch and decode file schema but reconstruct it linearly. Dataset manifest opens pay the same linear conversion once. Known-schema metadata-index fragment reads continue to skip the file schema buffer entirely; only their full-metadata fallback decodes and benefits from this change.

Performance

Measured on the same m7i.4xlarge EC2 host in us-east-2 with Rust 1.97.0 and the repository's release-with-debug profile. The fixture contains 32,768 two-leaf structs: 65,536 physical columns and 98,304 protobuf schema nodes. The valid-schema baseline restores the previous per-child mut_field_by_id lookup; the benchmark variants otherwise use identical code and fixture shapes.

Pure reconstruction uses three measured samples for each variant:

Physical columns Schema nodes Before After Speedup
1,024 1,536 2.080 ms 0.202 ms 10.30x
4,096 6,144 31.943 ms 0.960 ms 33.27x
16,384 24,576 845.834 ms 3.972 ms 212.95x
65,536 98,304 17,312.360 ms 16.769 ms 1,032.40x

Across the endpoints, the empirical scaling exponent drops from 2.17 to 1.06, discriminating quadratic-like from linear growth on this fixture.

End-to-end values are medians of three baseline samples and ten fixed samples. Read bytes, I/O counts, and observed result counts match before and after for every row.

Path Backend / cache Before After Speedup
Raw file open + query local cold 18,120.450 ms 199.642 ms 90.77x
Raw file open + query local hot 18,089.921 ms 162.132 ms 111.58x
Raw file open + query S3 17,511.494 ms 367.527 ms 47.65x
Self-describing metadata open local cold 17,908.873 ms 78.325 ms 228.65x
Self-describing metadata open local hot 17,988.429 ms 63.903 ms 281.50x
Self-describing metadata open S3 17,262.306 ms 153.614 ms 112.38x
Read all file metadata local cold 17,974.323 ms 181.297 ms 99.14x
Read all file metadata local hot 18,064.959 ms 147.584 ms 122.41x
Read all file metadata S3 17,404.097 ms 297.587 ms 58.48x
Dataset manifest open local cold 17,172.622 ms 55.073 ms 311.82x
Dataset manifest open local hot 17,160.633 ms 44.528 ms 385.39x
Dataset manifest open S3 16,908.815 ms 115.787 ms 146.03x

Known-schema metadata opens bypass reconstruction and serve as an unaffected control:

Backend / cache Before After
local cold 7.635 ms 7.697 ms
local hot 0.868 ms 1.317 ms
S3 61.781 ms 64.014 ms

The control ranges overlap, and their absolute median differences are 0.062–2.233 ms. Affected end-to-end paths save 16.79–17.93 seconds per open on this fixture.

This is independent of indexed metadata structural projection.

Summary by CodeRabbit

  • Bug Fixes
    • Improved schema reconstruction validation now rejects missing or invalid parent references and enforces correct parent ordering.
    • Schema decoding during metadata, manifest, transaction, and reader operations now uses fallible reconstruction and returns clearer errors when schema data is invalid.
  • Tests
    • Added regression coverage for missing parent references with a specific error message, plus coverage for wide/deep nested schemas and legacy duplicate field ID behavior.
  • Performance / Benchmarks
    • Added Criterion benchmark for schema reconstruction on wide, large-nesting inputs.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Schema reconstruction now validates parent relationships through fallible APIs, propagates errors across Rust and Python deserialization paths, adds regression coverage, and introduces a benchmark for wide nested schemas.

Changes

Schema reconstruction and error propagation

Layer / File(s) Summary
Fallible schema reconstruction
rust/lance-file/src/datatypes.rs
Adds validated field-tree reconstruction, metadata conversion, duplicate-ID handling, and tests for nesting and invalid parents.
Deserialization error propagation
rust/lance-file/src/previous/format/metadata.rs, rust/lance-file/src/reader.rs, rust/lance-table/src/format/manifest.rs, rust/lance/src/dataset/transaction.rs
Updates schema decoding paths to use fallible conversions and propagate reconstruction errors.
Python reconstruction errors
python/src/schema.rs, python/python/tests/test_schema.py
Maps reconstruction failures to ValueError and tests missing-parent handling.
Schema reconstruction benchmark
rust/lance-file/Cargo.toml, rust/lance-file/benches/schema.rs
Adds a Criterion benchmark for wide nested schema reconstruction at several field counts.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Protobuf
  participant Deserializer
  participant SchemaTryFrom
  participant Schema
  Protobuf->>Deserializer: provide encoded schema fields
  Deserializer->>SchemaTryFrom: convert protobuf fields
  SchemaTryFrom->>SchemaTryFrom: validate parent relationships
  SchemaTryFrom->>Schema: materialize reconstructed schema
  Schema-->>Deserializer: return schema or error
Loading

Suggested reviewers: beinan, wjones127

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: faster protobuf schema reconstruction in linear time.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch xuanwo/fix-linear-schema-reconstruction

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added A-python Python bindings A-encoding Encoding, IO, file reader/writer bug Something isn't working labels Jul 13, 2026
@codecov

codecov Bot commented Jul 13, 2026

Copy link
Copy Markdown

@Xuanwo
Xuanwo marked this pull request as ready for review July 14, 2026 06:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@python/python/tests/test_schema.py`:
- Around line 66-73: Add context to
test_lance_schema_from_protos_rejects_missing_parent by replacing the
hand-encoded field_proto literal with an encoded Field protobuf message where
practical; otherwise document each wire-format byte segment and its
corresponding name, id, parent_id, and logical_type field. Preserve the test’s
missing-parent setup and expected ValueError assertion.

In `@rust/lance-file/benches/schema.rs`:
- Around line 20-29: Add a doc comment to wide_two_leaf_structs documenting that
-1 denotes the root parent, each struct occupies a three-ID block containing one
parent and two leaves, and fields are emitted in pre-order. Keep the benchmark
fixture logic unchanged.

In `@rust/lance-file/src/datatypes.rs`:
- Around line 102-125: Add a concise doc comment to first_field_index_by_id
documenting that it performs pre-order depth-first traversal and returns the
first matching node, preserving legacy tie-breaking when duplicate field IDs
exist.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e27f9c01-5466-4882-a91b-90a5207d911c

📥 Commits

Reviewing files that changed from the base of the PR and between a3d4719 and 6bf30e5.

📒 Files selected for processing (9)
  • python/python/tests/test_schema.py
  • python/src/schema.rs
  • rust/lance-file/Cargo.toml
  • rust/lance-file/benches/schema.rs
  • rust/lance-file/src/datatypes.rs
  • rust/lance-file/src/previous/format/metadata.rs
  • rust/lance-file/src/reader.rs
  • rust/lance-table/src/format/manifest.rs
  • rust/lance/src/dataset/transaction.rs

Comment thread python/python/tests/test_schema.py
Comment thread rust/lance-file/benches/schema.rs
Comment thread rust/lance-file/src/datatypes.rs

@BubbleCal BubbleCal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice changes!

@westonpace westonpace left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just one nit that we might want to use TryFrom

Comment thread rust/lance-file/src/datatypes.rs Outdated
/// assert_eq!(schema.metadata["owner"], "lance");
/// # Ok::<(), lance_core::Error>(())
/// ```
pub fn try_into_schema(self) -> Result<Schema> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not impl TryFrom<FieldsWithMeta> for Schema?

Comment thread rust/lance-file/src/datatypes.rs Outdated
/// assert_eq!(schema.fields[0].name, "value");
/// # Ok::<(), lance_core::Error>(())
/// ```
pub fn try_to_schema(&self) -> Result<Schema> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same question. Why not TryFrom?

Comment thread rust/lance-file/src/datatypes.rs Outdated
Comment on lines +137 to +139
/// Parent fields must appear before their children. Duplicate field IDs are
/// retained for backwards compatibility, and parent references use the
/// legacy first depth-first match.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you expand on the last two sentences here a bit?

Suggested change
/// Parent fields must appear before their children. Duplicate field IDs are
/// retained for backwards compatibility, and parent references use the
/// legacy first depth-first match.
/// Parent fields must appear before their children. Some historical
/// manifests may have duplicate ids. If so, we will fall back to the
/// legacy behavior which is to pick the first instance of the id as
/// the parent of a field.

Comment on lines +208 to +224
let mut fields_by_node = Vec::with_capacity(nodes.len());
fields_by_node.resize_with(nodes.len(), || None);
for (node_index, mut node) in nodes.into_iter().enumerate().rev() {
node.field.children.reserve(node.child_indices.len());
for child_index in node.child_indices {
let child = fields_by_node
.get_mut(child_index)
.and_then(Option::take)
.ok_or_else(|| {
Error::internal(format!(
"Schema field arena node {child_index} was not materialized before its parent"
))
})?;
node.field.children.push(child);
}
fields_by_node[node_index] = Some(node.field);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the forward - backward traversal, clever 😄

@Xuanwo

Xuanwo commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

The failure is not related.

@Xuanwo
Xuanwo merged commit 8276d34 into main Jul 14, 2026
40 of 42 checks passed
@Xuanwo
Xuanwo deleted the xuanwo/fix-linear-schema-reconstruction branch July 14, 2026 17:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-encoding Encoding, IO, file reader/writer A-python Python bindings bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants