Repository navigation
feat(view): Implement view metadata builder and UpdateView method in REST catalog - #629
Conversation
3200027 to
d3a101f
Compare
|
|
||
| // Metadata defines the format for view metadata, | ||
| // similar to how Iceberg supports a common table format for tables | ||
| type Metadata interface { |
There was a problem hiding this comment.
moved to metadata.go
alessandro-nori
left a comment
There was a problem hiding this comment.
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?
| return err | ||
| return nil, err | ||
| } | ||
|
|
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
I didn't realize this PR existed, I'm not attached to my PR, I'll close mine. |
| // Updates returns the list of metadata updates used to build this metadata | ||
| Updates() Updates |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
There was a problem hiding this comment.
Sounds good, I'll go with this approach then.
| if !ok { | ||
| panic("current version not found") | ||
| } |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| if !ok { | ||
| return "", errors.New("filesystem IO does not support writing") | ||
| panic("current schema not found") | ||
| } |
| // 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) { |
There was a problem hiding this comment.
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);
}There was a problem hiding this comment.
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))There was a problem hiding this comment.
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
There was a problem hiding this comment.
Understood, will implement!
| // 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) { |
There was a problem hiding this comment.
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;
}There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
b95fd2a to
2dcf6d0
Compare
|
An update for maintainer(s) on this - after discussion with @twuebi , will make the following changes to the
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 🙇 |
There was a problem hiding this comment.
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)
})
}There was a problem hiding this comment.
thanks for the snippet will incorporate this as well
…ct preservation if enabled
706ac2e to
31da155
Compare
31da155 to
e2d54b9
Compare
|
Ok, implemented the items discussed above, sorry for the delay! |
|
@alessandro-nori @twuebi any further comments on this? |
There was a problem hiding this comment.
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();|
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 |
|
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) |
|
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 How about I default it to OTOH - we'll still want to enforce the ID being |
|
@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? |
|
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 |
|
@twuebi ack, now overriding |
|
Seems like macos 1.13.6 is flaky, not sure how to retrigger |
zeroshade
left a comment
There was a problem hiding this comment.
Thanks for all the work here! and for the reviews from @twuebi and @alessandro-nori
Thank you all! |
Description
This PR implements full support for updating Iceberg views for the REST catalog
Changes
UpdateViewmethod on the REST catalogview.MetadataBuilderto generate updates for use inUpdateViewon the REST catalogViewMetadataBuildertests to validate behaviorviewpackage substantiallyCreateViewmethod to take variadicCreateViewOpts and now return aview.View, similar to the behavior of theCreateTablemethodrestpackage to cover the new changes to the REST view methodssliceEqualHelperfromtable/metadata.gotointernal/utils.gofor use in theviewpackage*View, and extract the location from it