morningman commented on code in PR #71125:
URL: https://github.com/apache/doris/pull/71125#discussion_r4735428780


##########
fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceManifestPaths.java:
##########
@@ -0,0 +1,143 @@
+// 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 org.apache.doris.connector.lance;
+
+import org.apache.doris.connector.spi.DorisConnectorException;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.Optional;
+import java.util.regex.Pattern;
+
+/**
+ * Where a namespace-managed version's manifest must be for Doris to read that 
version.
+ *
+ * <p>Doris reads a managed version as it reads any other, by the dataset URI 
and the version
+ * number, and so does the BE: Lance then opens {@code 
<chain>/_versions/<u64::MAX - v>.manifest},
+ * or {@code <v>.manifest} in the V1 naming scheme, where the chain is the 
table root or
+ * {@code <root>/tree/<branch>}. The namespace records a manifest path for 
each version. Lance's
+ * own namespaces finalize a commit in CreateTableVersion and record that 
canonical path. A
+ * namespace that records the path Lance's client sends records the staged 
manifest beside it,
+ * named {@code <canonical>-<id>} ({@code make_staging_manifest_path}), and 
keeps it after the
+ * commit is finalized, since Lance's namespace store cannot update a record. 
A recorded path
+ * anywhere else names a manifest Doris would not read. It is also what a 
namespace answers once
+ * it has moved the table away from the location this read described, if the 
move changed the
+ * path inside the bucket; a path is relative to its bucket or container, so a 
move to another one
+ * under the same path is not seen here.
+ */
+final class LanceManifestPaths {
+
+    /** How the namespace records a version whose manifest is where Doris 
reads it. */
+    enum Recorded {
+        /** At its canonical path. */
+        CANONICAL,
+        /**
+         * At a staged manifest beside the canonical path. The version may not 
have been finalized
+         * yet, or was finalized after the namespace recorded the staged path.
+         */
+        STAGED
+    }
+
+    private static final String MANIFEST_EXTENSION = ".manifest";
+
+    private static final BigInteger U64_MAX = 
BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE);
+
+    /** A URL scheme; lance-io takes a single letter before the colon for a 
Windows drive instead. */
+    private static final Pattern URL_SCHEME = 
Pattern.compile("^[A-Za-z][A-Za-z0-9+.-]+:");
+
+    private LanceManifestPaths() {
+    }
+
+    /**
+     * How the namespace records version {@code version} of the chain of 
{@code tableUri} (the
+     * table root) on {@code branch}.
+     *
+     * @throws DorisConnectorException if the recorded path is neither the 
canonical path nor a
+     *     staged manifest beside it
+     */
+    static Recorded check(String tableUri, Optional<String> branch, long 
version, String manifestPath,
+            String tableName) {
+        String chain = objectStorePath(tableUri);
+        if (branch.isPresent()) {
+            chain = (chain.isEmpty() ? "" : chain + "/") + "tree/" + 
branch.get();

Review Comment:
   The mismatch is real, but the fix goes the other way. Lance doesn't allow a 
branch name with a leading or trailing `/`: `check_valid_branch` in Lance 
12.0.0 rejects it when a branch is created or checked out, and Lance's 
directory namespace rejects it too. Normalizing it would make 
`@branch('name'='/dev')` read `dev` on managed tables while the same query 
fails on every other Lance table. dcbf1d6ea97 instead refuses such a name 
before a managed branch is read, with branch-4.2's check from #68707 (`Invalid 
Lance branch name '/dev': it starts or ends with '/' or contains an empty 
segment`); it also refuses `..` and the other names that could leave `tree/`. 
After that, `branchUri` and `LanceManifestPaths.check` only see names they join 
the same way.
   



##########
fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogClient.java:
##########
@@ -148,58 +156,63 @@ void testConnection() {
     }
 
     /**
-     * Reads the planning metadata of one table at {@code version}, or at the 
newest version in storage
-     * when it is empty. Every dataset is read by its URI and a version, as 
the BE reads it.
+     * Reads the planning metadata of the version of one table that {@code 
selector} selects. Every dataset is
+     * read by its URI and a version, as the BE reads it.
+     *
+     * <p>The latest version of the main chain in storage is opened once as a 
handle, and the other selectors
+     * are checkouts from it, except an explicit version on the main chain and 
a managed table's branch (below).
+     * A tag is resolved first to the chain and version it points at, so a tag 
created on a branch selects that
+     * branch.
+     *
+     * <p>For a managed table the namespace decides which versions exist. 
"Latest" is the newest version it
+     * records, never the newest manifest in storage, and every version a read 
selects must be one it records,
+     * at the manifest path Doris reads ({@link LanceManifestPaths}). A branch 
is read from its own directory, as
+     * the BE reads it, so it does not depend on the main chain; the main 
handle only supplies tag files and the
+     * manifest listing that FOR TIME AS OF on main takes commit times from.
      *
      * @param metrics the statement's totals of the table, which the read is 
timed into
      */
-    LanceTableMetadata loadTableMetadata(String dbName, String tableName, 
OptionalLong version,
+    LanceTableMetadata loadTableMetadata(String dbName, String tableName, 
LanceRefSelector selector,
             LanceMetadataMetrics metrics) {
-        return readTable(dbName, tableName, version, metrics, (generation, 
access, readAllocator, timer) -> {
-            try (Dataset dataset = openDataset(generation, readAllocator, 
access, version, timer)) {
-                return readMetadata(dataset, access, timer);
+        ReadState state = new ReadState(selector, dbName + "." + tableName);
+        return readTable(dbName, tableName, state, metrics, (generation, 
readAllocator, timer) -> {
+            OptionalLong direct = directMainVersion(generation, state, timer);
+            if (state.access.isManagedVersioning() && 
state.branch.isPresent()) {
+                return readManagedBranch(generation, readAllocator, state, 
timer);
+            }
+            if (direct.isPresent() || selector.isLatestMain()) {
+                state.version = direct;
+                try (Dataset dataset = openDataset(generation, readAllocator, 
state.access, direct, timer)) {
+                    return readMetadata(dataset, state.access, timer);
+                }
+            }
+            try (Dataset main = openDataset(generation, readAllocator, 
state.access, OptionalLong.empty(), timer)) {

Review Comment:
   Kept as is; it's the same order as on branch-4.2. On main both steps always 
run: `FOR TIME AS OF` needs the latest dataset's `listVersions()` for the 
commit times and the namespace's list to select from, and the list is fetched 
once per read. So the order changes neither the calls nor the result of a 
successful read. It only matters when the namespace lists no versions at all, 
which a managed table with data doesn't do (a declared-only table is refused at 
`DescribeTable`); even then, if storage is readable, main reports the same 
`Lance namespace lists no versions for <table>` as a branch. The branch path 
asks the namespace first for reasons that don't apply to main: a branch the 
namespace lacks has to be reported as a missing branch rather than as a storage 
error, and a branch read must not depend on the main chain being readable.
   



##########
fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceCatalogClient.java:
##########
@@ -264,20 +297,392 @@ static LanceTableMetadata readMetadata(Dataset dataset, 
LanceTableAccess access,
         return new LanceTableMetadata(access, dataset.version(), schema, 
fragments);
     }
 
-    private static long versionAtOrBefore(Dataset latest, long 
timestampMillis, String requestedText,
-            String what) {
+    /** What a read has resolved so far; {@link #readFailure} reports errors 
against it. */
+    private static final class ReadState {
+        private final LanceRefSelector selector;
+        private final String tableName;
+        /** The table's access; a branch's access is derived from it with 
{@code onBranch}. */
+        private LanceTableAccess access;
+        private Optional<String> branch;
+        /**
+         * Set once the branch is known to exist: the namespace recorded 
versions for it, or its latest version
+         * was checked out. Later failures are not reported as a missing 
branch.
+         */
+        private boolean branchExists;
+        private OptionalLong version = OptionalLong.empty();
+        /** The managed version this read opens next, as the namespace records 
it. */
+        private RecordedVersion pinned;
+        /** The namespace's version list of the chain a FOR TIME AS OF reads 
("" is main), fetched once. */
+        private final Map<String, List<TableVersion>> namespaceVersions = new 
HashMap<>();
+
+        private ReadState(LanceRefSelector selector, String tableName) {
+            this.selector = selector;
+            this.tableName = tableName;
+            this.branch = selector.getBranch();
+        }
+
+        private String displayName() {
+            return tableName + branch.map(name -> "@" + name).orElse("");
+        }
+
+        private String tagSuffix() {
+            return selector.getTag().map(tag -> " (tag '" + tag + 
"')").orElse("");
+        }
+    }
+
+    /** A version of a managed chain the namespace records, and how it records 
its manifest. */
+    private static final class RecordedVersion {
+        private final Optional<String> branch;
+        private final long version;
+        private final LanceManifestPaths.Recorded manifest;
+
+        private RecordedVersion(Optional<String> branch, long version, 
LanceManifestPaths.Recorded manifest) {
+            this.branch = branch;
+            this.version = version;
+            this.manifest = manifest;
+        }
+    }
+
+    /**
+     * The main-chain version a selector names without looking at the latest 
manifest: an explicit version, or
+     * the latest version of a managed table, which the namespace records.
+     */
+    private OptionalLong directMainVersion(Generation generation, ReadState 
state, LanceMetadataMetrics.Timer timer) {
+        LanceRefSelector selector = state.selector;
+        if (selector.getTag().isPresent() || selector.getBranch().isPresent() 
|| selector.isTime()) {
+            return OptionalLong.empty();
+        }
+        if (!selector.getVersion().isPresent()) {
+            return state.access.isManagedVersioning()
+                    ? OptionalLong.of(recordedHead(generation, state, 
Optional.empty(), timer))
+                    : OptionalLong.empty();
+        }
+        state.version = selector.getVersion();
+        requireRecorded(generation, state, Optional.empty(), 
state.version.getAsLong(), timer);
+        return state.version;
+    }
+
+    /** Resolves the selector against the open latest main chain and reads the 
selected version. */
+    private LanceTableMetadata readFromLatest(Generation generation, Dataset 
main, ReadState state,
+            LanceMetadataMetrics.Timer timer) {
+        LanceRefSelector selector = state.selector;
+        if (selector.getTag().isPresent()) {
+            // Only this tag's file is read, however many tags the table has. 
The SDK checks the tag out on the
+            // branch of the version it points at.
+            String tag = selector.getTag().get();
+            state.version = 
OptionalLong.of(timer.measure(Stage.VERSION_RESOLVE, () -> tagVersion(main, 
tag, state)));
+            try (Dataset target = checkout(main, Ref.ofTag(tag), timer)) {
+                // The checkout reads the tag file again; the version it read 
is the one to check.
+                state.version = OptionalLong.of(target.version());
+                state.branch = branchOf(target.uri(), 
state.access.getDatasetUri());
+                requireRecorded(generation, state, state.branch, 
target.version(), timer);
+                return readMetadata(target, accessOf(target, state), timer);
+            }
+        }
+        if (state.branch.isPresent()) {
+            String branch = state.branch.get();
+            // Check out the branch's latest version first even when a version 
is already known, so a missing
+            // branch and a missing version inside an existing branch are told 
apart.
+            try (Dataset latest = checkout(main, Ref.ofBranch(branch), timer)) 
{
+                state.branchExists = true;
+                LanceTableAccess branchAccess = accessOf(latest, state);
+                if (selector.getVersion().isPresent() || selector.isTime()) {
+                    state.version = resolveSnapshotVersion(generation, latest, 
branchAccess, state, timer);
+                }
+                if (!state.version.isPresent()) {
+                    return readMetadata(latest, branchAccess, timer);
+                }
+                try (Dataset dataset = checkout(latest, Ref.ofBranch(branch, 
state.version.getAsLong()), timer)) {
+                    return readMetadata(dataset, branchAccess, timer);
+                }
+            }
+        }
+        // FOR TIME AS OF on the main chain, resolved from manifest commit 
times.
+        state.version = resolveSnapshotVersion(generation, main, state.access, 
state, timer);
+        try (Dataset dataset = checkout(main, 
Ref.ofMain(state.version.getAsLong()), timer)) {
+            return readMetadata(dataset, state.access, timer);
+        }
+    }
+
+    /**
+     * Reads a branch of a managed table from the branch's directory, by URI 
and version as the BE reads it. The
+     * namespace answers for the branch first, so a branch it lacks is 
reported as missing, and the main chain
+     * need not be readable. FOR TIME AS OF lists the branch's manifests from 
its newest version in storage and,
+     * as on main, selects among the versions the namespace records.
+     */
+    private LanceTableMetadata readManagedBranch(Generation generation, 
BufferAllocator readAllocator,
+            ReadState state, LanceMetadataMetrics.Timer timer) {
+        String branch = state.branch.get();
+        LanceTableAccess branchAccess = state.access.onBranch(branch,
+                branchUri(state.access.getDatasetUri(), branch));
+        LanceRefSelector selector = state.selector;
+        if (selector.getVersion().isPresent()) {
+            state.version = selector.getVersion();
+            requireRecorded(generation, state, state.branch, 
state.version.getAsLong(), timer);
+        } else if (selector.isTime()) {
+            namespaceVersions(generation, state, state.branch, timer);
+            state.branchExists = true;
+            try (Dataset latest = openDataset(generation, readAllocator, 
branchAccess, OptionalLong.empty(),
+                    timer)) {
+                state.version = resolveSnapshotVersion(generation, latest, 
branchAccess, state, timer);
+            }
+        } else {
+            state.version = OptionalLong.of(recordedHead(generation, state, 
state.branch, timer));
+        }
+        state.branchExists = true;
+        try (Dataset dataset = openDataset(generation, readAllocator, 
branchAccess, state.version, timer)) {
+            return readMetadata(dataset, branchAccess, timer);
+        }
+    }
+
+    /**
+     * The URI of a branch's directory, joined as Lance's {@code 
BranchLocation} joins it: {@code tree/<branch>}
+     * under the table root, before the URI's query string.
+     */
+    static String branchUri(String tableUri, String branch) {
+        int query = tableUri.indexOf('?');
+        String path = query < 0 ? tableUri : tableUri.substring(0, query);
+        String joined = path + (path.endsWith("/") ? "" : "/") + "tree/" + 
StringUtils.stripStart(branch, "/");
+        return query < 0 ? joined : joined + tableUri.substring(query);
+    }
+
+    private static long tagVersion(Dataset main, String tag, ReadState state) {
+        try {
+            return main.tags().getVersion(tag);
+        } catch (RuntimeException e) {
+            String rootMessage = ExceptionUtils.getRootCauseMessage(e);
+            if (rootMessage != null && rootMessage.contains("tag " + tag + " 
does not exist")) {
+                throw new UserFacingException("Lance tag '" + tag + "' of " + 
state.tableName + " was not found");
+            }
+            throw e;
+        }
+    }
+
+    /**
+     * A dataset URI without its query and trailing slash. The query may carry 
credentials, which a namespace can
+     * vend anew on every describe.
+     */
+    private static String location(String uri) {
+        return StringUtils.removeEnd(StringUtils.substringBefore(uri, "?"), 
"/");
+    }
+
+    /**
+     * The branch a dataset checked out from the table root is on, from its 
root directory: the table root for
+     * main, {@code <root>/tree/<branch>} otherwise. Lance inserts the branch 
path before a URI's query string, so
+     * the query is compared apart. A URI that is neither is an error rather 
than main, which would hand the BE the
+     * wrong chain.
+     */
+    static Optional<String> branchOf(String checkedOutUri, String tableUri) {
+        String root = location(tableUri);
+        String uri = location(checkedOutUri);
+        if (uri.equals(root)) {
+            return Optional.empty();
+        }
+        String branchRoot = root + "/tree/";
+        if (!uri.startsWith(branchRoot) || uri.length() == 
branchRoot.length()) {
+            // The URIs may carry credentials in their query, so they stay out 
of the message.
+            throw new DorisConnectorException("Cannot tell which branch a 
Lance tag was checked out on");
+        }
+        return Optional.of(uri.substring(branchRoot.length()));
+    }
+
+    /**
+     * The access for a dataset checked out from the table: the main chain 
keeps the table access, and a branch
+     * takes the directory the SDK checked out, which is what the BE opens by 
URI.
+     */
+    private static LanceTableAccess accessOf(Dataset dataset, ReadState state) 
{
+        return state.branch.isPresent() ? 
state.access.onBranch(state.branch.get(), dataset.uri()) : state.access;
+    }
+
+    /**
+     * The newest version the namespace records for a managed chain, which the 
read then opens. Doris asks for it
+     * itself: opening "latest" by URI would read the newest manifest in 
storage, which the namespace may not have
+     * published.
+     */
+    private long recordedHead(Generation generation, ReadState state, 
Optional<String> branch,
+            LanceMetadataMetrics.Timer timer) {
+        state.pinned = null;
+        Optional<TableVersion> head = timer.measure(Stage.VERSION_RESOLVE,
+                () -> 
generation.namespaceClient.latestManagedVersion(state.access, branch));
+        if (!head.isPresent()) {
+            throw new UserFacingException("Lance namespace lists no versions 
for " + state.tableName
+                    + branch.map(name -> "@" + name).orElse(""));
+        }
+        long version = head.get().getVersion();
+        state.pinned = new RecordedVersion(branch, version, 
LanceManifestPaths.check(state.access.getDatasetUri(),
+                branch, version, head.get().getManifestPath(), 
state.tableName));
+        return version;
+    }
+
+    /**
+     * Requires the namespace of a managed table to record {@code version} of 
the chain on {@code branch}, at the
+     * manifest path Doris reads; nothing for a storage-versioned table.
+     */
+    private void requireRecorded(Generation generation, ReadState state, 
Optional<String> branch, long version,
+            LanceMetadataMetrics.Timer timer) {
+        if (!state.access.isManagedVersioning()) {
+            return;
+        }
+        state.pinned = null;
+        TableVersion recorded = timer.measure(Stage.VERSION_RESOLVE,
+                () -> 
generation.namespaceClient.describeManagedVersion(state.access, branch, 
version));
+        state.pinned = new RecordedVersion(branch, version, 
LanceManifestPaths.check(state.access.getDatasetUri(),
+                branch, version, recorded.getManifestPath(), state.tableName));
+    }
+
+    /**
+     * The error for a version the namespace records at a staged manifest 
while its canonical manifest, which
+     * Doris reads, does not exist. Either the commit reserved the version and 
was not finalized, which a reader
+     * that uses the namespace would finish and Doris does not, or the version 
was finalized and cleanup later
+     * removed it; the namespace's record does not tell the two apart.
+     */
+    private static String unreadableStaged(RecordedVersion pinned, ReadState 
state) {
+        return "Lance version " + pinned.version + " of " + state.tableName
+                + pinned.branch.map(name -> "@" + name).orElse("") + " cannot 
be read: " + stagedOnly();
+    }
+
+    private static String stagedOnly() {
+        return "the namespace records it at a staged manifest, and its 
canonical manifest, which Doris reads,"
+                + " does not exist (its commit was not finalized, or cleanup 
removed it)";
+    }
+
+    private RuntimeException sanitizedCause(Throwable error, String uri, 
Map<String, String> options) {
+        return new RuntimeException(LanceErrorMessages.sanitize(error, uri, 
options, catalogSecrets));
+    }
+
+    /** Checks out a ref of an already open dataset; the SDK resolves the ref 
from the dataset directory. */
+    private static Dataset checkout(Dataset dataset, Ref ref, 
LanceMetadataMetrics.Timer timer) {
+        return timer.measure(Stage.VERSION_RESOLVE, () -> 
dataset.checkout(ref));
+    }
+
+    /**
+     * Resolves the selector's {@code FOR VERSION AS OF} / {@code FOR TIME AS 
OF} against the chain {@code latest}
+     * is checked out on: the main chain, or a branch when {@code access} is a 
branch access.
+     */
+    private OptionalLong resolveSnapshotVersion(Generation generation, Dataset 
latest, LanceTableAccess access,
+            ReadState state, LanceMetadataMetrics.Timer timer) {
+        LanceRefSelector selector = state.selector;
+        if (selector.getVersion().isPresent()) {
+            state.version = selector.getVersion();
+            requireRecorded(generation, state, access.getBranch(), 
state.version.getAsLong(), timer);
+            return state.version;
+        }
+        String requestedText = selector.getRequestedTime();
         try {
-            return 
LanceSnapshotResolver.versionAtOrBefore(latest.listVersions(), timestampMillis, 
requestedText);
+            return OptionalLong.of(resolveVersionAtOrBefore(generation, 
latest, access, selector.getTimestampMillis(),
+                    requestedText, state, timer));
         } catch (LanceSnapshotResolver.NoVersionAtOrBeforeException e) {
-            throw new UserFacingException("Lance table " + what + " has no 
version at or before '"
-                    + requestedText + "'");
-        } catch (LanceSnapshotResolver.HistoryRemovedException e) {
-            throw new UserFacingException("Lance cannot resolve FOR TIME AS OF 
'" + requestedText
-                    + "' on " + what + ": version " + e.getVersion()
-                    + ", which may hold the state at that time, no longer 
exists");
+            if (!access.getBranch().isPresent()) {
+                throw new UserFacingException("Lance table " + state.tableName 
+ " has no version at or before '"
+                        + requestedText + "'");
+            }
+            // A branch's chain starts at the version it was created from and 
carries its own commit times, so
+            // an earlier timestamp has nothing to select on the branch.
+            throw new UserFacingException("Lance branch '" + 
access.getBranch().get() + "' of " + state.tableName
+                    + " has no version at or before '" + requestedText + "'; a 
branch only holds the versions from"
+                    + " its creation on");
         }
     }
 
+    /**
+     * Whether a failure means the branch does not exist. A checkout reports 
"branch <name> does not exist", or a
+     * missing manifest under the branch directory when nothing was ever 
committed there; a namespace that reports
+     * the branch itself throws {@link TableBranchNotFoundException}.
+     */
+    private static boolean isBranchNotFound(Throwable throwable, String 
branch) {
+        if (ExceptionUtils.indexOfType(throwable, 
TableBranchNotFoundException.class) >= 0) {
+            return true;
+        }
+        String rootMessage = ExceptionUtils.getRootCauseMessage(throwable);
+        if (rootMessage == null) {
+            return false;
+        }
+        String lower = rootMessage.toLowerCase(Locale.ROOT);
+        String name = branch.toLowerCase(Locale.ROOT);
+        return lower.contains("branch " + name + " does not exist")
+                || (lower.contains("not found") && lower.contains("tree/" + 
name + "/"));
+    }
+
+    /** Whether a not-found came from the namespace client rather than 
storage. */
+    private static boolean isNamespaceMiss(Throwable throwable) {
+        return ExceptionUtils.indexOfType(throwable, 
TableVersionNotFoundException.class) >= 0
+                || ExceptionUtils.indexOfType(throwable, 
TableBranchNotFoundException.class) >= 0;
+    }
+
+    /**
+     * Every version the namespace records for the chain on {@code branch}, 
listed once per read. The whole list
+     * is needed: FOR TIME AS OF selects among it, and neither the order a 
namespace returns nor monotonic commit
+     * times can be relied on to stop early.
+     */
+    private List<TableVersion> namespaceVersions(Generation generation, 
ReadState state, Optional<String> branch,
+            LanceMetadataMetrics.Timer timer) {
+        return state.namespaceVersions.computeIfAbsent(branch.orElse(""), 
chain -> {
+            List<TableVersion> versions = timer.measure(Stage.VERSION_RESOLVE,
+                    () -> 
generation.namespaceClient.listManagedVersions(state.access, branch));
+            if (versions.isEmpty()) {
+                throw new UserFacingException("Lance namespace lists no 
versions for " + state.tableName
+                        + (chain.isEmpty() ? "" : "@" + chain));
+            }
+            return versions;
+        });
+    }
+
+    /**
+     * Resolves {@code FOR TIME AS OF} to a version on the chain {@code 
latest} is checked out on, from the commit
+     * times the manifests in storage record, over the history {@link 
LanceSnapshotResolver} describes. A managed
+     * table only selects among the versions its namespace records. A version 
it no longer records between
+     * recorded ones cuts the history like a removed one, and so does a 
recorded version storage lacks, since its
+     * commit time is unknown.
+     */
+    private long resolveVersionAtOrBefore(Generation generation, Dataset 
latest, LanceTableAccess access,
+            long timestamp, String requestedText, ReadState state, 
LanceMetadataMetrics.Timer timer) {
+        state.pinned = null;
+        Map<Long, TableVersion> records = null;

Review Comment:
   Done in 8fa3b5fd49f: the loop keeps `Map<Long, 
LanceManifestPaths.Recorded>`, and the removed-history catch and `state.pinned` 
look the result up. `RecordedVersion` now requires the kind, which the selected 
version always has, since the resolver only selects recorded versions.
   



##########
fe/fe-connector/fe-connector-lance/src/main/java/org/apache/doris/connector/lance/LanceConnectorMetadata.java:
##########
@@ -246,34 +247,79 @@ public Optional<ConnectorMvccSnapshot> 
beginQuerySnapshot(ConnectorSession sessi
     }
 
     /**
-     * {@code FOR VERSION AS OF <n>} opens version {@code n}; {@code FOR TIME 
AS OF '<time>'} opens the
-     * main-chain version committed last at or before that time in the session 
time zone. Tags, branches
-     * and scan options are not supported yet and fail rather than read the 
newest version.
+     * {@code FOR VERSION AS OF <n>} opens version {@code n}, and a 
non-numeric {@code FOR VERSION AS OF 'name'}
+     * names a tag, as for Paimon and for tag names in Iceberg; {@code FOR 
TIME AS OF '<time>'} opens the version
+     * committed last at or before that time in the session time zone. {@code 
@tag(name)} opens the version the tag
+     * points at, on the branch of that version; {@code @branch(name)} the 
latest version of the branch, where
+     * {@code main} is the main chain. A version or a time inside an {@code 
@branch} selects among the branch's own
+     * versions, which start at the version it was created from. Scan options 
and incremental reads fail rather
+     * than read the newest version. The pin carries the branch in {@link 
#BRANCH_PROPERTY}.
      */
     @Override
     public Optional<ConnectorMvccSnapshot> resolveTimeTravel(ConnectorSession 
session,
             ConnectorTableHandle handle, ConnectorTimeTravelSpec spec) {
-        LanceTableHandle lanceHandle = (LanceTableHandle) handle;
+        LanceTableHandle table = ((LanceTableHandle) handle).unpinned();
+        LanceRefSelector selector = selector(session, table, spec);
         LanceTableMetadata metadata;
+        if (selector.getTag().isPresent() || selector.isTime()) {

Review Comment:
   This doesn't happen for repeated references to the same selector. 
`resolveTimeTravel` is only called from 
`PluginDrivenMvccExternalTable.loadSnapshot`, which 
`StatementContext.loadSnapshots` calls once per table and selector in a 
statement (`MvccTableInfo` keyed by `versionKeyOf(tableSnapshot, scanParams)`). 
So `t@tag(v2) a JOIN t@tag(v2) b` resolves and reads once, and both scans then 
hit the `t@2` memo entry. A second read only happens for two different 
selectors that land on the same version, such as `t@tag(v2)` and `t FOR VERSION 
AS OF 'v2'`. The second one has to read the tag, or compare commit times, 
anyway to learn its version; what gets discarded is the walk over a fragment 
list whose manifest is already in the session cache. `FOR TIME AS OF` worked 
this way before this PR too.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to