Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: Refactor Table Metadata Tests #11947

Open
wants to merge 18 commits into
base: main
Choose a base branch
from

Conversation

HonahX
Copy link
Contributor

@HonahX HonahX commented Jan 10, 2025

  • Add new unit tests for V3 metadata
  • Refactor TableMetadata tests by parametrizing table format versions in all tests

[Updated] The above 2 will be included in a separate PR: #12025

  • Add MetadataTestUtils.TableMetadataBuilder and MetadataTestUtils.BaseSnapshotBuilder to simply test metadata and snapshot build. This will reduce the amount of test code changes when adding new fields to metadata/snapshot.

Not included:

@github-actions github-actions bot added the core label Jan 10, 2025
@HonahX HonahX marked this pull request as ready for review January 10, 2025 19:54
@HonahX
Copy link
Contributor Author

HonahX commented Jan 10, 2025

cc @RussellSpitzer @flyrain
May I ask for your help to review this?

return new TableMetadataBuilder(formatVersion);
}

public static class TableMetadataBuilder {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added test-only builders for TableMetadata and BaseSnapshot. This shall reduce the amount of code changes in tests when adding new fields.

cc: @RussellSpitzer

Copy link
Contributor

Choose a reason for hiding this comment

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

why do we need this class and why can't we just use the normal table metadata builder?

Copy link
Member

@RussellSpitzer RussellSpitzer Jan 14, 2025

Choose a reason for hiding this comment

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

I noted this in the other comment, but our normal builder has safety checks which prohibit us from building invalid or arbitrary Table Metadata. This makes it impossible to use in testing situations where we may want to do something like force the snapshot id or put invalid variables into the TableMetadata.

Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe a better name is UnsafeTableMetadataBuilder?

Copy link
Contributor

Choose a reason for hiding this comment

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

After looking through the tests, I'm a bit skeptical about the value of this change. I agree with making it easier to build these objects, but now it seems harder to read the tests because they are more verbose and it isn't clear how the builder methods interact. In some places, the snapshots and table metadata are built with each value explicitly, but in other places they are filled with example values and then overridden.

That makes me unsure about what the tests are testing and that they are correct. For instance, if a new field is added to the parser, it would be easy to see that the test case doesn't need to change because we use example data. But if this builder isn't updated then it could easily not exercise the parser because TableMetadata always uses a builder that fills in default values. I liked the existing code where a new field in TableMetadata required a change in tests to supply the new field's value. Then it was clear that the new field had to be handled by the parser.

Copy link
Member

Choose a reason for hiding this comment

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

That's actually why I prefer the builder, I believe the tests are much more readable without specifying all of the parameters each time and we would still force all tests to have to deal with new parameters if they all use the builder that defaults to an example fully-non-null metadata.

Previously, the worst case scenario of this approach (having to set every single property) was required for every single test. First, several local variables are created and set to arbitrary default values, seldomly these values are relevant to the test, then we call a constructor which has many arguments mostly null or empty.

For me this made every test a bit of a hunt and check, which args are being set explicitly because of this test and which just need to be non-null so that the test doesn't break? Previously, I had no idea what some tests were testing or if they were correct without IDE hints on which arg was which. For example, the test for UUID being null sets 3/ 30~ args to null and sets specific values to 13 of the args. Of all of these values only 1 of those nulls actually matters to the test and everything else is essentially noise.

If we do want to stick with using the full constructor everywhere I think that's fine but if our rational is that we don't want to force these tests to be able to ignore constructor changes then I think we need to never have secondary constructors for TableMetadata. I know adding more constructors is a a common review comment when we add new args and I think we should just articulate that we won't do that for these key constructors in Metadata and BaseSnapshot.

Copy link
Contributor Author

@HonahX HonahX Jan 16, 2025

Choose a reason for hiding this comment

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

I think we can approach this from two different perspectives, depending on the purpose of the test.

Type 1: Comprehensive Tests Covering All or Most Fields

These tests ensure that TableMetadata as a whole is correctly processed, typically verifying round-trip serialization, deserialization, and backward compatibility. Examples include:

