Repository navigation
feat(RTAS) Assign fresh ids - #3066
Conversation
31387a5 to
34d83d6
Compare
| } | ||
|
|
||
| #[test] | ||
| fn test_assign_fresh_ids() { |
| } | ||
|
|
||
| #[test] | ||
| fn test_assign_fresh_ids_with_type() { |
There was a problem hiding this comment.
Ported from Java's testAssignFreshIdsWithType for the equivalent types currently supported by iceberg-rust.
|
@CTTY would you be able to help with a review here? Would love to get RTAS support in iceberg rust |
|
@laskoviymishka would you be able to make take a look here! Would love to be able to make progress towards RTAS support in iceberg-rust! |
laskoviymishka
left a comment
There was a problem hiding this comment.
The numbering engine here is correct — I hand-traced the struct two-pass, map key-before-value, and list element-first ordering against the Java source and all four tests, and the id assignment comes out right. Landing it as #[allow(dead_code)] behind the #3056 TODO is a fine way to stage this too; no complaints on the scaffolding.
What I'd want resolved before this merges is the start_from contract, because every RTAS PR built on top of this inherits its semantics. Right now start_from is neither documented nor enforced, and a reused base id never consumes a fresh-id slot — so if the #3056 caller seeds it from a schema's highest_field_id() instead of the table's last_column_id()+1 (the way Java's buildReplacement does), a new column can silently be assigned the id of a previously-dropped column. Nothing here or in build() catches that, and it's exactly the class of spec-violating id reuse that corrupts historical reads across Java/PyIceberg/us. A precondition doc plus a debug_assert closes it cheaply — details inline.
Everything else is smaller: the returned schema_id shouldn't be treated as authoritative, the alias-remap error path is reachable but untested, and this is now the third copy of the field-tree walker (worth a follow-up to factor, not a blocker for this PR). Fix the start_from contract and I'll take another pass.
| use super::utils::try_insert_field; | ||
| use super::*; | ||
|
|
||
| pub(crate) fn assign_fresh_ids(schema: Schema, base: &Schema, start_from: i32) -> Result<Schema> { |
There was a problem hiding this comment.
The contract on start_from is the load-bearing thing here, and right now it's neither documented nor enforced. id_for only advances next_field_id on a miss, so a reused base id never consumes a slot — which means start_from has to sit past every id reachable from base, not just past schema's own ids. With base = {"a": 5}, replacement [a, b], start_from = 5, a reuses 5 and b also gets 5; the only thing that catches it is the generic duplicate-id check in build() ("Found duplicate 'field.id' 5"), which gives zero hint the real cause is start_from being too low.
The subtler hazard is what #3056 will seed this with. Java's TableMetadata.buildReplacement seeds from the table-wide lastColumnId — monotonic, and it reserves the ids of columns already dropped from the current schema — not from any single schema's highest_field_id(). If the follow-up seeds start_from from updated_schema.highest_field_id()+1, a brand-new column can be handed the id of a column that was dropped from the current schema: that id is absent from both base and the new schema, so nothing here or in build() fires, and we get spec-violating id reuse that corrupts historical reads and manifests keyed on that field id. The correct seed is table_metadata.last_column_id()+1 — the sibling UpdateSchema already does exactly this (update_schema.rs:338).
I'd document the precondition on the fn plainly (callers must pass table_metadata.last_column_id()+1, never a schema's highest_field_id()) and add a debug_assert!(start_from > base.highest_field_id()) as a cheap guard. While you're there, a short rustdoc covering the reuse-by-name behavior and the roles of schema/base/start_from would help — none of it is derivable from the signature today.
| let alias_to_id = assigner.apply_to_aliases(alias_to_id)?; | ||
|
|
||
| Schema::builder() | ||
| .with_schema_id(schema_id) |
There was a problem hiding this comment.
We thread the incoming schema_id straight through, but Java's 3-arg assignFreshIds never propagates it — the real schema-id is arbitrated later in addSchemaInternal, whose equivalent here is TableMetadataBuilder::add_schema (which documents that the provided schema_id may not be used). As long as #3056 routes the output through add_schema this is inert, but the test asserting schema_id() == 1 treats the preserved id as meaningful, which could nudge a caller into persisting it directly. I'd note in the rustdoc that the returned schema_id isn't authoritative and must be re-arbitrated via add_schema, and relax that assertion.
| .build() | ||
| } | ||
|
|
||
| struct AssignFreshIds { |
There was a problem hiding this comment.
This is the third near-identical copy of the field-tree id walker — ReassignFieldIds (id_reassigner.rs) and the private one in transaction/update_schema.rs are the other two, and apply_to_identifier_fields/apply_to_aliases here are byte-for-byte identical to id_reassigner's. The only genuinely new logic is id_for's base-name lookup. Three ~100-line stateful walkers means any fix to overflow handling, error wording, or traversal order has to land in three places. Not blocking this PR, but I'd like us to parameterize ReassignFieldIds with a strategy for "pick the id for an old id" (default fresh, overridable to check base first) and share the apply_to_* helpers instead of growing a third copy — worth at least a follow-up issue.
| .collect() | ||
| } | ||
|
|
||
| fn apply_to_aliases(&self, aliases: BiHashMap<String, i32>) -> Result<BiHashMap<String, i32>> { |
There was a problem hiding this comment.
Unlike identifier_field_ids, which build() validates via validate_identifier_ids, alias_to_id has no equivalent validation — so this "not found" branch is genuinely reachable: an alias pointing at a field dropped in the replacement schema lands right here, and it's untested. I'd add a small regression test that feeds an alias for a dropped field and asserts the error, so the branch is pinned.
| element_field: Arc::new(element_field), | ||
| })) | ||
| } | ||
| Type::Map(map) => { |
There was a problem hiding this comment.
This resolves new_key_id and new_value_id together before recursing into either subtree, whereas ReassignFieldIds assigns the key's id and fully recurses the key before touching the value. Both orders are deliberate — this one matches Java's key-then-value-then-recurse, and test_assign_fresh_ids_assigns_map_ids_before_nested_types pins it — but the divergence from the near-identical sibling is silent. A one-line comment on this arm saying key and value ids are resolved together before recursing, intentionally unlike ReassignFieldIds, would keep someone from "harmonizing" the two and quietly breaking the ordering the test enforces.
| fn new(target: &Schema, base: &Schema, start_from: i32) -> Self { | ||
| Self { | ||
| next_field_id: start_from, | ||
| target_names: target.field_id_to_name_map().clone(), |
There was a problem hiding this comment.
new only borrows target, so this deep-clones the whole HashMap<i32, String> even though the caller drops schema immediately after. Since assign_fresh_ids already destructures schema, pull id_to_name out of the destructure and take it by value:
let Schema { r#struct, schema_id, identifier_field_ids, alias_to_id, id_to_name, .. } = schema;
let mut assigner = AssignFreshIds::new(id_to_name, base, start_from);Saves a full copy of every field name on wide schemas.
| } | ||
| } | ||
|
|
||
| fn id_for(&mut self, old_id: i32) -> Result<i32> { |
There was a problem hiding this comment.
id_for reads like a pure getter but it advances next_field_id on a miss — unlike id_reassigner's visibly separate increase_next_field_id() step. A reader tracing how many ids get consumed can easily miscount. I'd rename it to something like resolve_or_assign_id, or drop a one-line doc noting the side effect.
|
Thanks for the review! Comments are addressed. I've chosen to leave off the Instead I've documented the contract on the function and added I'll file a follow-up issue for factoring the three walkers together rather than growing this PR. |
laskoviymishka
left a comment
There was a problem hiding this comment.
Most of round-1 is addressed — the doc now spells out the last_column_id() + 1 contract, checked_add handles overflow, schema_id is called out as non-authoritative, and the alias-for-dropped-field and dropped-column-id tests both landed. Thanks for those.
The one thing still open is the enforcement I asked for last round: the contract is documented but not asserted. A debug_assert in AssignFreshIds::new would make a too-low start_from fail loudly in dev/test as a contract violation, rather than surfacing two layers down as a generic duplicate-id error from build() — that's the corruption path I described last round, and it's exactly the misuse the doc now warns against. Left the specific line inline.
Everything else is small and inline (a variant-field clone, a HashSet-order test assertion). Add the assert and I'm happy here.
| } | ||
|
|
||
| impl AssignFreshIds { | ||
| fn new(target_names: HashMap<i32, String>, base: &Schema, start_from: i32) -> Self { |
There was a problem hiding this comment.
The doc contract landed, thanks — but this is still the one thing from last round I'd want enforced, not just documented. A debug_assert in new turns a too-low start_from from the cryptic build() duplicate-id error into a contract violation that fires in dev/test, right where a caller seeds from highest_field_id() + 1:
debug_assert!(
start_from > base.field_id_to_name_map().keys().copied().max().unwrap_or(0),
"start_from ({start_from}) must exceed base's highest id; pass table_metadata.last_column_id() + 1",
);It won't catch a dropped id sitting above the current highest — that all-time property still lives in last_column_id() — but it trips on the common misuse the doc now warns against, which is what I was after last round.
| outer_fields | ||
| .into_iter() | ||
| .map(|field| { | ||
| if field.field_type.is_primitive() { |
There was a problem hiding this comment.
is_primitive() is false for Type::Variant, so every variant field falls into the else branch and pays an Arc::unwrap_or_clone + re-alloc just for assign_type to hand back the same Type::Variant. if field.field_type.is_primitive() || field.field_type.is_variant() skips it. The same thing lives in id_reassigner.rs:55 — worth fixing both so they stay in step.
| } | ||
|
|
||
| #[test] | ||
| fn test_assign_fresh_ids_does_not_reuse_dropped_column_ids() { |
There was a problem hiding this comment.
identifier_field_ids() iterates a HashSet, so collecting to Vec and comparing against vec![8] only holds because there's a single element — it'll flake the moment a second identifier field is added. Compare against a HashSet instead.
laskoviymishka
left a comment
There was a problem hiding this comment.
Three rounds in, and it really is down to the one thing: the start_from contract reads well now, but it's still only documented, not enforced. A debug_assert!(start_from > base.highest_field_id(), ...) in AssignFreshIds::new is the whole ask — it turns a too-low start_from into a loud failure at the call site instead of a duplicate-id error two layers down in build(). Same request as the last two rounds; I'd really like to see it land before we merge, because it's the dropped-id reuse path I flagged in round 1 and the guard costs one line.
While we're in there, the doc's still a touch optimistic about that path — it says a too-low start_from surfaces "only as a generic error from build()", but the dropped-column case is exactly the one that doesn't: those ids slip through and build() succeeds. The assert can only be a partial guard, so the doc should name that silent case rather than imply build() catches everything. And the does_not_reuse_dropped_column_ids test only runs the correct call — a companion case with the naive start_from would actually demonstrate the hazard it names.
One new thing I couldn't fully verify: our struct traversal is two-pass where Java's visitor looks one-pass depth-first, which would make fresh ids diverge across clients (fragility, not corruption). Left it as a question inline. The variant-field clone and the loop-test assertion from last round are still open too, but those are small — the assert is the one that's holding this.
| } | ||
|
|
||
| impl AssignFreshIds { | ||
| fn new(target_names: HashMap<i32, String>, base: &Schema, start_from: i32) -> Self { |
There was a problem hiding this comment.
Third round on this one. The contract's documented but still not enforced — a debug_assert here in new turns a too-low start_from into a loud failure at the call site instead of surfacing two layers down as a build() duplicate-id error. Same ask as the last two rounds; this closes it.
debug_assert!(
start_from > base.highest_field_id(),
"start_from must exceed every id the table has assigned; pass last_column_id() + 1"
);One refinement while we're in here: the doc says a too-low start_from surfaces "only as a generic error from build()", but the dropped-column case is exactly the one that doesn't — those ids slip through and build() succeeds. The assert above can only be a partial guard (> highest_field_id() won't catch every dropped-id gap), so the doc should name that silent path rather than imply build() catches everything.
There was a problem hiding this comment.
Added the assert 2e8e469 with a comment explaining why this isn't load baring.
| Ok(id) | ||
| } | ||
|
|
||
| fn assign_fields(&mut self, fields: Vec<NestedFieldRef>) -> Result<Vec<NestedFieldRef>> { |
There was a problem hiding this comment.
New this round and I'm not fully sure — worth verifying against Java. We assign all sibling ids at a struct level before recursing into any nested type (two-pass), but Java's TypeUtil.assignFreshIds runs through CustomOrderSchemaVisitor, where iterating the lazy field results assigns-and-recurses together, so depth-first one-pass is the natural behavior there.
If Java is one-pass, a replacement with new fields at multiple nesting levels gets different fresh ids from us — not corruption (reused ids still match by name), but cross-client schema diffs would diverge. I couldn't pull the AssignFreshIds.struct() body to confirm; could you check whether Java assigns per-field depth-first here? If it's genuinely two-pass, this is fine as-is.
There was a problem hiding this comment.
Checked, Java is two-pass, so this is fine as-is. AssignFreshIds.struct runs two sequential loops: the first does newIds.add(idFor(name(fields.get(i).fieldId()))) for every field, under the comment "assign IDs for this struct's fields first"; only the second takes futures.iterator() and calls types.next(), which is what forces the recursion. The laziness in CustomOrderSchemaVisitor is what enables assigning sibling ids before descending. Likewise list assigns the element id before future.get(), and map assigns both key and value before either.
test_assign_fresh_ids_reuses_full_names_and_assigns_new_ids_in_correct_order pins this
| outer_fields | ||
| .into_iter() | ||
| .map(|field| { | ||
| if field.field_type.is_primitive() { |
There was a problem hiding this comment.
Still here from last round: is_primitive() is false for Type::Variant, so a variant field takes the else branch and does an unwrap_or_clone + assign_type round-trip that returns it unchanged. !field.field_type.is_nested() is the predicate you actually want. id_reassigner.rs:55 has the identical check — worth fixing both in one go.
| self.old_to_new_id.get(&id).copied().ok_or_else(|| { | ||
| Error::new( | ||
| ErrorKind::DataInvalid, | ||
| format!("Identifier Field ID {id} not found"), |
There was a problem hiding this comment.
Small one while we're here: "Identifier Field ID {id} not found" is title-cased but the rest of the module is lowercase ("field does not exist", "field ids must be unique"). "identifier field id {id} not found" matches — same fix applies to the copy in id_reassigner.rs:126.
|
|
||
| let assigned = assign_fresh_ids(schema, &empty_schema(), 11).unwrap(); | ||
|
|
||
| assert_eq!(assigned.as_struct(), expected.as_struct()); |
There was a problem hiding this comment.
Also still open from last round — the bare assert_eq! across 17 type variants won't tell you which test_type failed. assert_eq!(assigned.as_struct(), expected.as_struct(), "failed for type: {test_type:?}") fixes it.
| .build() | ||
| .unwrap(); | ||
|
|
||
| let assigned = assign_fresh_ids(replacement, &base, 6).unwrap(); |
There was a problem hiding this comment.
This passes for the wrong reason — the name says the function avoids dropped-column ids, but the function has no internal guard and the test only runs the correct call (start_from=6). A companion case with start_from=4 (the naive highest_field_id()+1 mistake) asserting fresh gets id 4 would actually demonstrate the hazard and make clear it's the caller's contract, not the function's. Same dropped-id gap as the assert thread above.
laskoviymishka
left a comment
There was a problem hiding this comment.
Most of round 3 is in — the companion naive-seed test (test_assign_fresh_ids_seeded_too_low_reuses_dropped_column_id, nicely factored behind schemas_with_dropped_column_ids()) and the failed for type: {test_type:?} loop assertion both landed. Thanks for those. And the two-pass traversal question I left open last round is resolved: Java's AssignFreshIds.struct() is two-pass as well (pre-assign loop, then the futures), and assigns_map_ids_before_nested_types pins the order — no cross-client divergence, so that one's closed.
The assert I'd been asking for since round 2 is in now — but your own new seeded_too_low test is what convinces me it needs to be a returned error rather than a debug panic. It seeds base.highest_field_id() + 1 = 4, which clears the assert (4 > 3), and then asserts retired id 4 comes back on fresh — so the guard sails right past the dropped-id reuse I flagged in round 1, and in release it compiles out and guards nothing at all. (The comment above the assert even says it trips the highest_field_id() + 1 mistake, but that's the exact seed the test shows passing.)
So the ask evolves one step: convert the debug_assert to Err(DataInvalid), and ideally take last_column_id instead of start_from so the precondition lives in the signature and matches what the #3056 caller holds. Then seeded_too_low flips to expect that error instead of pinning the corruption. That's the one thing holding it; the rest is a nit. Specifics inline.
| fn new(target_names: HashMap<i32, String>, base: &Schema, start_from: i32) -> Self { | ||
| // Partial guard only: it trips the common `base.highest_field_id() + 1` mistake, but ids | ||
| // dropped above `base`'s highest still slip through, as that bound lives in `last_column_id`. | ||
| debug_assert!( |
There was a problem hiding this comment.
Let's convert this to a returned Err(DataInvalid) rather than a debug_assert. Your own seeded_too_low test is the clincher: seed base.highest_field_id() + 1 = 4 clears the assert (4 > 3) and still lands on retired id 4 — the dropped-id reuse from round 1 walks straight past the guard, and in release the assert compiles out and guards nothing (on top of panicking in library code, which we don't do elsewhere).
I'd rather take last_column_id than start_from and derive the seed internally, so the contract lives in the signature and matches what the #3056 caller actually holds (table_metadata.last_column_id()):
if last_column_id < base.highest_field_id() {
return Err(Error::new(
ErrorKind::DataInvalid,
format!(
"last_column_id ({last_column_id}) is below base.highest_field_id() ({})",
base.highest_field_id()
),
));
}
let start_from = last_column_id.checked_add(1).ok_or_else(|| { /* overflow */ })?;An in-place if … return Err that keeps start_from works too, but then the dropped-id case still rides on the caller seeding correctly — so I lean toward taking last_column_id. wdyt?
(The comment just above is backwards, fwiw — it says the assert trips the highest_field_id() + 1 mistake, but that's the exact seed your test shows passing.)
| // A seed of 4 clears the `debug_assert` in `new` (base's highest id is 3) and `build()` | ||
| // sees no duplicates, so the retired id 4 is reused silently: the caller's contract, and | ||
| // the limit of the assert. | ||
| let assigned = assign_fresh_ids(replacement, &base, base.highest_field_id() + 1).unwrap(); |
There was a problem hiding this comment.
Once the guard returns an error, this test should assert that error instead of pinning the corruption. Right now it locks in fresh.id == 4 (a retired id) as the expected result, so a future fix that returns Err for the too-low seed makes this test fail — the wrong direction. Flip it to assign_fresh_ids(...).unwrap_err() and check err.kind() == ErrorKind::DataInvalid, and the comment can describe the rejection rather than the silent reuse.
| pub use self::visitor::*; | ||
| pub(super) mod _serde; | ||
| // TODO: Use for table replacement in https://github.com/apache/iceberg-rust/issues/3056. | ||
| #[allow(dead_code)] |
There was a problem hiding this comment.
Small thing while we're here — #[expect(dead_code)] instead of #[allow] (assuming MSRV ≥ 1.81) will warn and self-remove once the #3056 caller lands and uses the module; the #[allow] just lingers after it's no longer dead.
There was a problem hiding this comment.
Tried this, but it breaks CI. In test builds the module isn't dead code (the tests in it use it), so the expectation goes unfulfilled:
error: this lint expectation is unfulfilled
error: could not compile `iceberg` (lib test) due to 1 previous error
make check-clippy runs cargo clippy --all-targets --all-features --workspace -- -D warnings, and --all-targets includes the test target, so it's a hard failure rather than a warning. Sticking with #[allow] here.
laskoviymishka
left a comment
There was a problem hiding this comment.
I think this is good to merge overall.
Will keep it soaking for day or two.
|
We good to ship @laskoviymishka? |
Resolve id_reassigner.rs conflict: main migrated the error constructors to the invalid_data! macro (apache#2928) while this branch lowercased the identifier field message. Keep both. Apply the same macro migration to the new assign_fresh_ids.rs.
|
🌬️ ⛵ |
Which issue does this PR close?
What changes are included in this PR?
Adds an
assign_fresh_idsschema utility, modeled on Java'sAssignFreshIdsandTypeUtil.assignFreshIds.Fields present in the base schema keep their IDs by full field name, including nested fields. New fields receive increasing IDs from the supplied starting point, using the same struct, list, and map assignment order as Java. The reassigned schema retains its structure, defaults, identifier fields, aliases, and schema ID.
Are these changes tested?
Yes. The unit tests port Java's
testAssignFreshIdsandtestAssignFreshIdsWithTypefor the equivalent types currently supported by iceberg-rust. Additional tests cover full-name reuse, schema metadata, and Java-compatible nested struct, list, and map ID ordering.AI Disclosure
Used to review and write tests.