From d9eaf85cd7bed716be6bb2661a3f5687ff7ae432 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20L=E1=BB=99c=20Ph=C3=BAc?= <112325531+omninguyen@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:44:47 +0700 Subject: [PATCH] perf(lance): skip unused _versions lookups (#13371) * lance: skip unused _versions lookups Read _versions/ only for include_declared=false, check_declared or a new-name register: listings now do one lookup per table instead of two (about 45% faster at 100-500 tables). A failed _versions lookup no longer hides a table that never needed it. Adds visibility regression tests, lookup-count tests and a benchmark. Co-Authored-By: Claude Opus 5.5 * lance: read the deregistered marker through datasetState Co-Authored-By: Claude Opus 5.5 * lance: trim the dataset-state comments Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- weed/s3api/lance/dataset_state_test.go | 294 ++++++++++++++++++ weed/s3api/lance/handlers_table.go | 15 +- weed/s3api/lance/listing_lookup_bench_test.go | 150 +++++++++ weed/s3api/lance/listing_lookup_test.go | 211 +++++++++++++ weed/s3api/lance/markers.go | 11 +- 5 files changed, 669 insertions(+), 12 deletions(-) create mode 100644 weed/s3api/lance/dataset_state_test.go create mode 100644 weed/s3api/lance/listing_lookup_bench_test.go create mode 100644 weed/s3api/lance/listing_lookup_test.go diff --git a/weed/s3api/lance/dataset_state_test.go b/weed/s3api/lance/dataset_state_test.go new file mode 100644 index 0000000000..f665b869a4 --- /dev/null +++ b/weed/s3api/lance/dataset_state_test.go @@ -0,0 +1,294 @@ +package lance + +import ( + "errors" + "net/http" + "net/http/httptest" + "slices" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" +) + +// These tests pin what the catalog reports about a Lance table from the +// marker files beside its dataset: .lance-deregistered hides it, and +// _versions/ is what separates a table holding data from one only declared. + +// addVersions gives the dataset in dir a version manifest, which is what a +// Lance client writing data leaves behind. +func addVersions(h *testHarness, dir string) { + h.filer.Put(dir, versionsDir, nil) + h.filer.PutFile(dir+"/"+versionsDir, "1.manifest", time.Now()) +} + +// seedTableStates declares, in namespace bucket$ns, one table in each state a +// listing has to tell apart, and returns the identifiers of the two that are +// registered. +func seedTableStates(t *testing.T, h *testHarness, bucket, ns string) (declaredOnly, withData string) { + t.Helper() + prefix := bucket + "$" + ns + "$" + h.mustDo(t, http.MethodPost, "/v1/namespace/"+bucket+"$"+ns+"/create", `{}`, http.StatusOK) + declareLanceTable(t, h, prefix+"declared_only") + addVersions(h, declareLanceTable(t, h, prefix+"with_data")) + addVersions(h, declareLanceTable(t, h, prefix+"deregistered_with_data")) + h.mustDo(t, http.MethodPost, "/v1/table/"+prefix+"deregistered_with_data/deregister", `{}`, http.StatusOK) + declareLanceTable(t, h, prefix+"deregistered_empty") + h.mustDo(t, http.MethodPost, "/v1/table/"+prefix+"deregistered_empty/deregister", `{}`, http.StatusOK) + return prefix + "declared_only", prefix + "with_data" +} + +func listedTables(t *testing.T, h *testHarness, target string) []string { + t.Helper() + listed := decode[ListTablesResponse](t, h.mustDo(t, http.MethodGet, target, "", http.StatusOK)) + tables := slices.Clone(listed.Tables) + slices.Sort(tables) + return tables +} + +func TestListTablesVisibility(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + declaredOnly, withData := seedTableStates(t, h, "analytics", "sales") + + // an undeclared bucket holds both formats; only the Lance table is listed + h.createBucket(t, "mixed", "") + h.mustDo(t, http.MethodPost, "/v1/namespace/mixed$sales/create", `{}`, http.StatusOK) + addVersions(h, declareLanceTable(t, h, "mixed$sales$vectors")) + var created s3tables.CreateTableResponse + if err := h.admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), s3tables.NewManagerClient(h.filer.Client), "CreateTable", + &s3tables.CreateTableRequest{ + TableBucketARN: h.bucketARN(t, "mixed"), + Namespace: []string{"sales"}, + Name: "ledger", + Format: s3tables.FormatIceberg, + MetadataLocation: "s3://mixed/sales/ledger/metadata/v1.metadata.json", + }, &created, ""); err != nil { + t.Fatalf("create iceberg table: %v", err) + } + + for _, tc := range []struct { + query string + analytics []string + }{ + {query: "", analytics: []string{declaredOnly, withData}}, + {query: "?include_declared=true", analytics: []string{declaredOnly, withData}}, + {query: "?include_declared=false", analytics: []string{withData}}, + } { + if got := listedTables(t, h, "/v1/namespace/analytics$sales/table/list"+tc.query); !slices.Equal(got, tc.analytics) { + t.Errorf("ListTables%s = %v, want %v", tc.query, got, tc.analytics) + } + if got, want := listedTables(t, h, "/v1/namespace/mixed$sales/table/list"+tc.query), []string{"mixed$sales$vectors"}; !slices.Equal(got, want) { + t.Errorf("ListTables%s in a mixed bucket = %v, want %v", tc.query, got, want) + } + } +} + +// ListAllTables lists declared-only tables too, and does not read +// include_declared at all. +func TestListAllTablesVisibility(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + h.createBucket(t, "metrics", s3tables.FormatLance) + a1, a2 := seedTableStates(t, h, "analytics", "sales") + m1, m2 := seedTableStates(t, h, "metrics", "ops") + want := []string{a1, a2, m1, m2} + slices.Sort(want) + + for _, query := range []string{"", "?include_declared=false"} { + if got := listedTables(t, h, "/v1/table"+query); !slices.Equal(got, want) { + t.Errorf("ListAllTables%s = %v, want %v", query, got, want) + } + } +} + +func TestListTablesDelimiterAndPaging(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + declaredOnly, withData := seedTableStates(t, h, "analytics", "sales") + + dotted := listedTables(t, h, "/v1/namespace/analytics.sales/table/list?delimiter=.") + if want := []string{"analytics.sales.declared_only", "analytics.sales.with_data"}; !slices.Equal(dotted, want) { + t.Errorf("ListTables with delimiter . = %v, want %v", dotted, want) + } + + // One table a page: the token walks every catalog record, the deregistered + // ones answer as empty pages, and nothing is listed twice. + var all []string + token := "" + for page := 0; ; page++ { + if page > 10 { + t.Fatalf("paging did not end; listed so far %v", all) + } + target := "/v1/namespace/analytics$sales/table/list?limit=1" + if token != "" { + target += "&page_token=" + token + } + listed := decode[ListTablesResponse](t, h.mustDo(t, http.MethodGet, target, "", http.StatusOK)) + if len(listed.Tables) > 1 { + t.Fatalf("page %d holds %v, more than limit=1", page, listed.Tables) + } + all = append(all, listed.Tables...) + if listed.PageToken == "" { + break + } + token = listed.PageToken + } + slices.Sort(all) + if want := []string{declaredOnly, withData}; !slices.Equal(all, want) { + t.Errorf("tables across pages = %v, want %v", all, want) + } +} + +func TestDescribeTableCheckDeclared(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + declaredOnly, withData := seedTableStates(t, h, "analytics", "sales") + + describe := func(id, query, body string) DescribeTableResponse { + t.Helper() + return decode[DescribeTableResponse](t, + h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/describe"+query, body, http.StatusOK)) + } + + for _, id := range []string{declaredOnly, withData} { + for _, req := range []struct{ query, body string }{ + {"", `{}`}, + {"?check_declared=false", `{}`}, + {"", `{"check_declared":false}`}, + } { + if got := describe(id, req.query, req.body).IsOnlyDeclared; got != nil { + t.Errorf("describe %s%s %s: is_only_declared = %v, want it absent", id, req.query, req.body, *got) + } + } + } + + for _, req := range []struct{ query, body string }{ + {"?check_declared=true", `{}`}, + {"", `{"check_declared":true}`}, + } { + for id, want := range map[string]bool{declaredOnly: true, withData: false} { + got := describe(id, req.query, req.body).IsOnlyDeclared + if got == nil || *got != want { + t.Errorf("describe %s%s %s: is_only_declared = %v, want %v", id, req.query, req.body, got, want) + } + } + recorder := h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$deregistered_with_data/describe"+req.query, req.body, http.StatusNotFound) + if code := decode[errorResponse](t, recorder).Code; code != codeTableNotFound { + t.Errorf("describe of a deregistered table%s %s: code %d, want %d", req.query, req.body, code, codeTableNotFound) + } + } +} + +// A deregistered table is absent to every operation until it is registered +// again, and registering it again is not a conflict. +func TestDeregisteredTableIsAbsent(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + declaredOnly, withData := seedTableStates(t, h, "analytics", "sales") + gone := "analytics$sales$deregistered_with_data" + + internal := func(id string) error { + t.Helper() + parts, err := parseIdentifier(id, defaultDelimiter) + if err != nil { + t.Fatalf("parse %s: %v", id, err) + } + _, _, err = h.server.DescribeTableInternal(httptest.NewRequest(http.MethodPost, "/", nil), parts) + return err + } + + for _, id := range []string{declaredOnly, withData} { + h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/exists", `{}`, http.StatusOK) + h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/describe", `{}`, http.StatusOK) + if err := internal(id); err != nil { + t.Errorf("DescribeTableInternal(%s) = %v, want the table", id, err) + } + } + location := `{"location":"s3://analytics/sales/with_data"}` + h.mustDo(t, http.MethodPost, "/v1/table/"+withData+"/register", location, http.StatusConflict) + + h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/exists", `{}`, http.StatusNotFound) + h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/describe", `{}`, http.StatusNotFound) + var tablesErr *s3tables.S3TablesError + if err := internal(gone); !errors.As(err, &tablesErr) || tablesErr.Type != s3tables.ErrCodeNoSuchTable { + t.Errorf("DescribeTableInternal of a deregistered table = %v, want %s", err, s3tables.ErrCodeNoSuchTable) + } + + h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/register", + `{"location":"s3://analytics/sales/deregistered_with_data"}`, http.StatusOK) + if h.filer.Get("/buckets/analytics/sales/deregistered_with_data", deregisteredMarker) != nil { + t.Errorf("register left %s behind", deregisteredMarker) + } + h.mustDo(t, http.MethodPost, "/v1/table/"+gone+"/exists", `{}`, http.StatusOK) + if got := listedTables(t, h, "/v1/namespace/analytics$sales/table/list"); !slices.Contains(got, gone) { + t.Errorf("re-registered table missing from the listing %v", got) + } +} + +// The markers are read where the catalog record says the dataset is: its +// recorded location, or the name path when it records none. +func TestListingReadsMarkersAtTheRecordedLocation(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK) + client := s3tables.NewManagerClient(h.filer.Client) + create := func(name, location string) { + t.Helper() + var resp s3tables.CreateTableResponse + if err := h.admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), client, "CreateTable", &s3tables.CreateTableRequest{ + TableBucketARN: h.bucketARN(t, "analytics"), + Namespace: []string{"sales"}, + Name: name, + Format: s3tables.FormatLance, + MetadataLocation: location, + }, &resp, ""); err != nil { + t.Fatalf("create %s: %v", name, err) + } + } + create("unplaced", "") + create("alias", "s3://analytics/sales/store") + + var summaries s3tables.ListTablesResponse + if err := h.admin.Execute(t.Context(), client, "ListTables", &s3tables.ListTablesRequest{ + TableBucketARN: h.bucketARN(t, "analytics"), Namespace: []string{"sales"}, + }, &summaries, ""); err != nil { + t.Fatalf("list tables: %v", err) + } + for _, summary := range summaries.Tables { + if summary.Name == "unplaced" && summary.MetadataLocation != "" { + t.Fatalf("unplaced records location %q; the fallback case needs none", summary.MetadataLocation) + } + } + + list := func(query string) []string { + t.Helper() + return listedTables(t, h, "/v1/namespace/analytics$sales/table/list"+query) + } + both := []string{"analytics$sales$alias", "analytics$sales$unplaced"} + if got := list(""); !slices.Equal(got, both) { + t.Fatalf("listing = %v, want %v", got, both) + } + + // data at the name path does not count for a table recorded elsewhere + addVersions(h, "/buckets/analytics/sales/alias") + if got := list("?include_declared=false"); len(got) != 0 { + t.Errorf("include_declared=false with data only at the name paths = %v, want none", got) + } + addVersions(h, "/buckets/analytics/sales/store") + addVersions(h, "/buckets/analytics/sales/unplaced") + if got := list("?include_declared=false"); !slices.Equal(got, both) { + t.Errorf("include_declared=false with data at the recorded locations = %v, want %v", got, both) + } + + // a marker at the name path does not hide a table recorded elsewhere + h.filer.PutFile("/buckets/analytics/sales/alias", deregisteredMarker, time.Now()) + if got := list(""); !slices.Equal(got, both) { + t.Errorf("listing with a marker only at alias's name path = %v, want %v", got, both) + } + h.filer.PutFile("/buckets/analytics/sales/store", deregisteredMarker, time.Now()) + h.filer.PutFile("/buckets/analytics/sales/unplaced", deregisteredMarker, time.Now()) + if got := list(""); len(got) != 0 { + t.Errorf("listing with markers at the recorded locations = %v, want none", got) + } +} diff --git a/weed/s3api/lance/handlers_table.go b/weed/s3api/lance/handlers_table.go index e84c4b51b1..1d9c00b436 100644 --- a/weed/s3api/lance/handlers_table.go +++ b/weed/s3api/lance/handlers_table.go @@ -87,7 +87,7 @@ func (s *Server) lanceTableIDs(r *http.Request, bucket string, summaries []s3tab if location == "" { location = tableLocation(bucket, summary.Namespace, summary.Name) } - deregistered, hasData, err := s.datasetState(r, location) + deregistered, hasData, err := s.datasetState(r, location, !includeDeclared) if err != nil { glog.V(2).Infof("lance: cannot read dataset state for %s: %v", location, err) continue @@ -213,7 +213,7 @@ func (s *Server) describeTable(r *http.Request, parts []string, internal bool) ( return "", nil, err } location := table.location - deregistered, _, err := s.datasetState(r, location) + deregistered, _, err := s.datasetState(r, location, false) if err != nil { return "", nil, err } @@ -262,7 +262,8 @@ func (s *Server) handleDescribeTable(w http.ResponseWriter, r *http.Request) { } location := table.location - deregistered, hasData, err := s.datasetState(r, location) + checkDeclared := wants(r, "check_declared", req.CheckDeclared) + deregistered, hasData, err := s.datasetState(r, location, checkDeclared) if err != nil { writeError(w, r, http.StatusInternalServerError, codeInternal, err.Error()) return @@ -289,7 +290,7 @@ func (s *Server) handleDescribeTable(w http.ResponseWriter, r *http.Request) { if wants(r, "with_table_uri", req.WithTableURI) { resp.TableURI = location } - if wants(r, "check_declared", req.CheckDeclared) { + if checkDeclared { onlyDeclared := !hasData resp.IsOnlyDeclared = &onlyDeclared } @@ -332,7 +333,7 @@ func (s *Server) handleTableExists(w http.ResponseWriter, r *http.Request) { writeStorageError(w, r, err) return } - deregistered, _, err := s.datasetState(r, table.location) + deregistered, _, err := s.datasetState(r, table.location, false) if err != nil { writeError(w, r, http.StatusInternalServerError, codeInternal, err.Error()) return @@ -391,7 +392,7 @@ func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) { case err == nil: // A deregistered table is absent as far as the spec is concerned, so // registering over it is a re-registration rather than a conflict. - deregistered, _, stateErr := s.datasetState(r, existing.location) + deregistered, _, stateErr := s.datasetState(r, existing.location, false) if stateErr != nil { writeError(w, r, http.StatusInternalServerError, codeInternal, stateErr.Error()) return @@ -451,7 +452,7 @@ func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) { } // CreateTable also answers for a table the caller cannot read, so // bringing that one back still needs UpdateTable. - deregistered, _, stateErr := s.datasetState(r, location) + deregistered, _, stateErr := s.datasetState(r, location, false) if stateErr != nil { glog.V(1).Infof("lance: could not check %s for %s: %v", deregisteredMarker, location, stateErr) } diff --git a/weed/s3api/lance/listing_lookup_bench_test.go b/weed/s3api/lance/listing_lookup_bench_test.go new file mode 100644 index 0000000000..070a38fc37 --- /dev/null +++ b/weed/s3api/lance/listing_lookup_bench_test.go @@ -0,0 +1,150 @@ +package lance + +import ( + "fmt" + "net/http" + "net/http/httptest" + "path" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables/s3tablestest" +) + +// These benchmarks measure the listings against the in-memory filer, whose +// lookups cost no network round trip. The rtt cases add a fixed delay to every +// filer lookup to stand in for one; they model a filer on another host, not +// any measured deployment. lookups/op and versions/op are exact counts and do +// not depend on the machine. + +// simulatedFilerRTT is the delay the rtt cases add to each filer lookup. +const simulatedFilerRTT = 200 * time.Microsecond + +type benchHarness struct { + router *mux.Router + filer *s3tablestest.MemFiler + lookups atomic.Int64 + versions atomic.Int64 + delay atomic.Int64 // nanoseconds added to each lookup +} + +// newBenchHarness seeds tablesPerBucket Lance tables in namespace ns of each +// named bucket, each holding data (a _versions/ manifest), so every listing, +// include_declared=false included, lists them all. +func newBenchHarness(b *testing.B, buckets []string, tablesPerBucket int) *benchHarness { + b.Helper() + filer := s3tablestest.Start(b) + server := NewServer(s3tables.NewManagerClient(filer.Client), openAuthenticator{}) + server.SetS3Endpoint("http://127.0.0.1:8333") + server.SetS3Region(s3tables.DefaultRegion) + router := mux.NewRouter().SkipClean(true) + server.RegisterRoutes(router) + h := &benchHarness{router: router, filer: filer} + + admin := s3tables.NewManager() + admin.SetTrusted(true) + for _, bucket := range buckets { + var resp s3tables.CreateTableBucketResponse + if err := admin.Execute(b.Context(), s3tables.NewManagerClient(filer.Client), "CreateTableBucket", + &s3tables.CreateTableBucketRequest{Name: bucket, Format: s3tables.FormatLance}, &resp, ""); err != nil { + b.Fatalf("create table bucket %s: %v", bucket, err) + } + h.mustDo(b, http.MethodPost, "/v1/namespace/"+bucket+"$ns/create", `{}`) + for i := range tablesPerBucket { + name := fmt.Sprintf("t%04d", i) + h.mustDo(b, http.MethodPost, "/v1/table/"+bucket+"$ns$"+name+"/declare", `{}`) + dir := "/buckets/" + bucket + "/ns/" + name + if filer.Get(path.Dir(dir), name) == nil { + filer.Put(path.Dir(dir), name, nil) + } + filer.Put(dir, versionsDir, nil) + filer.PutFile(dir+"/"+versionsDir, "1.manifest", time.Now()) + } + } + + filer.OnLookup = func(dir, name string) { + h.lookups.Add(1) + if name == versionsDir { + h.versions.Add(1) + } + if d := time.Duration(h.delay.Load()); d > 0 { + // spin: time.Sleep overshoots a delay this short several times over + for start := time.Now(); time.Since(start) < d; { + } + } + } + return h +} + +func (h *benchHarness) mustDo(b *testing.B, method, target, body string) *httptest.ResponseRecorder { + b.Helper() + recorder := httptest.NewRecorder() + h.router.ServeHTTP(recorder, httptest.NewRequest(method, target, strings.NewReader(body))) + if recorder.Code != http.StatusOK { + b.Fatalf("%s %s = %d (%s)", method, target, recorder.Code, recorder.Body.String()) + } + return recorder +} + +// run times GET target and reports the filer lookups each request made. +func (h *benchHarness) run(b *testing.B, target string, wantTables int, rtt time.Duration) { + b.Helper() + // one request outside the timer, to check the listing is the one meant + if got := strings.Count(h.mustDo(b, http.MethodGet, target, "").Body.String(), "$ns$t"); got != wantTables { + b.Fatalf("GET %s listed %d tables, want %d", target, got, wantTables) + } + h.delay.Store(int64(rtt)) + defer h.delay.Store(0) + h.lookups.Store(0) + h.versions.Store(0) + ops := 0 + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + h.mustDo(b, http.MethodGet, target, "") + ops++ + } + b.StopTimer() + b.ReportMetric(float64(h.lookups.Load())/float64(ops), "lookups/op") + b.ReportMetric(float64(h.versions.Load())/float64(ops), "versions/op") +} + +func BenchmarkLanceListTables(b *testing.B) { + for _, tables := range []int{10, 100, 500} { + h := newBenchHarness(b, []string{"analytics"}, tables) + for _, rtt := range []time.Duration{0, simulatedFilerRTT} { + if rtt > 0 && tables > 100 { + continue // 500 tables at 200µs a lookup is too slow to repeat usefully + } + for _, query := range []string{"", "?include_declared=false"} { + label := "default" + if query != "" { + label = "include_declared=false" + } + b.Run(fmt.Sprintf("tables=%d/rtt=%s/%s", tables, rtt, label), func(b *testing.B) { + h.run(b, "/v1/namespace/analytics$ns/table/list"+query, tables, rtt) + }) + } + } + } +} + +func BenchmarkLanceListAllTables(b *testing.B) { + buckets := []string{"analytics", "metrics"} + for _, perBucket := range []int{5, 50, 250} { + h := newBenchHarness(b, buckets, perBucket) + total := perBucket * len(buckets) + for _, rtt := range []time.Duration{0, simulatedFilerRTT} { + if rtt > 0 && total > 100 { + continue + } + b.Run(fmt.Sprintf("tables=%d/rtt=%s", total, rtt), func(b *testing.B) { + h.run(b, "/v1/table", total, rtt) + }) + } + } +} diff --git a/weed/s3api/lance/listing_lookup_test.go b/weed/s3api/lance/listing_lookup_test.go new file mode 100644 index 0000000000..2608e2c26c --- /dev/null +++ b/weed/s3api/lance/listing_lookup_test.go @@ -0,0 +1,211 @@ +package lance + +import ( + "net/http" + "net/http/httptest" + "path" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" +) + +// lookupCounter counts, by entry name, the lookups the filer answers. The +// filer runs them on its own goroutines, hence the lock. +type lookupCounter struct { + mu sync.Mutex + counts map[string]int +} + +func countLookups(h *testHarness) *lookupCounter { + c := &lookupCounter{counts: map[string]int{}} + h.filer.OnLookup = func(dir, name string) { + c.mu.Lock() + c.counts[name]++ + c.mu.Unlock() + } + return c +} + +func (c *lookupCounter) reset() { + c.mu.Lock() + c.counts = map[string]int{} + c.mu.Unlock() +} + +func (c *lookupCounter) get(name string) int { + c.mu.Lock() + defer c.mu.Unlock() + return c.counts[name] +} + +// declareLanceTable declares a table and returns the filer directory of its +// dataset, creating that directory if the declare did not. +func declareLanceTable(t *testing.T, h *testHarness, id string) string { + t.Helper() + declared := decode[DeclareTableResponse](t, + h.mustDo(t, http.MethodPost, "/v1/table/"+id+"/declare", `{}`, http.StatusOK)) + dir := "/buckets/" + strings.TrimPrefix(declared.Location, "s3://") + if h.filer.Get(path.Dir(dir), path.Base(dir)) == nil { + h.filer.Put(path.Dir(dir), path.Base(dir), nil) + } + return dir +} + +// A listing needs a table's _versions/ only to drop declared-only tables, +// which ListTables does for include_declared=false and nothing else does. +// Probing it for every Lance table regardless doubles the filer lookups of +// the default listing and of ListAllTables (N tables, 2N lookups) for an +// answer that is thrown away. A deregistered table is dropped on its marker +// alone, so its _versions/ is never needed either. +func TestListingProbesVersionsOnlyWhenNeeded(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + h.createBucket(t, "metrics", s3tables.FormatLance) + h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK) + h.mustDo(t, http.MethodPost, "/v1/namespace/metrics$ops/create", `{}`, http.StatusOK) + + declareLanceTable(t, h, "analytics$sales$declared") + withData := declareLanceTable(t, h, "analytics$sales$withdata") + h.filer.Put(withData, versionsDir, nil) + h.filer.PutFile(withData+"/"+versionsDir, "1.manifest", time.Now()) + gone := declareLanceTable(t, h, "analytics$sales$gone") + h.filer.Put(gone, versionsDir, nil) + h.filer.PutFile(gone+"/"+versionsDir, "1.manifest", time.Now()) + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/deregister", `{}`, http.StatusOK) + declareLanceTable(t, h, "metrics$ops$latency") + + lookups := countLookups(h) + cases := []struct { + name string + target string + wantTables []string + wantMarker int // .lance-deregistered: one per Lance table listed from + wantVersions int // _versions: only where its answer decides the listing + }{ + { + name: "ListTables default", + target: "/v1/namespace/analytics$sales/table/list", + wantTables: []string{"analytics$sales$declared", "analytics$sales$withdata"}, + wantMarker: 3, + wantVersions: 0, + }, + { + name: "ListTables include_declared=true", + target: "/v1/namespace/analytics$sales/table/list?include_declared=true", + wantTables: []string{"analytics$sales$declared", "analytics$sales$withdata"}, + wantMarker: 3, + wantVersions: 0, + }, + { + name: "ListTables include_declared=false", + target: "/v1/namespace/analytics$sales/table/list?include_declared=false", + wantTables: []string{"analytics$sales$withdata"}, + wantMarker: 3, + // declared and withdata; gone is dropped on its marker + wantVersions: 2, + }, + { + name: "ListAllTables", + target: "/v1/table", + wantTables: []string{"analytics$sales$declared", "analytics$sales$withdata", "metrics$ops$latency"}, + wantMarker: 4, + wantVersions: 0, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + lookups.reset() + listed := decode[ListTablesResponse](t, h.mustDo(t, http.MethodGet, tc.target, "", http.StatusOK)) + + got := slices.Clone(listed.Tables) + slices.Sort(got) + if !slices.Equal(got, tc.wantTables) { + t.Errorf("tables = %v, want %v", got, tc.wantTables) + } + if n := lookups.get(deregisteredMarker); n != tc.wantMarker { + t.Errorf("%s lookups = %d, want %d", deregisteredMarker, n, tc.wantMarker) + } + if n := lookups.get(versionsDir); n != tc.wantVersions { + t.Errorf("%s lookups = %d, want %d: the listing probed data it does not use", versionsDir, n, tc.wantVersions) + } + }) + } +} + +// Describe, exists and register read a table's _versions/ only where the +// answer is used: describe with check_declared, and the register of a new +// name, which needs a dataset at the location. Everything else decides on the +// .lance-deregistered marker alone. +func TestHandlersProbeVersionsOnlyWhenNeeded(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK) + declareLanceTable(t, h, "analytics$sales$declared") + addVersions(h, declareLanceTable(t, h, "analytics$sales$withdata")) + addVersions(h, declareLanceTable(t, h, "analytics$sales$gone")) + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/deregister", `{}`, http.StatusOK) + h.filer.Put("/buckets/analytics/sales", "imported", nil) + addVersions(h, "/buckets/analytics/sales/imported") + + internal := func(id string) { + t.Helper() + parts, err := parseIdentifier(id, defaultDelimiter) + if err != nil { + t.Fatalf("parse %s: %v", id, err) + } + if _, _, err := h.server.DescribeTableInternal(httptest.NewRequest(http.MethodPost, "/", nil), parts); err != nil { + t.Fatalf("DescribeTableInternal(%s): %v", id, err) + } + } + + lookups := countLookups(h) + // in order: re-registering gone and registering imported change the state + cases := []struct { + name string + do func() + wantMarker int + wantVersions int + }{ + {"describe", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$declared/describe", `{}`, http.StatusOK) + }, 1, 0}, + {"describe check_declared", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$withdata/describe?check_declared=true", `{}`, http.StatusOK) + }, 1, 1}, + {"describe check_declared deregistered", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/describe?check_declared=true", `{}`, http.StatusNotFound) + }, 1, 0}, + {"DescribeTableInternal", func() { internal("analytics$sales$withdata") }, 1, 0}, + {"exists", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$withdata/exists", `{}`, http.StatusOK) + }, 1, 0}, + {"register existing name", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$withdata/register", + `{"location":"s3://analytics/sales/withdata"}`, http.StatusConflict) + }, 1, 0}, + {"register deregistered name", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$gone/register", + `{"location":"s3://analytics/sales/gone"}`, http.StatusOK) + }, 1, 0}, + {"register new name", func() { + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$imported/register", + `{"location":"s3://analytics/sales/imported"}`, http.StatusOK) + }, 1, 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + lookups.reset() + tc.do() + if n := lookups.get(deregisteredMarker); n != tc.wantMarker { + t.Errorf("%s lookups = %d, want %d", deregisteredMarker, n, tc.wantMarker) + } + if n := lookups.get(versionsDir); n != tc.wantVersions { + t.Errorf("%s lookups = %d, want %d: the handler probed data it does not use", versionsDir, n, tc.wantVersions) + } + }) + } +} diff --git a/weed/s3api/lance/markers.go b/weed/s3api/lance/markers.go index 88f4977f7d..9d54cc1055 100644 --- a/weed/s3api/lance/markers.go +++ b/weed/s3api/lance/markers.go @@ -84,15 +84,16 @@ func (s *Server) removeMarker(r *http.Request, location, name string) error { // datasetState reports the two things the spec asks about a table's storage: // whether it has been deregistered, and whether it holds data yet. A dataset // holds data once it has a version manifest, which is how a directory catalog -// decides the same question. -func (s *Server) datasetState(r *http.Request, location string) (deregistered, hasData bool, err error) { +// decides the same question. _versions/ is read only when checkData is set +// and the table is not deregistered; otherwise hasData is false. +func (s *Server) datasetState(r *http.Request, location string, checkData bool) (deregistered, hasData bool, err error) { dir := datasetDir(location) if dir == "" { return false, false, nil } - if deregistered, err = s.entryExists(r, dir, deregisteredMarker); err != nil { - return false, false, err + if deregistered, err = s.entryExists(r, dir, deregisteredMarker); err != nil || deregistered || !checkData { + return deregistered, false, err } hasData, err = s.entryExists(r, dir, versionsDir) - return deregistered, hasData, err + return false, hasData, err }