  • testJsonConversion – Ensures that all fields are correctly handled in serialization and deserialization.
  • testBackwardCompatibility – Verifies that metadata remains compatible across versions.

For these tests, I agree that continuing to use the constructor directly makes sense. Since these tests require explicitly setting all fields, any new field will naturally require an update, ensuring that the test remains valid and that new fields are properly incorporated.

Type 2: Targeted Tests for Specific Features or Edge Cases

These tests focus on specific behaviors or individual fields rather than the full metadata structure. For example:

  • testInvalidMainBranch – Only checks whether currentSnapshotId matches the main branch.
  • testJsonWithPreviousMetadataLog – Specifically validates how the metadataLog field is handled.

For these tests, I think the builder approach provides a readability advantage. It allows us to set only the relevant fields, making it clear what the test is actually focusing on while avoiding unnecessary details. This helps maintain clarity and ensures that unrelated fields don’t introduce noise into the test.

In conclusion, introducing the builder can significantly simplify unit tests with a more focused scope, while the constructor remains useful for comprehensive tests. One key benefit of this mixed approach is that comprehensive tests are relatively few, meaning we can still reduce the overall effort required when adding new fields.

There are also opportunities to further refine this PR by eliminating unnecessary setters. If we decide to move forward with this approach, I can update the implementation accordingly. Looking forward to your thoughts!

return new BaseSnapshotBuilder();
}

