Skip to content

feat(view): Implement view metadata builder and UpdateView method in REST catalog - #629

Merged
zeroshade merged 14 commits into
apache:mainfrom
jnagel12:jnagel12/implement-rest-view-support
Dec 4, 2025
Merged

zeroshade merged 14 commits into
apache:mainfrom
jnagel12:jnagel12/implement-rest-view-support

Conversation

@jnagel12

@jnagel12 jnagel12 commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor

Description

This PR implements full support for updating Iceberg views for the REST catalog

Changes

  • Implements an UpdateView method on the REST catalog
  • Implements view.MetadataBuilder to generate updates for use in UpdateView on the REST catalog
    • I did my best to blend the style of the existing codebase and use idiomatic Go, while still being faithful to the Java reference code. Some of the refactors of existing code bring the state of the view package more inline with Java
    • I transcribed every applicable unit test from the Java ViewMetadataBuilder tests to validate behavior
  • Refactors the existing state of the view package substantially
    • I apologize for the diff here, I was working off of a fork for a few weeks and had not previously seen the recent additions to view metadata support. Did my best to reconcile them
  • Refactors the REST catalog CreateView method to take variadic CreateViewOpts and now return a view.View, similar to the behavior of the CreateTable method
  • Added unit and integration tests to the rest package to cover the new changes to the REST view methods
  • Small refactor to extract sliceEqualHelper from table/metadata.go to internal/utils.go for use in the view package
  • Refactors the CreateMetadata function used by the SQL catalog to return a *View, and extract the location from it

@jnagel12
jnagel12 force-pushed the jnagel12/implement-rest-view-support branch from 3200027 to d3a101f Compare November 18, 2025 21:39
Comment thread view/view.go

// Metadata defines the format for view metadata,
// similar to how Iceberg supports a common table format for tables
type Metadata interface {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

moved to metadata.go

@alessandro-nori alessandro-nori 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.

It looks like this PR has some overlaps with what @twuebi is working on.
Could we limit the changes in this PR to the REST catalog?

Comment thread catalog/rest/rest.go
return err
return nil, err
}

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.

since Version is now coming from the caller, I think we should enforce that fields like VersionID, TimestampMs are correctly set before the request is sent to the server.

Alternatively we could change the method signature to receive a slice of Representations instead of view.Version

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think one way of doing this is making Version an interface and making the struct private. What do you think? TimestampMS is defaulted to now in that constructor.

If we only take representations we lose the ability to set the summary and default NS, and adding those explicitly to the REST call bloats the parameter list

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.

Makes sense, thanks for the clarification.
About Version, I would be consistent with how Snapshot is handled for table.Metadata so I think the current implementation is fine.

Comment thread catalog/rest/rest.go Resolved
@twuebi

twuebi commented Nov 19, 2025 •

Copy link
Copy Markdown
Contributor

It looks like this PR has some overlaps with what @twuebi is working on. Could we limit the changes in this PR to the REST catalog?

I didn't realize this PR existed, I'm not attached to my PR, I'll close mine.

Comment thread view/metadata.go Outdated
Comment on lines +91 to +92
// Updates returns the list of metadata updates used to build this metadata
Updates() Updates

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.

I'd prefer if we'd return a result struct like:

type ViewMetadataBuildResult struct {
	Metadata *metadata
	Changes  []ViewUpdate
}

from builder.Build() instead, the updates are a property of the builder / result of the builder but not the metadata itself, reading metadata from disk or receiving it on the wire will have an empty list here, the result struct would separate the concerns and prevent this awkwardness.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I also was not a fan of it being on the metadata itself, but it's what the Java implementation does. I more or less view it as a reference implementation so figured I'd replicate it, but obviously Build() and BuildWithoutChanges() is awkward as you mentioned.

This seems like a fine compromise. What would you think about embedding metadata in the BuildResult for the convenience of method promotion?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I guess to play devil's advocate, I can see why the java implementation might choose to couple changes / updates and metadata. The only reason I added a method for BuildWithoutUpdates was to discard the updates reference to save memory if the caller doesn't need it. But it's not as though the updates is a big chunk of memory.

I could also just get rid of the ugly switching on withUpdates to make this cleaner if you're ok with that as well

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sounds good, I'll go with this approach then.

Comment thread view/metadata.go
Comment on lines +338 to 340
if !ok {
panic("current version not found")
}

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.

Is this always a bug in iceberg-go if we arrive here? Can a user of the library provoke this panic? If so, we should either return an error or nil, we should avoid runtime panics