public static class BaseSnapshotBuilder {
Copy link
Contributor

Choose a reason for hiding this comment

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

why is this class needed?

Copy link
Contributor Author

@HonahX HonahX Jan 14, 2025

Choose a reason for hiding this comment

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

This class is added to reduce the amount of code changes required in tests when we add new fields to BaseSnapshot (example)

With this class, we only have to update the builder instead of updating all the test that calls BaseSnapshot constructor.

Copy link
Member

@RussellSpitzer RussellSpitzer Jan 14, 2025

Choose a reason for hiding this comment

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

I'm strongly in favor of adding this. Our real builder in TableMetadata has too many safety valves which makes it very difficult to build TableMetadata objects which violate those rules (which we need to do to test certain failure modes)

Wrong thread, moved up. Here I just think we'll make it much easier to build tests without stating all the args over and over.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think a better name would be TestSnapshotBuilder or UnsafeSnapshotBuilder?

@SuppressWarnings("MethodLength")
public void testJsonConversion() throws Exception {
public void testJsonConversion(int formatVersion) throws Exception {
Copy link
Member

Choose a reason for hiding this comment

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

I'm not sure it's clear what this is testing anymore and why it is restricted to 2 or higher? I think we may need to spend a little more time on this one to be clear about what we are testing?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah I should've paid more attention to this. It is actually just the last sequence number need to be set to 0 for v1 metadata. I've updated the test to remove the restriction.

statisticsFiles,
partitionStatisticsFiles,
ImmutableList.of());
MetadataTestUtils.buildTestTableMetadata(formatVersion)
Copy link
Member

Choose a reason for hiding this comment

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

Another one where I think if we have more interesting defaults for TestTableMetadata, we can reduce our constructors here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added a buildTestTableMetadataWithExampleValues similar to the one for snapshot. Now we only have to call necessary setters only in each test.

@ParameterizedTest
@MethodSource("formatVersionsProvider")
public void testInvalidMainBranch(int formatVersion) throws IOException {
assumeThat(formatVersion).isGreaterThanOrEqualTo(2);
Copy link
Member

Choose a reason for hiding this comment

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

I feel like this should have a Constant in TableMetadata. I think we should add in a BRANCHING_MIN_SUPPORT_VERSION or whatnot

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added

static final int BRANCHING_MIN_SUPPORT_VERSION = 2;
static final int UUID_REQUIRED_MIN_VERSION = 2;

Do you think we need constants for other cases like

@ParameterizedTest
@FieldSource("org.apache.iceberg.TestHelpers#ALL_VERSIONS")
public void testParserV2PartitionSpecsValidation(int formatVersion) throws Exception {
assumeThat(formatVersion).isGreaterThanOrEqualTo(2);
String unsupportedVersion =
readTableMetadataInputFile(
String.format("TableMetadataV%sMissingPartitionSpecs.json", formatVersion));
assertThatThrownBy(() -> TableMetadataParser.fromJson(unsupportedVersion))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("partition-specs must exist in format v%s", formatVersion));
}
@ParameterizedTest
@FieldSource("org.apache.iceberg.TestHelpers#ALL_VERSIONS")
public void testParserLastAssignedFieldIdValidation(int formatVersion) throws Exception {
assumeThat(formatVersion).isGreaterThanOrEqualTo(2);
String unsupportedVersion =
readTableMetadataInputFile(
String.format("TableMetadataV%sMissingLastPartitionId.json", formatVersion));
assertThatThrownBy(() -> TableMetadataParser.fromJson(unsupportedVersion))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("last-partition-id must exist in format v%s", formatVersion));
}
@ParameterizedTest
@FieldSource("org.apache.iceberg.TestHelpers#ALL_VERSIONS")
public void testParserSortOrderValidation(int formatVersion) throws Exception {
assumeThat(formatVersion).isGreaterThanOrEqualTo(2);

My concern is that if we do so we will end up with lots of constant for all the new features starting from v2

Copy link
Member

@RussellSpitzer RussellSpitzer left a comment

Choose a reason for hiding this comment

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

Looks mostly good to me. I really appreciate the utility methods. I have a few nits which I hope will clean things up.

@ParameterizedTest
@MethodSource("formatVersionsProvider")
public void testMainWithoutCurrent(int formatVersion) throws IOException {
assumeThat(formatVersion).isGreaterThanOrEqualTo(2);
Copy link
Member

Choose a reason for hiding this comment

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

Branch support constant here again

@ParameterizedTest
@MethodSource("formatVersionsProvider")
public void testV2UUIDValidation(int formatVersion) {
assumeThat(formatVersion).isGreaterThanOrEqualTo(2);
Copy link
Member

Choose a reason for hiding this comment

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

I think maybe this needs a constant too?

@@ -372,6 +373,7 @@ public static TableMetadata fromJson(String metadataLocation, JsonNode node) {
formatVersion == 1, "%s must exist in format v%s", SCHEMAS, formatVersion);

schema = SchemaParser.fromJson(JsonUtil.get(SCHEMA, node));
Schema.checkCompatibility(schema, formatVersion);
Copy link
Contributor

Choose a reason for hiding this comment

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

@HonahX, when I introduced this compatibility check, I purposely called it at write time rather than at read time. I've also pushed back on strictness in the read path like this in the REST catalog and other places. The reason for it is that we don't want to immediately reject metadata on read because that prevents the library from being used to debug or fix metadata issues.

For example, this check validates that initial default values are not used in v2 tables. But what if a table is created by another library that way? Checking compatibility here prevents loading the table at all, let alone using this library to drop the problematic column from the schema using SQL DDL or direct calls. Failing to load the table has much broader consequences, like failing existence checks because tableExists calls loadTable, failing to run information_schema queries that are unrelated, or failing to run expireSnapshots and remove old data -- which can cause compliance problems.

I think that a better time to fail is when the actual problem caused by the compatibility issue happens. For instance, if there is a default that can't be applied, then the library should fail to read from the table.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the explanation! So in general we want to be less restrictive on read side to open the opportunities of fix things instead of rejecting all the errors.

I will revert this change.

Copy link
Member

Choose a reason for hiding this comment

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

I think if this is the case we should have some tests that show that parsing invalid metadata is a behavior is allowed by the library. Parsing some invalid Json should not throw an exception for compatibility purposes? I think we could just take a fully populated V3 Metadata and change it's format version to 1 or something. This should be readable (but not really usable)? I'm not sure what other cases we would want, but I think we'd be in a better state if we had tests for behaviors we want to keep in the code.

new BaseSnapshot(
0, snapshotId, parentId, System.currentTimeMillis(), null, null, 1, manifestList);
MetadataTestUtils.buildTestSnapshotWithExampleValues()
.setOperation(null)
Copy link
Member

Choose a reason for hiding this comment

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

I don't think operation, summary or schema ID really need to be specified here right?

return new BaseSnapshotBuilder();
}

public static BaseSnapshotBuilder buildTestSnapshotWithExampleValues() {
Copy link
Contributor

Choose a reason for hiding this comment

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

I would expect this to be a configuration method on the builder, not a factory method that returns a builder. I think it would be more clear that way. Here's what I saw below:

        MetadataTestUtils.buildTestSnapshotWithExampleValues()
            .buildWithExampleManifestList(
                temp,
                ImmutableList.of(
                    MetadataTestUtils.EXAMPLE_MANIFEST_PATH_1,
                    MetadataTestUtils.EXAMPLE_MANIFEST_PATH_2));

Instead, I think it would make more sense like this:

        MetadataTestUtils.unsafeMetadataBuilder()
            .withExampleValues()
            .withExampleManifestList(EXAMPLE_MANIFEST_PATH_1, EXAMPLE_MANIFEST_PATH_2)
            .build();

Also, is it necessary to use an unsafe builder for these cases? The justification for the builder was to be able to build invalid cases, but these are valid.

partitionStatisticsFiles,
ImmutableList.of());
MetadataTestUtils.buildTestTableMetadataWithExampleValues(formatVersion)
.setCurrentSchemaId(7)
Copy link
Member

Choose a reason for hiding this comment

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

we shouldn't really need any of these if they are in TestTableMetadataWithExampleValues since this is a ser/de test

}

public BaseSnapshotBuilder setSequenceNumber(long sequenceNumber) {
this.sequenceNumber = sequenceNumber;
Copy link
Contributor

Choose a reason for hiding this comment

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

Because this is a long primitive, it cannot mimic v1 snapshots.

return this;
}

public BaseSnapshotBuilder setTimestampMillis(long timestampMillis) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this field default?

return this;
}

public BaseSnapshotBuilder setManifestListLocation(String manifestListLocation) {
Copy link
Contributor

Choose a reason for hiding this comment

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

What about making this similar to setV1ManifestLocations instead and combining it with buildWithExampleManifestList? I think that would make more sense.

manifestListLocation);
}