@jnagel12 jnagel12 Nov 19, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This should never happen. Initialization of metadata should always be done with a call to init and validate. validate specifically checks that the version list and schema lists are nonempty, and also that the current version ID exists in the list of versions. Similar logic for schemas.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

To address your question around user of the library provoking, the answer should be no they should not be able to provoke it. metadata is private and it's initialization should be abstracted by the view package. Thus, a user should not be able to initialize an invalid metadata instance unless there is a bug in iceberg-go

Comment thread view/metadata.go
if !ok {
return "", errors.New("filesystem IO does not support writing")
panic("current schema not found")
}

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.

same as above

Comment thread view/metadata.go Resolved
Comment thread view/metadata_builder.go Outdated
// build builds the view metadata updates from the builder
// if withUpdates is set to false, updates will not be included
// in the returned Metadata, thus its Updates() will return an empty slice
func (b *MetadataBuilder) build(withUpdates bool) (Metadata, error) {

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.

I may have missed it, I think we're missing this validation:

    private void checkIfDialectIsDropped(ViewVersion previous, ViewVersion current) {
      Set<String> baseDialects = sqlDialectsFor(previous);
      Set<String> updatedDialects = sqlDialectsFor(current);

      Preconditions.checkState(
          updatedDialects.containsAll(baseDialects),
          "Cannot replace view due to loss of view dialects (%s=false):\nPrevious dialects: %s\nNew dialects: %s",
          ViewProperties.REPLACE_DROP_DIALECT_ALLOWED,
          baseDialects,
          updatedDialects);
    }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The reason I omitted this is because AFAICT it was a configurable property as to whether this was permitted or not. I made the naive assumption that ultimately the catalog could enforce this depending on whether it's permitted or not but I'm not sure.

!PropertyUtil.propertyAsBoolean(
              properties,
              ViewProperties.REPLACE_DROP_DIALECT_ALLOWED,
              ViewProperties.REPLACE_DROP_DIALECT_ALLOWED_DEFAULT)) {
        checkIfDialectIsDropped(previousViewVersion, versionsById.get(currentVersionId))

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.

I'd keep it, they also apply to non-rest catalogs, there this may be the only place this is validated, I'd try to avoid reimplementing these checks in all catalogs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Understood, will implement!

Comment thread view/metadata_builder.go Outdated
// build builds the view metadata updates from the builder
// if withUpdates is set to false, updates will not be included
// in the returned Metadata, thus its Updates() will return an empty slice
func (b *MetadataBuilder) build(withUpdates bool) (Metadata, error) {

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.

We're also missing this action I think:

public ViewMetadata build() {
      ...
      // expire old versions, but keep at least the versions added in this builder and the current
      // version
      int numVersions =
          ImmutableSet.builder()
              .addAll(
                  changes(MetadataUpdate.AddViewVersion.class)
                      .map(v -> v.viewVersion().versionId())
                      .collect(Collectors.toSet()))
              .add(currentVersionId)
              .build()
              .size();
      int numVersionsToKeep = Math.max(numVersions, historySize);
      List<ViewVersion> retainedVersions;
      List<ViewHistoryEntry> retainedHistory;
      if (versions.size() > numVersionsToKeep) {
        retainedVersions =
            expireVersions(versionsById, numVersionsToKeep, versionsById.get(currentVersionId));
        Set<Integer> retainedVersionIds =
            retainedVersions.stream().map(ViewVersion::versionId).collect(Collectors.toSet());
        retainedHistory = updateHistory(history, retainedVersionIds);
      } else {
        retainedVersions = versions;
        retainedHistory = history;
      }
    ...
    }

    static List<ViewVersion> expireVersions(
        Map<Integer, ViewVersion> versionsById, int numVersionsToKeep, ViewVersion currentVersion) {
      // version ids are assigned sequentially. keep the latest versions by ID.
      List<Integer> ids = Lists.newArrayList(versionsById.keySet());
      ids.sort(Comparator.reverseOrder());

      List<ViewVersion> retainedVersions = Lists.newArrayList();
      // always retain the current version
      retainedVersions.add(currentVersion);

      for (int idToKeep : ids.subList(0, numVersionsToKeep)) {
        if (retainedVersions.size() == numVersionsToKeep) {
          break;
        }

        ViewVersion version = versionsById.get(idToKeep);
        if (currentVersion.versionId() != version.versionId()) {
          retainedVersions.add(version);
        }
      }

      return retainedVersions;
    }


    static List<ViewHistoryEntry> updateHistory(List<ViewHistoryEntry> history, Set<Integer> ids) {
      List<ViewHistoryEntry> retainedHistory = Lists.newArrayList();
      for (ViewHistoryEntry entry : history) {
        if (ids.contains(entry.versionId())) {
          retainedHistory.add(entry);
        } else {
          // clear history past any unknown version
          retainedHistory.clear();
        }
      }

      return retainedHistory;
    }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes sorry I should have left a comment about this in my summary, I intentionally omitted this for now. It's my understanding that at least the rest catalog will manage history retention, so I made the decision to omit this for an MVP to avoid further bloat in the PR if catalogs will ultimately handle retention (since there is no Go catalog implementation I know of).

What are your thoughts?

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.

I'd keep it in here to avoid duplicating this logic across catalog implementations, the metadata builder is the shared thing amongst all of them, we're also managing history in the table metadata builder, for sake of consistency it'd also make sense to do it here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sounds good to me, will implement it 👍 . Just a heads up going to be unable to work on this tomorrow but will resume work on Friday.

@jnagel12
jnagel12 force-pushed the jnagel12/implement-rest-view-support branch from b95fd2a to 2dcf6d0 Compare November 19, 2025 23:23
@jnagel12

Copy link
Copy Markdown
Contributor Author

An update for maintainer(s) on this - after discussion with @twuebi , will make the following changes to the MetadataBuilder in this PR.

  • Implement history retention management
  • Implement enforcement of policy around dropping dialects
  • Will return View MD and Updates as separate entities from the builder packaged in a container struct

As I mentioned above will be unavailable tomorrow but will get back to this Friday. Hopefully the rest of the PR should be reviewable as is in the meantime 🙇

Comment thread view/requirements.go

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.

Let's add some tests, maybe something like:

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package view_test

import (
	"encoding/json"
	"testing"

	"github.com/apache/iceberg-go/view"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
)

func TestParseRequirementList(t *testing.T) {
	t.Run("should parse a list of requirements", func(t *testing.T) {
		jsonData := []byte(`[
			{"type": "assert-view-uuid", "uuid": "550e8400-e29b-41d4-a716-446655440000"}
		]`)

		expected := view.Requirements{
			view.AssertViewUUID(uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")),
		}

		var actual view.Requirements
		err := json.Unmarshal(jsonData, &actual)

		assert.NoError(t, err)
		assert.Equal(t, expected, actual)
	})

	t.Run("should handle an empty list", func(t *testing.T) {
		jsonData := []byte(`[]`)
		var actual view.Requirements
		err := json.Unmarshal(jsonData, &actual)
		assert.NoError(t, err)
		assert.Empty(t, actual)
	})

	t.Run("should return an error for an unknown requirement type in the list", func(t *testing.T) {
		jsonData := []byte(`[
			{"type": "assert-view-uuid", "uuid": "550e8400-e29b-41d4-a716-446655440000"},
			{"type": "assert-foo-bar"}
		]`)

		var actual view.Requirements
		err := json.Unmarshal(jsonData, &actual)
		assert.Error(t, err)
		assert.Contains(t, err.Error(), "unknown requirement type: assert-foo-bar")
	})

	t.Run("should return an error for invalid json", func(t *testing.T) {
		jsonData := []byte(`[{"type": "assert-view-uuid", "uuid": "550e8400-e29b-41d4-a716-446655440000"},]`) // trailing comma
		var actual view.Requirements
		err := json.Unmarshal(jsonData, &actual)
		assert.Error(t, err)
	})
}

Copy link
Copy Markdown
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 snippet will incorporate this as well

@jnagel12
jnagel12 force-pushed the jnagel12/implement-rest-view-support branch 2 times, most recently from 706ac2e to 31da155 Compare November 24, 2025 13:20
@jnagel12
jnagel12 force-pushed the jnagel12/implement-rest-view-support branch from 31da155 to e2d54b9 Compare November 24, 2025 13:22
@jnagel12

Copy link
Copy Markdown
Contributor Author

Ok, implemented the items discussed above, sorry for the delay!

@zeroshade

Copy link
Copy Markdown
Member

@alessandro-nori @twuebi any further comments on this?

@twuebi twuebi 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.

Not sure where java is doing it, but, org.apache.iceberg.view.ViewCatalogTests::basicCreateView creates a view with Schema with schemaId = 5, it then asserts assertThat(view.schema().schemaId()).isEqualTo(0);, not too certain about the conditions for it but it seems like we should be reassigning schema id at least upon initial view creation

...
  protected static final Schema SCHEMA =
      new Schema(
          5,
          required(3, "id", Types.IntegerType.get(), "unique ID"),
          required(4, "data", Types.StringType.get()));
  public void basicCreateView() {

    ...
    View view =
        catalog()
            .buildView(identifier)
            .withSchema(SCHEMA)
            .withDefaultNamespace(identifier.namespace())
            .withQuery("spark", "select * from ns.tbl")
            .create();

    assertThat(view).isNotNull();
    assertThat(catalog().viewExists(identifier)).as("View should exist").isTrue();
    assertThat(((BaseView) view).operations().current().metadataFileLocation()).isNotNull();

    // validate view settings
    assertThat(view.name()).isEqualTo(ViewUtil.fullViewName(catalog().name(), identifier));
    assertThat(view.history())
        .hasSize(1)
        .first()
        .extracting(ViewHistoryEntry::versionId)
        .isEqualTo(1);
    assertThat(view.schema().schemaId()).isEqualTo(0);
...
  }

There's also a hard-coding of the initial view version to 1 in org.apache.iceberg.rest.RESTSessionCatalog.RESTViewBuilder::create / org.apache.iceberg.view.BaseMetastoreViewCatalog.BaseViewBuilder#create(org.apache.iceberg.view.ViewOperations):

ViewVersion viewVersion =
          ImmutableViewVersion.builder()
              .versionId(1)
              .schemaId(schema.schemaId())
              .addAllRepresentations(representations)
              .defaultNamespace(defaultNamespace)
              .defaultCatalog(defaultCatalog)
              .timestampMillis(System.currentTimeMillis())
              .putAllSummary(EnvironmentContext.get())
              .build();

@twuebi

twuebi commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

nevermind, I just realized we're doing the schemaId reassignment with:

func (b *MetadataBuilder) addSchema(schema *iceberg.Schema) (int, error) {
	newSchemaID := b.reuseOrCreateNewSchemaID(schema)

@jnagel12

jnagel12 commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor Author

nevermind, I just realized we're doing the schemaId reassignment with:

func (b *MetadataBuilder) addSchema(schema *iceberg.Schema) (int, error) {
	newSchemaID := b.reuseOrCreateNewSchemaID(schema)

Yes that's correct.

On the note about the REST impl, that's a good catch. I'll update it to override the version ID to 1 in the CreateView method. Does that sound good?

@jnagel12

jnagel12 commented Dec 2, 2025

Copy link
Copy Markdown
Contributor Author

Also in case it's a concern, per REST API spec, schema ID on create is managed by the catalog, and if reassigned, new schema ID is propagated to the view version's schema ID (spec)

@twuebi

twuebi commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

Sure, I'm wondering if there's a good reason not to do it here in the view constructor, as in if there's any harm in it.

@jnagel12

jnagel12 commented Dec 2, 2025 •

Copy link
Copy Markdown
Contributor Author

Sure, I'm wondering if there's a good reason not to do it here in the view constructor, as in if there's any harm in it.

Meaning in NewViewVersion? I was thinking about that. I guess if users in general should be building updates using the MetadataBuilder, it doesn't matter if we default the ID in that constructor to 1 since we reassign in the builder.

How about I default it to 1 there and add a variadic version opt WithViewVersionID in case there are reasons to set manually?

OTOH - we'll still want to enforce the ID being 1 anyway in CreateView so maybe it's a moot point. Up to you

@jnagel12

jnagel12 commented Dec 3, 2025

Copy link
Copy Markdown
Contributor Author

@twuebi for now just enforced in the REST handler. LMK if you want me to take the approach I described above of dropping the positional param for Version ID and making it default 1 with variadic opt.

@zeroshade any other blockers here I should look at in the meantime?

@twuebi

twuebi commented Dec 3, 2025

Copy link
Copy Markdown
Contributor

sorry for the delay @jnagel12, I would like us to move it to the constructor of the view metadata since catalog applications will have to do this server-side as clients are generally not to be trusted

@jnagel12

jnagel12 commented Dec 3, 2025

Copy link
Copy Markdown
Contributor Author

@twuebi ack, now overriding VersionID to 1 in NewMetadataWithUUID (called by NewMetadata). Updated test for it as well

@jnagel12

jnagel12 commented Dec 3, 2025

Copy link
Copy Markdown
Contributor Author

Seems like macos 1.13.6 is flaky, not sure how to retrigger

@zeroshade zeroshade 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.

Thanks for all the work here! and for the reviews from @twuebi and @alessandro-nori

@zeroshade
zeroshade merged commit 5edb1e3 into apache:main Dec 4, 2025
@jnagel12

jnagel12 commented Dec 5, 2025

Copy link
Copy Markdown
Contributor Author

Thanks for all the work here! and for the reviews from @twuebi and @alessandro-nori

Thank you all!

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.

4 participants