public Snapshot buildWithExampleManifestList(Path temp, List<String> manifestFiles)
Copy link
Contributor

Choose a reason for hiding this comment

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

I'd expect this to be a normal method on the builder. Why put it here instead?

.setSummary(summary2)
.setSchemaId(1)
.setManifestListLocation("file:/tmp/manifest2.avro")
.build());
Copy link
Contributor

Choose a reason for hiding this comment

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

It doesn't seem to me that this strictly needs to be changed, but I'm okay with it for readability.

MetadataTestUtils.buildTestSnapshotWithExampleValues()
.setOperation(null)
.setSummary(null)
.setSchemaId(null)
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this set operation and summary? Seems like only schema ID is needed.

Snapshot expected =
new BaseSnapshot(
0, snapshotId, parentId, System.currentTimeMillis(), null, null, null, manifestList);
MetadataTestUtils.buildTestSnapshotWithExampleValues()
Copy link
Contributor

Choose a reason for hiding this comment

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

Since this is used to fill base data and then the methods are used to override, should example values be the default behavior? That would make more sense to me.

@HonahX
Copy link
Contributor Author

HonahX commented Jan 21, 2025

Hi everyone, thanks for all the review and suggestions! Since there is an ongoing discussion on whether to add test-only builders for Snapshot and TableMetadata, I created a new PR, #12025, for the following changes:

  • Refactor TableMetadata tests by parametrizing table format versions in all tests
  • Add example metadata files for V3 table
  • Add constants for several features/fields' min format version

I will update the title and description of this PR so that we can focus on the test-only builders in this one.

@HonahX HonahX changed the title Core: Parsing and Writing Tests for V3 Metadata Core: Refactor Table Metadata Tests Jan 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants