Compare commits

...
Author SHA1 Message Date
user.emailandDevin 7ab73b914e dlm: advance the mutation seq on a lost-renewal replay
The replayed lease extension kept the old seq, so InsertBackupLock
dropped it as stale and a promoted backup would have expired the
recovered lock early.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 19:49:33 -07:00
user.emailandDevin f7684c4478 dlm: replay the current token on a lost renewal's retry
A renewal rotates the token server-side before the response is sent. When
that response is lost the client only knows the superseded token: retries
mismatched, the token was cleared, and the holder conflicted with its own
lease until it expired. The lock now remembers the superseded token, so a
retry from the same owner replays the current token, and a superseded
token can still release its own lock.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 19:30:07 -07:00
user.emailandDevin db02eea349 cluster: bound connection acquisition inside the lock attempt
A blocking dial ran under context.Background(), so a caller supplying
grpc.WithBlock() could wait past the attempt window before the RPC
deadline even started. The attempt context now covers both
getOrCreateConnection and the DistributedLock call, and WithGrpcClient
threads it into GrpcDial on both the cached and streaming paths.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 18:42:49 -07:00
user.email dbf2c3d30f cluster: keep the renew token across a failed attempt
A renewal can rotate the token server-side before its response is lost,
and clearing the token on any RPC failure then abandons a live lease the
client can neither renew nor unlock. Keep the token so the next attempt
retries with it: it still validates when the request never landed, and a
definitive rejection clears it through the response's empty RenewToken.
2026-10-26 17:49:33 -07:00
user.email ad73b66200 cluster: bound the whole lock-acquisition window
A single bounded attempt can take most of noLockServerRetryPeriod before
the retry clock even starts, so an unreachable owner stalls acquisition
roughly two attempts past the intended window. Start the clock before
the first attempt and cap each attempt by what remains; contention still
waits it out.
2026-10-26 17:49:18 -07:00
user.email fcc7bd04c6 cluster: bound each DistributedLock attempt
A lock-ring member reachable from the masters but not from this filer
makes one DistributedLock attempt wait out the TCP connect timeout, so a
write whose key hashes to it stalls far past noLockServerRetryPeriod
before failing. Give the attempt a 10s context deadline so the retry
window can take effect; a timed-out attempt keeps no renew token, so the
lock server still grants the key to at most one owner.
2026-10-26 17:38:19 -07:00
Chris LuandDevin a9d6bfc51f test: boto3 s3vectors conformance harness (P1) (#12105)
* vector: boto3 s3vectors conformance harness

test/vectors spins a mini cluster, an s3 gateway with -port.vectors and
-vectors.grpc, and a weed-vector-server, then exercises the AWS client
end to end: bucket and index lifecycle, put/get/list/delete vectors,
and a filtered query asserting distances and metadata.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci: run the s3vectors conformance subset

An e2e job in rust-vector-tests: builds weed and weed-vector-server,
then runs test/vectors against a mini cluster plus the vectors gateway.
The workflow now also watches vector.proto, its stubs, and test/vectors.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci: fix e2e protoc and codespell findings

The e2e job needed the same vendored-protoc step as the unit-test job —
lance's build scripts locate protoc themselves. Codespell flags the AWS
`$nin` operator literal and the `lits` variable: exempt `nin` in
.codespellrc like the existing word exemptions, rename the variable,
and fold the negation into the IN/NOT IN symbol directly.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: classify catalog errors by code, not message text

* s3: drop the implicit vector namespace on vector-bucket delete

* test: point the vector engine at the gateway lance port

* test: bind the vectors gateway listeners to loopback

* test: make the filter and distance assertions load-bearing

* test: rebuild the harness binaries on every run

* ci: fix the vectors end-to-end job

* ci: run the vector tests on gateway and command changes

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 15:53:50 -07:00
Chris Lu c55b7c5a29 s3: fix CreateIndex metadata panic and ListVectors segmented paging (#12106)
* s3: nil-check metadataConfiguration before reading its keys

* s3: honor maxResults/nextToken in segmented ListVectors

* s3: exclude non-Lance buckets from ListVectorBuckets

* s3: test segmented ListVectors paging token math

* ci: silence codespell on the "$nin" operator and rename lits
2026-10-26 15:40:25 -07:00
Chris LuandDevin dcc94f818d vector: S3 Vectors API gateway (P1) (#12103)
* vector: S3 Vectors API gateway over VectorService

weed/s3api/s3vectors serves the AWS S3 Vectors JSON API: bucket CRUD
maps to S3 Tables table buckets, index CRUD to Lance table records plus
the VectorService CreateIndex/DropIndex RPCs, and the data plane
(Put/Get/List/Delete/QueryVectors) calls the shared service. The AWS
filter document translates to a Lance SQL predicate over the metadata
JSON column; unsupported operators fail loudly rather than overmatch.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: -port.vectors and -vectors.grpc on weed s3

Mirror the Lance server startup: the S3 Vectors API binds its own port
and dials the weed-vector-server gRPC address; both disabled by default.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: resolve index ARNs, authorize index ops, fix catalog fields

- vector buckets declare FormatLance so a new bucket accepts index
  tables instead of defaulting to ICEBERG.
- ListIndexes decodes the `tables` response field; `tableSummaries`
  hid every index.
- resolveIndexARNs honors indexArn alone; handlers no longer treat
  indexName as the only carrier.
- data-plane RPCs fetch the index record first, so callers authorize
  against the index resource and a missing index 404s before touching
  the engine; QueryVectors reports the index's configured metric.
- IndexArn added to the index-level request types.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: serve the vectors port over TLS when configured

When -key.file/-cert.file are set, the vectors listener mirrors the
main API and serves TLS rather than a second plaintext endpoint.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: harden the s3vectors gateway handlers

- $ne no longer shadows the operator: exclusion filters emit <>
  instead of equality.
- a null element in a PutVectors list fails the request instead of
  panicking.
- requests are capped at 32 MiB; distances return via *float32 so an
  exact match still reports 0 when returnDistance is set.
- CreateIndex declares the `vector` namespace first and validates
  dimension (1..=4096) before the catalog write; a failed
  VectorService.CreateIndex rolls the table record back.
- non-filterable metadata keys persist as JSON rather than a
  comma-joined string, and index records carry their createdAt.
- ListVectors honors segmentIndex/segmentCount by slicing the full
  listing in the gateway.
- catalog errors map to AccessDeniedException/ConflictException instead
  of a blanket ValidationException, and malformed ARNs 400 instead of
  slicing.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: /{Operation} routes and vectors-port TLS, conn cleanup

Path-dispatched clients (POST /QueryVectors) reach the same handlers as
X-Amz-Target calls. A failed listener bind now closes the vector gRPC
connection instead of leaving it open with the endpoint disabled.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 14:57:44 -07:00
Chris Lu 74abcb630e ci: retry the timing-sensitive s3 lifecycle expiration tests once (#12073)
* ci: retry the timing-sensitive s3 lifecycle expiration tests once

test_lifecycle_expiration and test_lifecyclev2_expiration assert exact
object counts after fixed sleeps. The lifecycle worker expires objects
via meta-log replay, and under the suite's write flood a shard's replay
can trail an object's PUT event past the test's window (observed on
master and PR runs, SQL-store job only). Split them out of the main
list and allow one retry; each attempt is independent so real
regressions still fail.

* ci: allow a second retry for s3 lifecycle expiration tests
2026-10-26 13:39:40 -07:00
Jay Hemnanianduser.email 1e7afbacf4 s3: list every bucket when auth is off (#12077)
* s3: list every bucket when auth is off

With no identities configured, every request may create, read and
write any bucket, but ListBuckets treated the caller as an
unauthenticated user and returned an empty list, so `aws s3 ls` showed
nothing. List all buckets in that mode, with prefix, max-buckets and
continuation tokens as before. Listing with auth on is unchanged.

* s3: cover the auth-on anonymous ListBuckets case

The no-auth listing change also moves the nil-identity gate; pin the
security-relevant direction that a request without an identity still
sees no buckets once auth enforcement is on.

* s3: verify ListBuckets continuation token reaches the next page

---------

Co-authored-by: user.email <chrislusf@users.noreply.github.com>
2026-10-26 13:38:36 -07:00
Chris LuandDevin 87f15e4d6c vector: weed-vector-server, the VectorService gRPC (P1) (#12102)
* vector: VectorService protobuf contract

The shared RPC boundary between the Go S3 gateway and the Rust vector
engine from the vector design doc: CreateIndex/DropIndex, Put/Get/
List/Delete/Query vectors. A Table reference carries the Lance table id
and an optional pinned version, matching the snapshot discipline queries
are required to keep.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: generated Go stubs for vector.proto

protoc output via weed/pb/Makefile.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: carry return_data through QueryVectors

S3 Vectors QueryVectors honours returnData, but the contract had no
way to ask for or carry vector data in a query response, so the
gateway would need a second GetVectors round-trip per query. Add
return_data to the request and data to QueryResult now, while the
contract is still new.

* vector: pin metadata numbers to double precision in the contract

Metadata arrives as JSON, where numbers carry double precision; say
so on the field so neither side promises integer fidelity past 2^53.

* vector: declare_table on the lance namespace client

CreateIndex needs a way to ask the catalog for a new table's location;
expose POST /v1/table/{id}/declare.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: cargo fmt coverage.rs

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: weed-vector-server, the VectorService gRPC

A tonic server over weed-vector-core: CreateIndex declares the table
through the namespace and writes an empty {key, vector, metadata}
dataset; PutVectors upserts by key (delete + append until merge_insert
is exercised); Get/List/Delete/Query route through the engine's
resolved table, honoring pinned versions and the prefilter default.
Metadata travels as a Utf8 JSON column, proto Struct on the wire.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: stamp the metric in the schema, tighten put validation

CreateIndex now bounds dimension at the S3 Vectors 4096 maximum and
records the distance metric in the vector field's Arrow metadata, so a
later reader recovers the index's configured metric from the table
itself. batch_of checks every vector's data length individually before
flattening — equal totals could still let a short vector borrow floats
from its neighbor — and writes against the dataset's own schema.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: upsert vectors in a single merge commit

PutVectors ran delete-then-append: a failed append left the old keys
deleted, and two concurrent puts could both append a replacement. Use
lance's merge_insert on the key column — one commit, no delete window,
conflicts fail the request instead of duplicating keys.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: read the index's metric; fetch metadata in one take

QueryVectors hardcoded L2 — it now reads the metric the index was
created with from the vector field's metadata. return_metadata fetched
each hit's row one at a time; collect the row ids into a single
take_rows call and join metadata back on the hit key.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: honor return_data in query results

QueryResult grew a data field but query_vectors never populated it.
Fetch the vector column in the same batched take_rows as metadata and
return each hit's stored embedding.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: reject a malformed query as invalid_argument

A zero top_k silently became one result and a dim-mismatched query
vector surfaced as an internal scan error; reject both before querying.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: reject a malformed list next_token

A token that failed to parse silently restarted the listing from
offset zero; surface it as invalid_argument instead.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: answer an empty put without a commit and cover ragged input

An empty vectors list would still run a merge commit; return the
current version instead. Pin the ragged-vector check with a test.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: keep non_filterable_metadata_keys on the table schema

create_index dropped the declared filter policy. Persist it as JSON on
the metadata field so the index carries which keys a filter may touch;
enforcing the list belongs to the gateway that translates the request
filter into Lance SQL.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: reject duplicate keys in one put

A repeated key for a new row committed both copies, and for an existing
key the merge failure surfaced as internal. Reject duplicates up front
as invalid_argument.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: report open failures as not_found or unavailable

A catalog 404 or a missing dataset/version is not a client mistake, and a
catalog outage is retryable: mapping every open error to invalid_argument
made both indistinguishable from a bad request.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: page list_vectors when max_results is unset

A proto3 client that omits max_results sends 0, which used to limit the
scan to zero rows and return no token.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: drop stray empty service.rs.tmp

* vector: rename datas map to data_map

codespell flags datas as a misspelling of data; use a distinct map name.

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 13:32:34 -07:00
Chris LuandDevin d771a91571 vector: VectorService gRPC contract (P1) (#12101)
* vector: VectorService protobuf contract

The shared RPC boundary between the Go S3 gateway and the Rust vector
engine from the vector design doc: CreateIndex/DropIndex, Put/Get/
List/Delete/Query vectors. A Table reference carries the Lance table id
and an optional pinned version, matching the snapshot discipline queries
are required to keep.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: generated Go stubs for vector.proto

protoc output via weed/pb/Makefile.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: carry return_data through QueryVectors

S3 Vectors QueryVectors honours returnData, but the contract had no
way to ask for or carry vector data in a query response, so the
gateway would need a second GetVectors round-trip per query. Add
return_data to the request and data to QueryResult now, while the
contract is still new.

* vector: pin metadata numbers to double precision in the contract

Metadata arrives as JSON, where numbers carry double precision; say
so on the field so neither side promises integer fidelity past 2^53.

* vector: clarify the query filter is raw Lance SQL over one metadata column

The doc said 'metadata columns' but the table stores all metadata in a
single JSON column named metadata; the gateway translates S3 Vectors
filter expressions onto it.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 13:26:11 -07:00
Chris Lu 6b379badbb filer: shut down test filers' meta-log buffers, fixing the 32-bit OOM (#12104)
* filer: shut down test filers' meta-log buffers, fixing the 32-bit OOM

Each log_buffer.NewLogBuffer preallocates five 8 MiB windows and spawns
loopFlush/loopInterval goroutines that keep them reachable. The
weed/filer tests built ~70 filers and aggregators that almost never
called ShutdownLogBuffer, pinning ~2.8 GB plus live churn, and the
linux/386 job ran out of its ~4 GiB address space inside
newSealedBuffers.

- MetaAggregator.Shutdown now retires MetaLogBuffer too: the "aggr"
  buffer's loops previously outlived the aggregator.
- newTestFiler and newTestFilerWithStubStore register t.Cleanup
  shutdowns; the one-off filer/aggregator literals defer theirs.

* filer: wait for the aggregated meta-log buffer to stop in Shutdown

ShutdownLogBuffer only signals the stop; loopFlush and its pooled windows
exit asynchronously. Match Filer.Shutdown's local-buffer sequence so the
aggregator returns with the buffer's memory already released.

* filer: cancel test filers' flush context before buffer shutdown

The stub-store helpers build real NewFiler instances, so the queued
shutdown flush retries appendToFile every ~737ms under flushCtx, which
nothing ever cancelled — the buffer and its pool stayed alive past each
test. Cancelling first lets the flush drop the window and WaitForShutdown
confirms loopFlush exited.

* filer: wait for test log buffers to drain after shutdown

The stub-flush buffers cannot hang, but without WaitForShutdown their
loopFlush goroutines release the pooled windows asynchronously — the
memory this PR means to free is still counted as live while the next
test allocates.
2026-10-26 13:24:48 -07:00
Chris Lu aff18b2336 vector: restore spike CLI flags lost in the #12098 rebase (#12099)
* vector: --vector takes hyphenated floats again

* vector: --vector-column/--key-column on the get subcommand

* vector: --vector-column/--key-column on describe and coverage

* vector: surface describe resolve errors when column flags are set

* vector: cover the restored CLI flags with parse tests
2026-10-26 12:24:01 -07:00
Chris LuandDevin 72ac424198 filer: deliver meta-log events under their stream position, not their stamp (#12084)
* filer: deliver meta-log events under their stream position, not their stamp

A mutation's event timestamp is stamped before the filer store write so
the entry and its event share a commit time, while the log-buffer append
happens after the write. A write delayed behind later-stamped mutations
keeps its early stamp in the payload while AddDataToBuffer bumps
LogEntry.TsNs to keep the stream monotone - so subscribers could
receive events whose payload TsNs arrives out of order.

Consumers treat the delivered TsNs as a stream position (cursors,
watermarks, replay windows). The s3 lifecycle daily-run drains events in
order and pins its per-shard cursor behind the first not-yet-due match;
an event delivered with a stale stamp after the cursor already passed it
is filtered out forever and its pending match silently never fires -
the flaky test_lifecyclev2_expiration signature of exactly one object of
a same-rule pair surviving, with errors=0 on every pass.

Normalize event.TsNs to logEntry.TsNs at delivery (and for the
skeleton-filtered heartbeat) so delivered timestamps are monotone by
construction. The commit-time stamp remains available on the entries
themselves via CommitTsNs.

* pb,filer: stamp metadata events with a mutation timestamp

TsNs on the wire now carries the delivery stream position, so the
mutation's commit stamp needs its own field. Add mutation_ts_ns to
SubscribeMetadataResponse and set it when the event is created.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: carry the mutation stamp through event delivery

Delivery rewrites TsNs to the stream position; the payload stamp survives
in MutationTsNs, backfilled from TsNs for payloads written before the
field existed. The notification callback forwards it to the wire message.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* pb: normalize chunk-replay timestamps like eachLogEntryFn

ReadLogFileRefs bypasses the server decode path, so a delayed append
still arrived under its stale payload stamp and could hide behind a
subscriber cursor. Deliver the stream position and preserve the stamp in
MutationTsNs.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: order replay and tombstones by the mutation stamp

Replay treated the delivered TsNs as the commit time, so a peer write
delayed in its own log could overwrite a newer local entry. Compare and
stamp with MutationTsNs, falling back to TsNs for older peers.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* remote.sync: carry the mutation stamp through reshaped renames

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: test replay ordering on the mutation stamp

* filer: tombstone remote deletes by delivery position, order by commit stamp

* filer: keep the peer commit stamp when restamping aggregated events

* pb: keep the log cursor on the entry position past callback restamps

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 12:18:40 -07:00
Chris Lu 68565fa883 admin: bump a-h/templ to v0.3.1100 to match @latest codegen (#12100)
CI installs the templ CLI with `@latest`, which now generates code
calling templruntime.NewAttributeExpression — a symbol added after the
v0.3.1070 runtime pinned in go.mod, breaking `make install` builds on
clean runners. Bump the runtime to v0.3.1100 and regenerate.
2026-10-26 12:03:41 -07:00
Chris LuandDevin 3abf8b2572 filer,pb,mount: keep per-chunk cipher keys out of logs (#12085)
* filer: format ChunkView without its cipher key

readChunkSliceAt logs a failed chunk fetch with %+v, which printed the
per-chunk AES-256-GCM key into error-level logs on every failed read.
Give ChunkView a String() that omits CipherKey so %v and %+v stay safe.

* pb: scrub cipher keys when an entry must be logged whole

ScrubCipherKeys clones an Entry with chunk CipherKey fields cleared, so
a warning that needs the full entry still cannot leak the keys.

* log entry identifiers instead of whole metadata messages

Several log lines formatted whole protobuf messages — SubscribeMetadataResponse,
EventNotification, Entry-carrying requests — whose chunks include cipher_key
under -encryptVolumeData, so the keys escaped into logs (some at default
verbosity). Log the directory, entry name and event timestamp instead; where a
chunk list was printed, print file ids via FileIdsString.

* log queue: unwrap SubscribeMetadataResponse and never print raw protos

The fallback printed any message with %+v, so a SubscribeMetadataResponse
carrying entries would still put cipher keys in the log. Unwrap its event
notifications (batched events included) and reduce unknown messages to
their type name.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* remote sync logs: name the event's real path

Rename targets logged under resp.Directory while the entry lives under
NewParentPath; route them through MetadataEventTargetDirectory. Sync
failure logs printed only the directory, so same-dir failures shared an
identifier — log the source and destination paths instead.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* log queue: log the entry's destination path on moves

A cross-directory rename printed "file" -> "file" under the source
path, hiding where the entry landed. Use NewParentPath so the log
shows the destination directory next to the new name.

* admin: install the go.mod-pinned templ, not @latest

install-templ fetched templ@latest, which now emits
templruntime.NewAttributeExpression - a symbol absent from the
runtime pinned in go.mod - so every fresh 'make' regenerated
uncompilable _templ.go files. Install the go.mod version and
reinstall when the binary on PATH reports a different one.

* admin: drop stray Makefile change belonging to the templ pin PR

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* notification: join the move destination path in log queue output

A NewParentPath of "/" printed //name for moves into the root;
path.Join keeps a single leading slash.

* log queue: skip a nil event notification instead of logging an empty move

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* pb: tolerate nil chunk entries while scrubbing cipher keys for logs

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* subscription and backup failure logs name the event's file

The process/marshal failure logs printed only the event directory and
timestamp, so a failed sync left operators guessing which file failed.
Use MetadataEventSourceFullPath/MetadataEventTargetFullPath so each
failure names the source and target paths without printing the entries.

* replication: identify entry-less events without printing the proto

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: scrub cipher keys from the bucket-metadata debug dump

buildBucketMetadata marshals the whole filer entry to JSON for a V(3)
log line; a chunked entry would emit each chunk's cipher_key base64.
Marshal the scrubbed copy instead.

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 11:52:56 -07:00
Chris Lu c27d7fe5a4 s3: keep transient object-entry errors out of ErrObjectNotFound (#12083)
* s3: keep transient object-entry errors out of ErrObjectNotFound

getObjectEntry wrapped every fetch error as ErrObjectNotFound, so a
transient filer failure (busy filer, ctx deadline, transport blip) was
indistinguishable from a real miss. LifecycleDelete resolves
ErrObjectNotFound permanently as NOOP_RESOLVED, so one flaky lookup at
dispatch time silently skipped the object's expiration - errors=0, no
retry, no log. This matches the flaky s3tests
test_lifecyclev2_expiration signature: exactly one object of a
same-rule pair surviving past its window.

Only collapse genuine misses (filer not-found, version/latest-version
sentinels); everything else propagates so the worker retries it as
RETRY_LATER instead of resolving it.

Also seed bucketConfigCache in the retention test server and teach the
fake filer to inject per-path lookup errors.

* s3: keep invalid version ids on the not-found path in getObjectEntry

A malformed versionId used to collapse into ErrObjectNotFound like every
other fetch error, so the handlers answered NoSuchKey. With transient
errors now propagated, an invalid id would surface as InternalError;
fold it back into the miss classification.

* filer_pb: keep Unavailable out of LookupEntry's not-found normalization

* s3: reject Unavailable in isObjectEntryMiss before message matching

* s3: keep transient fallback errors out of latest-version resolution

* filer_pb: limit LookupEntry's not-found text match to miss statuses

* s3: limit isFilerNotFound text matching to miss statuses
2026-10-26 11:52:15 -07:00
Chris LuandDevin 8498ad716b vector: spike CLI, reference-comparison suite, CI (P0 phase 3) (#12098)
* vector: project _distance and _rowid explicitly

Lance warns that a knn projection without _distance will stop
auto-including it; spell both scoring columns out.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: reference-comparison tests

The spike's exit gate: assert the engine's answers equal a bare
scan().nearest() on the same pinned version — over a fresh index, over
unindexed fragments, over a two-segment index after optimize_indices,
and after a delete. A version-pinned handle querying through
maintenance sees only its own version.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: weed-vector spike CLI

describe / coverage / query / get against a namespace-registered table
or a plain dataset URI, so the spike runs against a real SeaweedFS Lance
table bucket and against a local fixture alike. Flag and env names
mirror weed-worker.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci: rust-vector-tests workflow

Build and test seaweed-vector in release on pushes and PRs touching it
or its path-dependency trees, mirroring rust-worker-tests.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: derive Serialize for the spike CLI's JSON output

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: --postfilter on the spike CLI

Track the Query field rename; the flag stays an explicit opt-out of
prefiltering for comparison runs.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: assert the pinned query's answers

The maintenance test passed even with zero pinned hits: an empty result
satisfies all() trivially. Assert the hit count and compare the pinned
answers against the reference on the pinned handle.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci: vector tests also watch plugin.proto

weed-vector-core path-depends on weed-lance-worker, which compiles
weed/pb/plugin.proto through seaweed-worker-core; a proto-only change
would skip these checks and could break this workspace.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: describe prints layout and coverage

The describe doc comment promised the vector layout and index coverage;
print both, and propagate count_rows errors instead of printing 0.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 11:48:46 -07:00
eda4b9efdd vector: ANN coverage introspection + prefilter (P0 phase 2) (#12097)
* vector: share the test dataset builder

The coverage tests need the same tempdir Lance datasets the query tests
build; move them into a cfg(test) helper module.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: prefilter the metadata filter

prefilter=false post-filters the top-K rows, which can return fewer than
k results and never sees unindexed rows beyond the nearest cut. Expose
the choice so the S3 Vectors layer can honour AWS filter semantics.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: index coverage introspection

coverage() unions each index's fragment bitmaps against the manifest's
fragment list to report which fragments a vector index covers, which it
has not reached, and how many rows the flat pass still has to scan.
Tests pin the behaviour the spike is for: rows appended after an index
build stay in the top-K, and a version-pinned dataset never sees the
next commit.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: default filtered queries to prefilter

postfilter=false is now the normal path: the metadata filter cuts the
eligible rows before ranking, so a query returns k hits whenever k
eligible rows exist. Lance's post-filter remains reachable through
Query::postfilter for comparison runs.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: intersect index bitmaps with the live manifest

A bitmap records fragments the index covered when built; a fragment the
manifest dropped afterwards stayed in the reported coverage.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: keep bitmap-less indices in coverage

An index whose metadata has no fragment bitmap was dropped from the
report entirely, indistinguishable from no index at all. Count its
segments and mark its coverage unknown instead.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: count live rows in unindexed coverage

physical_rows counts deleted rows and can be absent in the manifest;
sum FileFragment::count_rows for the unindexed fragments instead.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: error on a null key in a selected key column

* vector: compare filtered ANN and flat hits as sets

* vector: coverage reports the checked-out version

* vector: project _distance and _rowid explicitly

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: chrislusf <chris@seaweedfs.com>
2026-10-26 11:45:07 -07:00
Chris LuandDevin 7388d0d4fc vector: seaweed-vector workspace + flat/indexed top-K engine (P0 phase 1) (#12096)
* vector: scaffold the seaweed-vector workspace

Standalone cargo workspace for the vector query engine, mirroring the
seaweed-worker layout: own lockfile, same lint policy, path dependencies
across the two trees since there is no common root manifest.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: resolve a table's vector layout

VectorTable::resolve finds the vector column (explicit name, else the
column named vector, else the sole fixed-size float list), the optional
key column, and the metadata columns a query can project.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: flat and indexed top-k, key lookup

query::flat runs an exact scan (use_index(false)); query::ann lets Lance
split the query between index segments and a flat pass over fragments no
index covers yet, so rows written after the last index build stay
eligible. Both honour a metadata filter and return the raw _distance in
the query's metric.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: reject a non-utf8 or non-identifier key column

An explicit --key-column naming a non-UTF8 field made hits() silently
report row ids as keys, and get() interpolated the name into a SQL
filter verbatim. Require Utf8 at resolve and in hits(), and require a
plain identifier before building the IN predicate.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: fall back to row id on a null key

keys.value() on a null slot fabricates an empty-string key; a row with
no key reports its row id instead, matching the no-key-column case.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: quote the key column in the IN filter

A Utf8 key column named e.g. document-key made the predicate parse as
subtraction, and an identifier interpolated unquoted is injectable.
Backtick-quote it and double its inner backticks; double quotes are
string literals in the filter dialect, not identifiers.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* vector: project only the columns a hit needs

The knn projection pulled every metadata column — including other
vector columns — although Hit returns none of them. Filters still
evaluate off the scan path, so restrict the output to the key and the
scoring columns.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 10:13:05 -07:00
Chris LuandDevin 6f8f8e7079 admin: install the go.mod-pinned templ, not @latest (#12090)
* admin: install the go.mod-pinned templ, not @latest

install-templ fetched templ@latest, which now emits
templruntime.NewAttributeExpression - a symbol absent from the
runtime pinned in go.mod - so every fresh 'make' regenerated
uncompilable _templ.go files. Install the go.mod version and
reinstall when the binary on PATH reports a different one.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* admin: invoke templ from Go's install dir, not PATH

A templ binary earlier on PATH than GOBIN still shadowed the pinned
compiler after install-templ ran, so generate kept emitting code for
the wrong runtime. Resolve GOBIN (or GOPATH/bin) and call the pinned
binary by absolute path for install checks, generate, watch, and fmt.

* admin: regenerate templ output with the pinned v0.3.1070

The checked-in _templ.go files were stamped v0.3.1020, older than the
go.mod pin. Regenerate so the committed code matches the compiler the
runtime links against.

* admin: resolve templ under the first GOPATH entry

go install drops binaries in the first GOPATH element's bin, so a
multi-element GOPATH left TEMPL pointing at a path that does not exist.
Split on the OS list separator so Windows GOPATHs resolve too.

* admin: install pinned templ before fmt and pattern-rule generates

fmt and a direct %_templ.go rebuild invoked TEMPL without ensuring the
pinned binary exists; an order-only prerequisite keeps the check cheap
without forcing regeneration.

* admin: keep spaced GOPATH/templ paths intact in the Makefile

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 09:30:33 -07:00
6ebc055a94 master, volume, filer: start on a read-only mounted directory and serve existing data read-only (#12081)
* master, volume, filer: start on a read-only mounted directory and serve existing data read-only

A read-only mount was treated as writable (permission bits only), so every
service failed on its first write: the master panicked writing raft conf.tmp,
the filer exited opening the leveldb LOCK, and the volume server skipped every
volume while still offering the directory as free capacity.

- util.IsReadOnlyMount: access(W_OK) == EROFS.
- volume: on a read-only -dir take the existing O_RDONLY/noWriteOrDelete load,
  index .idx in memory when no .sdx exists, offer no free slots (same branches
  as isDiskSpaceLow), skip the vid stamp there.
- master: on a read-only -mdir run raft from a private copy and refuse new
  volume ids.
- filer: leveldb2/leveldb3 set their existing ReadOnly option.

* volume: skip read-only mounts when picking EC shard copy targets

A shard copy landing on a read-only mount fails at write time; offer
only writable locations like the other placement paths do.

* volume: mirror the read-only mount handling in the Rust volume server

The .dat open only fell back to read-only on EACCES, so a real read-only
mount (EROFS) still failed the load. The index side already degrades
once no_write_or_delete is set. Add is_read_only_mount via access(W_OK)
== EROFS, mark DiskLocation.read_only_mount, and mirror the Go checks:
no free slots, heartbeat max = used, no vid-stamp writes, no EC shard
copy targets, and a read-only index dir forces the volume read-only.

* volume: write vid stamps while only the index dir is read-only

* filer: skip the write-bit check when a leveldb store opens read-only

* filer: serve reads of buckets with no leveldb3 dir on a read-only store

* volume: derive a stable dir uuid when a read-only mount cannot store one

* master: keep the read-only raft copy across restarts so votes survive

* volume: index a missing .idx in memory on a read-only mount

* volume: release the .idx handle after an in-memory read-only load

* volume: mount EC shards read-only when their index dir is on a read-only mount

* volume: mark the index dir read-only before the tail repair opens .idx

* volume: write vid stamps while only the index dir is read-only (Rust)

* volume: derive a stable dir uuid and report no free slots on a read-only mount (Rust)

* volume: index a missing .idx in memory on a read-only mount (Rust)

* volume: refuse an EC copy whose shard owner is on a read-only disk

* master: key the read-only raft copy by the absolute -mdir

Two masters sharing the same relative -mdir text from different working
directories would have collided on one temp copy and shared raft state.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: mix device and host into the read-only dir uuid

Deriving the uuid from the path alone let independent servers at the
same mount point report one uuid, which RegisterUuids rejects. Hash in
the device id and hostname so restarts stay stable but disks differ.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: vic6996-web <320442181+vic6996-web@users.noreply.github.com>
Co-authored-by: user.email <chrislusf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 09:28:49 -07:00
dependabot[bot] 0214f9b34e build(deps): bump github.com/pkg/sftp from 1.13.11 to 1.13.12 (#12086)
Bumps [github.com/pkg/sftp](https://github.com/pkg/sftp) from 1.13.11 to 1.13.12.
- [Release notes](https://github.com/pkg/sftp/releases)
- [Commits](https://github.com/pkg/sftp/compare/v1.13.11...v1.13.12)

---
updated-dependencies:
- dependency-name: github.com/pkg/sftp
  dependency-version: 1.13.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:24:50 -07:00
dependabot[bot] b7d3c8a5a6 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azcore from 1.23.2 to 1.23.3 (#12087)
build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/azcore

Bumps [github.com/Azure/azure-sdk-for-go/sdk/azcore](https://github.com/Azure/azure-sdk-for-go) from 1.23.2 to 1.23.3.
- [Release notes](https://github.com/Azure/azure-sdk-for-go/releases)
- [Commits](https://github.com/Azure/azure-sdk-for-go/compare/sdk/azcore/v1.23.2...sdk/azcore/v1.23.3)

---
updated-dependencies:
- dependency-name: github.com/Azure/azure-sdk-for-go/sdk/azcore
  dependency-version: 1.23.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:24:36 -07:00
dependabot[bot] 74161edb7a build(deps): bump github.com/getsentry/sentry-go from 0.49.0 to 0.50.0 (#12089)
Bumps [github.com/getsentry/sentry-go](https://github.com/getsentry/sentry-go) from 0.49.0 to 0.50.0.
- [Release notes](https://github.com/getsentry/sentry-go/releases)
- [Changelog](https://github.com/getsentry/sentry-go/blob/master/CHANGELOG.md)
- [Commits](https://github.com/getsentry/sentry-go/compare/v0.49.0...v0.50.0)

---
updated-dependencies:
- dependency-name: github.com/getsentry/sentry-go
  dependency-version: 0.50.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:24:25 -07:00
dependabot[bot] 07cfe2d5e2 build(deps): bump github.com/redis/go-redis/v9 from 9.22.0 to 9.23.0 (#12088)
Bumps [github.com/redis/go-redis/v9](https://github.com/redis/go-redis) from 9.22.0 to 9.23.0.
- [Release notes](https://github.com/redis/go-redis/releases)
- [Changelog](https://github.com/redis/go-redis/blob/master/RELEASE-NOTES.md)
- [Commits](https://github.com/redis/go-redis/compare/v9.22.0...v9.23.0)

---
updated-dependencies:
- dependency-name: github.com/redis/go-redis/v9
  dependency-version: 9.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:24:09 -07:00
dependabot[bot] 692423d641 build(deps): bump github.com/ThreeDotsLabs/watermill from 1.5.2 to 1.5.3 (#12091)
Bumps [github.com/ThreeDotsLabs/watermill](https://github.com/ThreeDotsLabs/watermill) from 1.5.2 to 1.5.3.
- [Release notes](https://github.com/ThreeDotsLabs/watermill/releases)
- [Changelog](https://github.com/ThreeDotsLabs/watermill/blob/master/RELEASE-PROCEDURE.md)
- [Commits](https://github.com/ThreeDotsLabs/watermill/compare/v1.5.2...v1.5.3)

---
updated-dependencies:
- dependency-name: github.com/ThreeDotsLabs/watermill
  dependency-version: 1.5.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:23:51 -07:00
dependabot[bot] 2ffe61189f build(deps): bump actions/github-script from 7 to 9 (#12095)
Bumps [actions/github-script](https://github.com/actions/github-script) from 7 to 9.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v9)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-version: '9'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:23:32 -07:00
dependabot[bot] 41c33bdb21 build(deps): bump github/codeql-action from 4.39.0 to 4.39.1 (#12092)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.0 to 4.39.1.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v4.39.0...v4.39.1)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 4.39.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:20:41 -07:00
d010664634 build(deps): bump docker/login-action from 4.6.0 to 4.7.0 (#12094)
* build(deps): bump docker/login-action from 4.6.0 to 4.7.0

Bumps [docker/login-action](https://github.com/docker/login-action) from 4.6.0 to 4.7.0.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v4.6.0...v4.7.0)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* ci: correct stale version comments on SHA-pinned docker actions

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: user.email <chrislusf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 09:20:15 -07:00
dependabot[bot] 66e8211821 build(deps): bump actions/download-artifact from 7 to 8 (#12093)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 7 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-26 09:19:02 -07:00
a235473105 [Volume] Preserve request semantics in replica proxy reads (#12075)
* fix 12074

* volume: shuffle a copy of cached replica locations for proxy reads

LookupVolumeId serves cached location slices shared between lookups; shuffling in place races with concurrent proxied reads of the same volume.

* seaweed-volume: forward inbound method and surface lookup failure in proxy reads

Mirror the Go handler: proxy_request used to always send GET, turning a client HEAD into a replica download, and a failed master lookup returned 404 like missing data. Forward the inbound method and answer 500 for lookup failures in proxy mode.

* volume: keep master lookup error detail out of the proxy error response

* volume: bound the proxied-request wait in the method-preservation test

* seaweed-volume: answer 404 for missing volumes in proxy-mode lookups

Mirror Go's LookupVolumeId: a per-volume error in the master's lookup
reply (e.g. a missing volume) means "no locations" and answers 404
downstream, not a lookup failure that proxy mode answers 500.

* volume: guard nil lookup result in proxy path

A master response that omits the requested vid leaves
LookupVolumeId returning a nil *LookupResult with a nil error;
dereferencing it panics the read handler.

* seaweed-volume: answered lookup errors are missing data, not failures

A master reply carrying a per-volume error with HTTP 404 (volume not
found) now yields empty locations like Go's LookupResult, so proxy mode
answers 404. Other failure statuses such as 503 during master warmup
remain lookup failures that proxy mode answers 500.

* seaweed-volume: drop hop-by-hop headers from replica proxy reads

Go's inbound request drops Host, Content-Length and Transfer-Encoding
into dedicated fields, so its forwarded header set never carries them.
hyper keeps them; forwarding a client's Content-Length with no body
stalls the replica's read, and forwarding its Host misnames the target.

* volume: bound the proxy master lookup to the request context

* volume: drop hop-by-hop and Connection-nominated headers from proxy reads

* seaweed-volume: drop Connection-nominated headers from proxy reads

* volume: skip the proxy lookup error when the inbound request is gone

* volume: drop proxy-specific headers from replica proxy reads

* seaweed-volume: drop proxy-specific headers from replica proxy reads

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume: drop hop-by-hop headers from replica proxy responses

* seaweed-volume: drop hop-by-hop headers from replica proxy responses

* seaweed-volume: a failed lookup status without an error body is still a failure

* volume: do not re-proxy an already-proxied read for a missing volume

A proxied request that reaches a server which still lacks the volume was
looked up and forwarded again, so a stale location answer could bounce
the read between two servers until the client gave up. The Rust volume
server's proxy_missing_volume already returns 404 for proxied=true;
mirror it here.

* seaweed-volume: replace stale proxied params in the forwarded query

Go builds the proxied URL with query.Set(reqIsProxied), which replaces
every proxied param the client sent. Appending after a client-supplied
proxied=false left the replica's first-value lookup reading the stale
marker, defeating the loop guard.

---------

Co-authored-by: chrislusf <chrislusf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 08:13:34 -07:00
Chris LuandDevin dfd9ecab05 mount: resume metadata-log replay where a dropped stream stopped (#12079)
* pb: checkpoint metadata-log replay progress per settled entry

A chunk-mode subscriber's resume cursor only advanced after the whole
LogFileRefs batch drained, so a stream dropped mid-replay resubscribed
from the original stale position and re-read the same log files while
live traffic kept appending - under a flapping filer the replay window
never shrank, and each reconnect re-listed and re-fetched the same
backlog.

ReadLogFileRefs now reports every entry the merge has settled -
delivered or filter-skipped - and FollowMetadata checkpoints StartTsNs
on it, so a reconnect resumes where the previous stream stopped and the
backlog drains across restarts. The peer aggregator wires the same
progress into its resubscribe/offset position.

* pb: emit a replay checkpoint only after the merge passes its timestamp

Checkpointing an entry's timestamp the moment it settles could strand a
same-timestamp entry still queued on another filer's stream: resuming is
exclusive, so a reconnect would skip the unsettled half of the tie. The
merge now emits a timestamp only once a later entry proves every tied
entry was delivered (and once at clean EOF).

* pb+filer: never regress the replay cursor below the settled checkpoint

The drain's final assignment took the last settled entry's own timestamp,
which can lag the log position progressFn just checkpointed - a skewed or
legacy entry rewinds option.StartTsNs (and the peer's lastTsNs), so the next
drain or a resubscribe re-reads the settled prefix. Guard both assignments
so the cursor only moves forward.

* pb: cover the resubscribe path of replay checkpoints

A drain that aborts mid-replay leaves StartTsNs at the last checkpoint
the merge passed, and the next subscribe resumes there instead of
re-reading the whole ref set. The test drives the real
makeSubscribeMetadataFunc path: refs, a mid-batch apply failure, then a
resubscribe whose SinceNs must carry the checkpoint.

* pb: emit the tail replay checkpoint only for a settled timestamp

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 08:06:15 -07:00
0d721fccee fix(volume): keep preallocated growth above -volume.minFreeSpace (#12067)
* fix(volume): keep preallocated growth above -volume.minFreeSpace

When free space fell below -volume.minFreeSpace, every volume went
read-only and the master kept growing new volumes. With preallocation on,
each new volume reserved its full size, driving the disk further below the
floor (15 Oct incident: 66 empty volumes reserved about 1980 GiB).

Two causes, both in weed/storage/store.go:

- MaybeAdjustVolumeMax sized a disk's volume slots from raw free space, so
  space inside the floor was counted as available. It now counts only free
  space above the floor.
- addVolume trusted the once-a-minute low-disk flag. A preallocated volume
  is now refused when the disk is low now, or when its reservation would
  not fit above the floor. Volumes without preallocation, including merges
  that copy existing data, are not affected.

addVolume runs under a store-level lock, so two concurrent creates cannot
both pass the room check against the same free space.

* volume: mirror headroom guard in the rust store

find_free_location only trusted the once-a-probe is_disk_space_low flag,
so a burst of preallocated creates could still run the disk under
-volume.minFreeSpace between probes, and maybe_adjust_volume_max sized
slots from raw free space. Adds MinFreeSpace::is_low/available_space to
match Go and applies both checks the same way. store.write() already
serializes add_volume, so no extra lock is needed.

* volume: read rust headroom tests from a fake disk

The floor arithmetic used a live free-space reading, so unrelated disk
activity could flip a test between pass and fail. Store.disk_stats_of is
now the same seam Go uses (diskStatusOf): the growth-loop and floor tests
run against a controlled disk, mirroring the Go suite one for one.

* volume: hold back create metadata from the headroom check

An exact-fit preallocation left free space exactly at the floor, so the
.vif and .idx writes that follow a create could dip under it and get the
location flagged read-only at the next probe. Reserve room for .vif on
the data filesystem, and for .idx growth only when dir_idx shares it.

* volume: mirror the metadata allowance in the rust store

Same rule as the Go side: charge .vif against the checked filesystem and
.idx only when dir_idx shares it, and grow the exact-fit test's fake
disk by the per-create cost.

* volume: skip the reservation check where create cannot preallocate

* volume: mirror the platform preallocation gate in the rust store

* volume.copy: count the preallocation reservation in the destination space check

The copy path picked a location with room for the copied .dat, then reserved
the master's full volume size limit on it. A volume smaller than the limit
could land on a disk whose free space above -volume.minFreeSpace fit the
copy but not the reservation, driving the disk under the floor the same way
the growth loop did.

Fetch the preallocation setting before choosing the location and require
room for the reservation itself, only where CreateVolumeFile actually
reserves blocks.

* seaweed-volume: store min-free-space-adjusted available space like Go

Go's DiskLocation.AvailableSpace holds free space above the
-volume.minFreeSpace floor; the Rust probe cached raw free instead, so the
VolumeCopy location check could accept a disk already inside the floor.
Store the same adjusted figure and cover it with a test.

* seaweed-volume: reserve the copied .dat like Go's CreateVolumeFile

VolumeCopy called set_len for the reservation, which only grows a sparse
file — no blocks are held, so a disk with room for the copied bytes but
not the full reservation only fails mid-copy. preallocate_file fallocates
KEEP_SIZE on Linux like Go, reserving the blocks up front; off Linux it
is a no-op, matching PREALLOCATE_SUPPORTED.

* seaweed-volume: charge a copy's destination pick for the .dat reservation

Go's VolumeCopy now sizes its free-location check against the master's
volume size limit when the platform preallocates, not just the copied
bytes. The Rust pick only measured the copied bytes, so a destination
could accept a copy whose reservation then dips under the floor. The
config fetch moves ahead of the pick (same order as Go) and feeds both
the space check and the reservation itself.

* volume.copy: charge the picked location's free space under volumeCreateLock

The copy path picked a destination off the once-a-minute AvailableSpace
probe and released the decision long before the .dat reservation landed.
Two copies could pass the same cached headroom and together drive the disk
under -volume.minFreeSpace.

ReserveFreeLocation serializes the pick under volumeCreateLock, verifies
the disk still has live room for the reservation, and charges it against
the location's cached free space until the next probe refreshes it.

* seaweed-volume: mirror the copy pick's live-check and headroom charge

Go's VolumeCopy now picks through Store.ReserveFreeLocation: live disk
stats under the store write lock, then the reservation charged against the
location's cached free space. The Rust plan_copy_destination gains the
same store.reserve_free_location so two copies cannot spend the same
headroom before the first .dat reservation lands.

* volume.copy: saturate the free-space charge against a live-space drop

The two statfs reads bracketing a pick can race a large external write; a
plain subtraction would underflow and leave the location looking roomy
until the next probe.

* volume.copy: release the headroom reservation when a copy does not land

ReserveFreeLocation charges the picked location's cached free space, but
a failed copy never returned it, so the headroom stayed booked until the
next disk-space probe and blocked retries. ReleaseFreeLocation refunds
the charge; the copy's cleanup defer now registers with the reservation
so every failure path (existing-replica delete, .note write, stream send)
releases it, including the post-transfer mount/validate failures covered
by the outer defer.

* seaweed-volume: mirror the copy headroom release on failed copies

release_free_location refunds reserve_free_location's charge. The copy
returns it when the plan's existing-replica delete fails, when the .note
write fails, and in cleanup_failed_copy, so a failed copy stops holding
the headroom until the next disk-space probe.

* volume.copy: keep pending copy headroom out of probe readings

ReleaseFreeLocation refunded the reservation into AvailableSpace even when
a CheckDiskSpace probe had already rebased the cache on live stats — the
probe's reading still shows the in-flight copy's bytes as free, so the
refund double-counted headroom and two copies could spend the same space,
driving the disk under -volume.minFreeSpace.

Track the outstanding charge in DiskLocation.ReservedSpace instead: probes
subtract it so they cannot re-spend it, a failed copy removes only its own
charge, and a landed copy commits it — the charge and the new usage cancel
out. hasRoomForNewVolume respects pending headroom too, so a preallocating
create cannot overrun an in-flight copy.

* seaweed-volume: mirror pending copy headroom across disk probes

reserved_space tracks the in-flight copy's charge separately from the
cached free space: check_disk_space subtracts it, release removes only the
failed copy's charge, a landed copy commits it, and has_room_for_new_volume
respects it — matching the Go side.

* volume.copy: settle a copy's headroom as its bytes land on disk

The pending charge held the copy's full reservation until commit, but
written and fallocated bytes already show up in statfs, so the live-space
check counted them twice. A slow copy could then block other copies and
volume growth despite free space above -volume.minFreeSpace.

Settle the charge instead: commit the bytes CreateVolumeFile actually
reserved (a failed fallocate leaves nothing committed), then settle each
file's write progress as it lands. The failure paths now release only the
unsettled remainder; allocatedSize is exported for the .dat's st_blocks.

* seaweed-volume: mirror copy headroom settling as bytes land

reserved_space keeps only the promised bytes statfs cannot see yet:
preallocate_dat settles whatever blocks the filesystem actually reserved
(0 when fallocate cannot), each copied file's progress settles the rest as
it lands, and a failed copy releases only the unsettled remainder —
matching the Go side.

* volume.copy: release a failed copy's headroom charge only once

Both defers fired on the same in-closure error: the inner released the
unsettled charge and the outer released it again, driving ReservedSpace
negative (an atomic.Uint64 underflow) and inflating AvailableSpace —
the location would then fail every later headroom check, or worse,
pass them with fabricated space. Zero the charge once it is released;
the Rust mirror already releases via swap(0) for the same reason.

* volume.copy: write into the preallocated .dat instead of staging over it

The .dat stream staged into .copying and renamed over the file
CreateVolumeFile had just fallocated, so the copy's transient footprint
was preallocate+dat — more than the reservation the pick just checked —
and the reservation itself was discarded at rename. Writing in place
reuses the fallocated extent, keeps the peak at the reserved maximum,
and leaves the copied volume preallocated like a created one.

* seaweed-volume: mirror the in-place write into the preallocated .dat

The .dat copy opened the just-fallocated file with truncate, freeing its
blocks at open and spending the headroom again as the stream re-grew it.
Append mode preserves them, matching the Go side.

---------

Co-authored-by: chrislusf <chrislusf@gmail.com>
Co-authored-by: user.email <chrislusf@users.noreply.github.com>
2026-10-26 08:03:25 -07:00
b5af82409f fix: volume.fsck -volumeId purges live chunks referenced from outside the volume's bucket (#12076)
* fix: volume.fsck -volumeId purges live chunks referenced from outside the volume's bucket

-volumeId narrowed the filer read to <bucketsPath>/<collection> when
the selected volumes shared one bucketed collection (#9347). A filer
started with -collection, or an fs.configure rule, stores files from
any path in that collection, so the narrowed read misses their
references and reports live chunks as orphans; with
-reallyDeleteFromVolume they are deleted. #11794 already made
-collection read from the root for this reason. Do the same for
-volumeId: the flag keeps selecting which volumes are checked and
purged, and the filer is always read from "/".

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

* test: volume.fsck keeps chunks referenced outside the volume's bucket

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: user.email <chrislusf@users.noreply.github.com>
2026-10-26 07:58:43 -07:00
Nguyễn Lộc Phúcanduser.email 937633a77d iceberg: fix CREATE TABLE rejecting a partition on the first column (#12072)
* iceberg: fix CREATE TABLE rejecting a partition on the first column

Apache Spark number the columns of a new
table from 0 and leave assigning fresh IDs to the catalog, so a table
partitioned or sorted by its first column arrives with source-id 0. The
create-table request decoded its partition spec and write order into
iceberg-go's bound PartitionSpec and SortOrder, which require positive
source IDs, so every such CREATE TABLE, and CTAS through stage-create,
was refused with "Malformed request: Invalid request body".

Decode both as iceberg.UnboundPartitionSpec and table.UnboundSortOrder,
as iceberg-go documents for catalog create-table requests;
newTableMetadata already resolves the placeholders through the request
schema by name and assigns fresh IDs. A spec or order that does not
resolve against the schema is now answered with 400 instead of 500, and
the decode error message carries the underlying reason.

Tests check that Spark's request bodies resolve to the same metadata as
1-based placeholders, that the handler accepts them, that unresolvable
source IDs get 400, and add a Spark integration test that partitions by
the first column.

* iceberg: gofmt the create-table source-id tests

---------

Co-authored-by: user.email <chrislusf@users.noreply.github.com>
2026-10-26 07:54:10 -07:00
a6be3c89c2 filer: support nanosecond timestamps for conditional delete (#11339) (#12071)
* filer: support nanosecond timestamps for conditional delete (#11339)

* shell: fs.verify prune carries the entry mtime in nanoseconds

IfNotModifiedAfter now resolves to sub-second precision on the filer,
so pass the looked-up mtime_ns along with mtime; the re-lookup check
catches same-second rewrites that share the second, and the test mock
mirrors the filer's seconds/nanoseconds cutoff.

* shell: volume.fsck guards empty-directory deletes with mtime nanoseconds

The looked-up mtime_ns joins the seconds in IfNotModifiedAfter so a
directory rewritten within the same second is not dropped; the stub
filer mirrors the filer's scale heuristic and the race fixtures use a
realistic mtime so the nanosecond branch engages.

* filer: cover the seconds guard and equality boundary

Test second-resolution cutoffs on both sides of the entry's second and
the exact-equality nanosecond guard that still deletes.

* filer: compare the nanosecond guard as a time, not UnixNano

UnixNano overflows for mtimes outside 1678-2262, letting a far-future
entry slip past the guard; time.After compares exactly at every epoch.
The seconds branch keeps Unix() so a same-second cutoff still deletes.

* filer_pb: add explicit if_not_modified_after_ns to DeleteEntryRequest

* filer: prefer explicit nanoseconds guard, keep if_not_modified_after as seconds

* shell: send seconds and nanoseconds delete cutoffs, skip unexpressible mtimes

* filer: merge conditional-delete guards into one nanosecond cutoff

DeleteEntryMetaAndData carried both the seconds and nanoseconds guards
even though the precedence between them is fixed, so every caller passed
a dead parameter. The gRPC handler now folds if_not_modified_after into
nanoseconds at the boundary, where (sec+1)*1e9-1 keeps the whole-second
cutoff exact, and the filer takes a single ifNotModifiedAfterNs.

* filer: hold the conditional-delete cutoff as a time, not int64 nanoseconds

A seconds-only guard at or past year 2262 saturated to MaxInt64
nanoseconds (~2262), so a delete whose cutoff matched a far-future mtime
was skipped while the request still reported success, and any entry
between 2262 and the real cutoff survived pruning. The merged cutoff is
now a time.Time, where a whole-second guard maps to the last nanosecond
of its second for any int64 second.

---------

Co-authored-by: user.email <chrislusf@users.noreply.github.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-10-26 07:51:33 -07:00
b85281f0da s3: group ListMultipartUploads by delimiter into CommonPrefixes (#12069)
* s3: group ListMultipartUploads by delimiter into CommonPrefixes

The delimiter was echoed but ignored, so every upload was listed. Keys
that continue past the delimiter after the prefix are now listed once as
a common prefix, counted toward max-uploads like an upload.

* s3: bound tracked multipart common prefixes to the page

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* s3: omit upload id marker when a page ends on a common prefix

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: user.email <chrislusf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 06:10:09 -07:00
b7b571d469 webdav: copy a file onto a collection URL without losing the collection (#12068)
* webdav: copy a file onto a collection URL without losing the collection

An overwriting COPY of a file to dir/ removed dir, then OpenFile refused
the name ending in / and the request failed with 403, leaving neither.
Drop the trailing slash from the destination when the source is a file.

* webdav: cover file-over-collection COPY through the real handler

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* webdav: keep a root destination out of the slash trim

A file COPY or MOVE onto / would rewrite the Destination to an empty
path, turning the existing refusal into x/net's bad-gateway error; leave
the root untouched so RemoveAll refuses it as before.

---------

Co-authored-by: user.email <chrislusf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-26 06:08:24 -07:00
github-actions[bot] 96f310dec8 docs: regenerate star history chart 2026-10-26 08:02:43 +00:00
Chris Lu ffa87c25fd ci: fix aarch64/amd64 musl rust builds on ubuntu-24.04 (#12070)
The 24.04 bump broke build-rust-binaries: aws-lc-sys C objects compile against noble's glibc 2.39 headers, which redirect sscanf/strtol to the C23 __isoc23_* variants musl does not provide, failing the link.

Same fix as the enterprise build on seaweedfs/artifactory:
- arm64: keep aarch64-linux-gnu-gcc, link a tiny forwarding shim that
  resolves __isoc23_sscanf/__isoc23_strtol to musl's vsscanf/strtol.
- amd64: point CC at musl-gcc so C deps compile against musl headers.
2026-10-25 21:09:37 -07:00
github-actions[bot] 153ab668c9 4.51 2026-10-25 19:39:07 +00:00
Chris Lu 6dd6ad512c iam/oidc: drop single-use web-identity tokens and the jti replay cache (#12065)
* iam/oidc: drop single-use web-identity tokens and the jti replay cache

Reverts the single-use semantics added in #11936 (and the #12017
refactor): AssumeRoleWithWebIdentity consumed each web-identity
token's jti into a bounded replay cache, so a second exchange of the
same token was rejected until exp + skew.

AWS STS accepts a web-identity token repeatedly until it expires,
and Kubernetes workload identity depends on that: the kubelet keeps
a projected ServiceAccount token until ~80% of its lifetime, so pod
restarts, co-located containers sharing the token file, repeated CLI
invocations, and pre-rotation SDK refreshes all re-present the same
jti and were refused on 4.50.

The replay machinery also carried a real maintenance cost — a
bounded concurrent cache, fingerprint-keyed entries for jti-less
tokens, adopt/merge handoffs so provider rebuilds could not reopen
consumed tokens, and provider-reuse bookkeeping in the refresh path
that existed only to preserve that state. Removing it restores AWS
semantics and deletes the whole apparatus.

Refs #12063. Alternative to the per-provider opt-out in #12064.

* iam: reuse unchanged OIDC providers on refresh

refreshOIDCProvidersFrom rebuilt every managed provider on any store
change, so an unrelated write discarded each provider's JWKS cache and
an unreachable issuer could then fail exchanges the cached keys would
have allowed. Keep a per-record provider cache keyed on the record
content fingerprint and only rebuild when the record changes.

* iam/oidc: require exp in ValidateToken

Dropping the single-use check also removed the implicit bound on
expiry-less tokens: a signed web-identity token without exp could
mint STS sessions indefinitely. Require the exp claim, matching AWS
AssumeRoleWithWebIdentity which rejects tokens without one.

* iam/oidc: bound idle connections on the provider transport

A provider replaced on refresh drops its http.Transport without a
close; give it an IdleConnTimeout so pooled connections and their
goroutines cannot linger.

* s3api: cover web-identity token reuse over HTTP

Sign one token and exchange that exact string twice, directly covering
the Kubernetes projected-token reuse this change restores.

* test(iam): refresh reuses an unchanged record's provider

Covers the provider-reuse cache: an unrelated record's refresh keeps a
provider's JWKS state, a changed record rebuilds it.
2026-10-25 12:04:59 -07:00
515380c349 s3: answer GET and HEAD of a delete marker as S3 does (#12051)
* s3: answer GET and HEAD of a delete marker as S3 does

A delete marker as the current version now returns 404 NoSuchKey with
x-amz-delete-marker: true and the marker's x-amz-version-id. Asking for the
marker by versionId returns 405 MethodNotAllowed with the same headers and
Last-Modified, instead of 404 NoSuchKey.

* s3: check the tag-conditioned read grant before answering a delete marker

The marker branch returned before the entry-based policy recheck the rest
of the read path performs, so an s3:ExistingObjectTag-conditioned Deny did
not apply to the delete-marker response and its version headers.

* s3: send Allow: DELETE with the delete-marker 405

RFC 9110 15.5.6 requires a 405 answer to list the methods the resource
supports; S3 sends allow: DELETE for a delete marker named by versionId.

* s3: keep delete-marker headers on conditional-read misses

If-Match or If-Unmodified-Since against a current delete marker short-
circuited to a bare NoSuchKey. Carry the resolved marker through the
conditional result so the 404 keeps x-amz-delete-marker and
x-amz-version-id, matching the unconditional read.

* s3: exercise delete-marker responses through GET and HEAD handlers

* s3: read marker version id from the entry before the caller's guess

A delete marker written outside the normal PUT path can miss the
version-id attribute while the v_<id> file name still names it; the
new x-amz-version-id header would then report "null". Reuse
versionIdFromEntry so both the handler and conditional-miss paths
emit the real id.

* s3: answer 405 for versionId=null on a suspended-versioning marker

The null marker lives in .versions while getSpecificObjectVersion only
checks the plain path, so GET/HEAD ?versionId=null answered
NoSuchVersion. On that miss, look up the null marker and answer it
like any other marker named by versionId.

* s3: propagate null-marker lookup failures instead of answering 404

A transient filer error reading .versions/v_null was swallowed as
"no marker", so GET/HEAD answered NoSuchVersion for a live read
failure. NotFound and absent entries still mean no marker; anything
else is InternalError now.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
Co-authored-by: chrislusf <chrislusf@users.noreply.github.com>
2026-10-25 12:02:19 -07:00
Chris LuandDevin 9620e7ebfe filer: auto-enable per-path commit records when a peer has its own store (#12062)
* filer: enable per-path commit records only when a peer has its own store

Since seaweedfs#11698 every metadata change writes a per-path commit
record into the filer store (an MpTs key, plus an MpDl key on deletes),
and the records stay after the path is deleted. They order the events a
filer replays from peer filers that keep their own store, since replay
only runs when peerSignature != f.Signature.

Filers that all share one store (one Redis, MySQL, TiKV, ...) never
replay each other's events, so the records are never read, yet each
change still costs one or two extra store writes and the key count grows
with every path ever changed — unbounded growth for in-memory stores.

This turns the records off by default and latches them on the first time
a peer reports a different store signature — no option needed. The latch
is persisted in the store (MpRep) so it survives restarts and converges
filers sharing a store even before they discover the peer themselves.
While off, a filer keeps an MpOff marker so enabling later bumps the
records' generation (MpGen, folded into each record key) past the
unrecorded window: a record older than a change made while off cannot
let an older replayed peer event win. Ordering for unrecorded changes
falls back to the entry's mtime, the same as entries written before the
records existed.

Supersedes the manual option approach in seaweedfs#12060.

* filer: keep delete tombstones while records off, harden enable path

Review on the first commit:

- A delete committed while the records were off left no entry and no
  usable tombstone: after enabling, an older replayed create could
  resurrect the path. Deletes and rename sources are now always recorded
  under the generation-0 MpDl key — they are never fenced by a
  generation bump, and they cannot go stale because every delete is
  recorded. Creates/updates still write nothing while off.

- bumpPathCommitGen could regress MpGen under concurrent bumpers on a
  shared store. It now loops: each pass writes only a generation higher
  than any it has seen, so concurrent bumps converge upward.

- doSubscribeToOneFiler proceeded into replay when
  enablePathCommitRecords failed, running the whole session without
  ordering. It now aborts the subscribe so the reconnect retries with
  the records on.

* filer: bind pending commit-record repairs to their generation

A failed MpTs write kept in metaTsPending could land after a shared-store
generation bump, writing a pre-bump timestamp as a current-generation
record and overriding newer unrecorded state. Each pending change record
now carries the generation it failed under: repairs write it only while
that generation is current, and ordering reads ignore it otherwise.
Pending delete records need no binding — MpDl keys are never fenced.

* filer: never move the local records' generation backward

The converge loop in bumpPathCommitGen seeded from zero and both it and
syncPathCommitGen stored unconditionally: a stale writer could leave the
stored generation below what this filer already adopted, and the next
sync or bump then walked the local value back — orphaning records it
wrote under the higher generation. The bump now seeds from the local
generation and every store only moves it forward.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: name a records generation after the off marker it consumes

Two filers consuming the same off marker each counted one past the
stored generation, so the second could store N+2 after the first
stored N+1 and write records under a key the other could not read
until the next check. The bump now takes the marker's own timestamp —
filers racing on one marker land on one value — a marker older than
the stored generation is cleaned as a leftover, and a stored value
that already passed the bump is adopted instead of counted past. A
newly enabling filer whose marker was already consumed names its own
off window with the current time, so its unrecorded period is still
fenced.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: tell a fresh off marker from one the generation already consumed

A marker whose timestamp reads at or below the stored generation was
dropped as leftover, but a new off period can also read that old — the
off filer's clock lagging, or a host clock moving back — and dropping
it kept records from before that period live, so stale replay could
win.

The stored generation now names the marker it was bumped for: a marker
the store still shows is consumed unless it is that one, however old
it reads, and only the consumed marker itself is cleared without a
bump. The generation trails in the value, so a whole-slice read still
yields it on stores written before the pair was stored. Enabling
fences the filer's own off window with the current time instead of a
marker a sharer may already have consumed.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: cover racing off-marker consumers settling on one generation

* filer: adopt the stored generation, not the consumed marker it names

A filer syncing with no off marker present read the value's first field —
the consumed marker's timestamp — so a restart after a lagging-clock off
period under-counted the generation and kept records the bump dropped.

* filer: re-check the off marker before consuming it

A sync whose marker read ran behind a later off period's consume cycle
still bumped for its stale read: the stored generation already covered a
different marker, so the bump overwrote the consumed name, counted the
generation past records a newer consumption meant to keep, and cleared
whatever marker was live by then. Each pass now re-reads the marker and
only bumps or clears while it is still the one the pass saw.

* filer: keep a failed generation read from resetting the records' generation

The final generation read ignored errors and then stored whatever gen
held — possibly zero — so a transient store failure could hide records
the current generation wrote. Unexpected read errors now return before
the local generation changes.

Also cover a sync whose marker read runs behind another consumer's
delete: it must adopt the stored generation, not bump for the stale read.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: fail a bump that cannot verify the stored generation

A generation read that failed mid-bump was treated as absent: the
write could land below a generation a racing bumper had stored, or
re-store a marker that bumper had already consumed. Read failures
now abort the pass like every other store error on the path.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: cover generation reads that fail instead of returning a value

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* filer: carry the commit timestamp on the entry itself

The per-path MpTs record only exists because a commit timestamp had
nowhere else to live. Stamping commit_ts_ns on the entry before its
store write - and reusing that stamp as the emitted event's TsNs -
makes the entry its own commit record: replay and bootstrap traversal
order on it with zero extra writes for creates and updates.

Deletes still need a durable key since a removed entry cannot carry a
timestamp, so MpDl tombstones stay (one write per delete, growth
bounded by delete history). Entries predating the field fall back to
mtime, matching what peers and old records already assume.

This replaces the MpTs/MpOff/MpGen/MpRep machinery entirely: shared-
store filers write nothing extra, and dedicated-store replication
keeps last-writer-wins ordering plus tombstone coverage for deletes
and ancestor drops.

* filer: keep a directory update replay from tombstoning its subtree

A same-path update wrote a delete record before the delete-and-reinsert,
so a directory metadata change read as a subtree delete: a later peer
event for a child older than the update was then skipped even though
nobody deleted the children, leaving files missing on this filer. Only
file updates take the tombstone now — the re-inserted directory entry's
own commit stamp orders the path itself.

* filer: order unstamped entries by their recorded commit before mtime

Entries written before stamping existed have no CommitTsNs, so the
ordering check fell back to the client-settable mtime and dropped the
MpTs record those versions wrote: an entry committed at event time 300
with mtime 100 lost to a delayed peer event at 200 after upgrade. Read
the legacy record for unstamped entries in localCommitTsNs, CommitTsNs,
and the traverse stamp (which also stopped falling back to mtime,
regressing entry_ts_ns to 0).

* filer: release queued rename event stamps when the rename fails

Each moved entry carried an in-flight stamp its queued event would
adopt at emit time. When the move succeeded but a later child move or
the commit failed, the handler rolled back without emitting the queued
events or releasing their stamps, pinning the delivered and flushed
watermarks below the aborted rename forever. Release every queued
stamp on both failure exits in both rename handlers.

* filer: apply a directory update replay with an in-place upsert

Deleting the stored entry before inserting its replacement left a
window where the directory had no entry and no ordering record — a
tombstone cannot stand in for it without reading as a subtree delete
that suppresses the children's own records. A stale peer event accepted
in that gap could replay an older update or delete and sweep the
directory's children. Upsert the replacement instead: the entry keeps
its recorded commit order across the whole update, and a directory has
no chunks or hard links for a delete to release.

* filer: update an existing directory entry on replay instead of upserting

InsertEntry is not an upsert on SQL stores configured without upsert
support — PostgreSQL with enableUpsert=false issues a plain INSERT and
its duplicate-key error does not match the MySQL-only fallback, so a
replay updating a present directory failed on every retry. Pick
UpdateEntry when the entry exists and InsertEntry when it is absent;
UpdateEntry touches no row that is not there.

* filer: detect a shared-store delete racing a replayed directory update

UpdateEntry reports success even when the row was deleted between the
find and the update — the UPDATE changes zero rows and the replayed
change is dropped while the subscription offset advances. Re-read the
entry after the update and retry the write, re-checking the recorded
commit order each pass so a newer peer change wins instead of being
resurrected over.

* filer: declare commit_ts_ns in field-number order

Field 6 sits between extended and hard_link_id; the declaration now
reads in the same order. Wire format unchanged. Also syncs the Java
client's checked-in copy of filer.proto, which the pb Makefile copies
on gen.

* filer: option to skip delete tombstones entirely

filer.options.deleteTombstones=false stops writing MpDl records on
deletes - a single filer or shared-store cluster never replays peer
events, so the tombstones are dead weight. The tradeoff is explicit:
if a dedicated-store peer does replicate, a stale event can resurrect
a deleted path.

* filer: drop delete tombstones entirely

Deletes no longer write MpDl records, and the pending-repair machinery
they needed is gone with them: per-mutation metadata overhead is now
zero for every store topology. Ordering information lives only on the
entry itself via commit_ts_ns.

The accepted tradeoff: a dedicated-store peer replaying an event older
than a delete can resurrect the path, and a kept directory no longer
fences stale child creates. Recorded tombstones and MpTs records left
by older builds are still read, so upgrades keep the protections they
already have.

* filer: stop reading legacy per-path records too

Drops the MpTs/MpDl read path along with the writes: meta_path_ts.go
keeps only the entry-field readers (CommitTsNs, EntryCommitTsNs,
localCommitTsNs). Entries written before stamping existed fall back to
mtime, and tombstones or commit records older builds left behind no
longer fence replayed events.

* filer: trim commit timestamp comments

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 11:37:06 -07:00
Chris Lu 53834117a6 mini: lift the post-mint allocation hold on first inventory report (#12061)
* mini: lift the post-mint allocation hold on first inventory report

DeferAllocation armed a fixed warmup window whenever the leader minted a
fresh topology id, so the first write on a brand-new weed mini blocked
for the whole window even though no prior cluster state could exist.
The window still has to cover a rebuilt master's veteran servers, which
report on their first post-reconnect heartbeat.

Mini has exactly one possible reporter — the embedded volume server,
whose first heartbeat carries the full inventory — so hold allocation
only until that report is applied. The bound raise and topology-id
freeze checks run while the heartbeat is processed, so a wiped master
state still raises the bound or trips the freeze before the hold lifts.

Standalone weed master and weed server keep the fixed window: volume
servers outside the process can still be on their way.

* master: apply queued topology-id reports before opening the allocation gate

SetTopologyInitPending(false) cleared the pending flag before replaying
topology ids stashed while the local id was still being minted. A
NextVolumeId landing in the drain window saw no gate and no freeze yet.
The post-mint allocation hold used to cover the gap by delaying the
winner past the freeze; once the hold can release on first inventory,
the gate must stay closed until the queued checks have run.

* mini: gate the first-report release on single-master mode

releaseAllocOnFirstReport assumes the embedded volume server is the only
possible reporter of prior cluster state. A mini started with
-master.peers joins other masters, whose own volume servers can still be
on their way when the first report lands, so keep the regular
quiet-pulse hold there.

* master: check reported topology id on empty full reports

A HasNoVolumes heartbeat carries the same LastSeenTopologyId a populated
list does, but the mismatch freeze only ran for non-empty reports. An
EC-only veteran could therefore release the post-mint allocation hold
through NoteInventoryApplied while its stale topology id never reached
CheckReportedTopologyId.

* master: drain the topology-id stash inside the init-gate lock

CheckReportedTopologyId only held reportedTopologyIdsLock while stashing,
so a report in flight during SetTopologyInitPending(false) could land its
freeze after topologyInitPending cleared, letting a NextVolumeId slip
through the gap. The whole check now runs under the lock, and the gate is
released inside the same critical section as the drain.

* mini, master: pin and enforce the single volume-server reporter

isSingleMasterMode only checks master peers; SendHeartbeat still accepted
any volume server, so a late foreign report could carry prior cluster
state after the first-report release dropped the hold. Mini now pins the
embedded volume server's address and the master refuses registration from
any other reporter while ReleaseAllocOnFirstReport is set.

* master: admit the volume-server reporter before applying heartbeat state

* test: cover SendHeartbeat admission ordering

A refused reporter must not freeze growth or raise the id bound, and the
pinned reporter's stale topology id still must.

* mini: re-derive the single-reporter release on every run

The package-level master options survive in-process reruns, so a
multi-master mini following a single-master one must not inherit the
first-report release or a stale reporter pin.

* master: admit addressless first heartbeats under the reporter pin

An unregistered heartbeat with no Ip skipped the single-reporter
admission check but still reached the seen-bound raise and the
topology-id freeze before the delta-heartbeat skip. Admission now runs
for every unregistered heartbeat; an empty address can never equal the
pin.
2026-10-25 09:25:39 -07:00
Chris LuandDevin 88b91cccba command: no extra localhost listener when -ip.bind is specified (#12055)
* util: add listenOnLocalhost parameter to NewIpAndLocalListeners

Nil keeps the current behavior of also binding localhost when the host
is a specific address; all callers pass nil for now.

* command: add -ip.bind.localhost flag to opt out of the extra localhost listener

Binding a command to a specific -ip.bind address also opened a second
listener on localhost for every port, with no way to turn it off. Each
command that calls NewIpAndLocalListeners (master, master.follower,
filer, s3, iam, volume, sftp, mq.broker, mq.agent) now accepts
-ip.bind.localhost=false to bind only the requested address. Embedded
services get prefixed flags (s3.ip.bind.localhost, sftp.ip.bind.localhost,
iam.ip.bind.localhost), and the command-level flag also disables them so
a single switch turns off every extra listener the command opens.

* mini: only require all-interface port availability while the loopback listener is on

With -ip.bind.localhost=false each service binds just -ip.bind, so a port
held on another address no longer collides; the all-interface precheck
would reject or relocate usable ports. WebDAV, the Admin UI, and the
Admin worker gRPC (which binds -admin.worker.ip, not -ip.bind) never open
a loopback companion listener, so their checks now use the address they
actually bind.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* mq.broker: bind the gRPC listener to -ip.bind instead of all interfaces

The listener used an empty host so -ip was ignored for binding and the
localhost companion was never created, leaving -ip.bind.localhost with
nothing to control. Give the broker the same -ip/-ip.bind pair the other
servers use; embedded mode binds to -ip.bind like its peers.

* server: add -sftp.ip.bind.localhost and -iam.ip.bind.localhost switches

weed filer already exposes the prefixed opt-outs for its embedded sftp
and iam; give weed server the same pair so each extra listener can be
disabled individually while -ip.bind.localhost=false still turns them
all off.

* mq.broker: keep the default all-interface bind unless localhost is off

An unset -ip.bind used to mean the standalone broker listened on every
interface; defaulting it to -ip silently cut off multi-homed clients. Only
fall back to -ip when -ip.bind.localhost=false, where a specific bind is
needed for the opt-out to take effect.

* mini: validate the Admin HTTP port on the address it will bind

The port check always used -ip.bind while startMiniAdminWithWorker falls
back to loopback when Admin has no credential, so a loopback-held port
passed validation and killed the admin at startup.

* mq.broker: keep the all-interface default bind when -ip.bind is unset

-ip only becomes the fallback once -ip.bind.localhost=false needs a
specific address for the listener.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* mini: validate the Admin HTTP port on its effective bind IP

When the Admin listener falls back to loopback (no credential or mTLS
configured), the pre-flight port check now probes that same address
instead of -ip.bind.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* util: keep NewIpAndLocalListeners source-compatible for 3-arg callers

* command: drop the -ip.bind.localhost flag; an explicit -ip.bind drops the extra listener

Instead of an opt-out flag, the loopback companion listener now simply
follows whether the bind address was chosen: it is created only while
-ip.bind is unset and the bind address falls back to -ip. Passing
-ip.bind=<addr> binds each port to exactly that address.

Each service options struct carries a listenOnLocalhost *bool that
embedders (weed server, weed mini, embedded s3/sftp/iam in weed filer)
set from the parent's -ip.bind state, captured before the bind flag is
repointed or filled in by the -ip fallback; standalone commands derive
it from their own flag before the fallback runs.

iam and mq.agent gain a real -ip.bind flag so they have a way to pin a
single address. mq.broker keeps its new -ip.bind flag but drops the
-ip.bind.localhost fallback hack: empty still listens on all interfaces.

* server: default embedded mq.agent brokers to the broker's bind address

With an explicit -ip.bind the embedded broker no longer listens on
localhost, so an unset -mq.agent.brokers defaulting to localhost:17777
could not reach it. Default to <serverBindIp>:<mq.broker.port> (the
address the embedded broker binds), falling back to localhost when the
bind address is a wildcard. An explicit -mq.agent.brokers still wins.

Also fix the NewIpAndLocalListeners skip message to say localhost.

* server: bind embedded mq.agent to serverBindIp

The embedded agent's ipBind was never set, so startQueueAgent fell back
to the advertised -ip address and an explicit -ip.bind did not pin the
agent listener.

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 06:52:16 -07:00
fefac028ec feat: send EC shards in parallel per destination disk (#12050)
* feat: send EC shards in parallel per destination disk

One stream per destination disk. max_shard_transfers unset means no global cap, 0 sends shards sequentially, and N is a global cap that still keeps one stream per disk. The value is persisted through TaskPolicy. The maintenance form is a checkbox plus Max transfers because unset and 0 differ. The key is intentionally omitted from GetConfigSpec.

* ec shard distribution: treat negative max_shard_transfers as sequential

The config layer (normalizedMaxShardTransfers) clamps negative values to 0,
which selects sequential distribution. shardTransferCap diverged: a negative
cap that reached ShardDistributionOptions directly would have selected
uncapped parallel mode, the most aggressive setting. Align the options layer
with the same normalization so invalid input degrades to the conservative
mode.

* ec: serialize shard transfers to a server when a target leaves disk choice to the receiver

disk_id 0 is auto-placement on the receiving volume server, so an
auto-placed stream can land on a disk another queued stream is pinned
to. Grouping by (destNode, disk_id) alone let both run at once; collapse
all of that server's transfers under the destNode key instead.

* worker: clamp max_shard_transfers to the int32 wire range

ReadIntConfig returned the 0 fallback for values above MaxInt32, turning
a large positive cap into sequential mode. Read int64 and clamp into
range instead.

* worker: drop unused shard-transfer form helper

The maintenance form renders and collects max_shard_transfers in
plugin.templ JavaScript; the Go copy had no callers.

* worker: bound max_shard_transfers conversion under an in-range guard

---------

Co-authored-by: Chepurnov Simon <195125934+CHEPURNOV-S-S@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-10-25 06:37:26 -07:00
Jay HemnaniandChris Lu 0c9872f842 filer, volume: ignore Range when If-Range no longer matches (#12052)
* filer, volume: ignore Range when If-Range no longer matches

A GET with Range and a stale If-Range validator got 206 with the requested
bytes of the current file. RFC 9110 13.1.5: send the whole content instead,
so a resumed download restarts rather than mixing two versions.

* volume(rs): drop Range when If-Range no longer matches

Mirror the Go fix for the Rust volume server: evaluate If-Range against the
response ETag (strong comparison) or Last-Modified once the needle's
validators are known, then drop the range on a stale validator so the whole
current representation is sent. A dropped range on the RangeFromSource
strategy falls back to a full stream of the data-file region; buffered and
chunk-manifest paths already take Option<&str>.

* volume(rs): fail If-Range when the header value is not readable

* volume(rs): accept all HTTP-date formats in If-Range like Go

* server: cover alternate HTTP-date formats in If-Range test

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-10-25 06:36:40 -07:00
Chris LuandDevin da1d7444b8 master: shorten the first-write hold after a fresh topology id (#12059)
* master: release the post-mint allocation hold after a quiet pulse

DeferAllocation armed a fixed warmup window whenever the leader minted a
fresh topology id, so the first write on a brand-new cluster blocked for
the whole window even though no prior state could exist. The window
still has to cover a rebuilt master's veteran servers, which report on
their first post-reconnect heartbeat.

Track the last heartbeat that could carry prior cluster state — a server
joining, held volumes or shards, a nonzero id bound, or a foreign
topology id — and lift the hold one pulse after it goes quiet, capped by
the original window.

* master: make the post-mint allocation hold configurable

master.volume_growth.allocation_deferral overrides the warmup window a
leader holds volume id allocation for after minting a fresh topology
id. Unset keeps the existing window; "0s" disables the hold for setups
that know the cluster is fresh (test harnesses, single-node labs); any
other duration replaces the cap while the quiet-pulse early release
still applies.

* master: re-check the allocation deadline while it is held

NextVolumeId slept for the whole computed delay, so a heartbeat landing
mid-sleep that pushed the quiet deadline out was ignored — the pending
allocation could still run ahead of a straggler's report. Wait in short
slices, re-evaluating the deadline and the growth freeze each round.

* master: count only ids above the issued bound as prior-state evidence

Heartbeat echoes of volumes and shards this master allocated during the
hold refreshed the quiet window, so each growth allocation re-extended
the deferral until the hard cap. Evidence now requires an id beyond the
bound this leader has issued, a higher reported bound, or a foreign
topology id; a joining server (dn == nil) still counts once.

* master: reject an unparseable allocation_deferral instead of disabling the hold

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* master: do not count a skipped heartbeat as a joining server

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: assert the allocation hold extends past the original quiet deadline

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* master: release the post-mint hold after two quiet pulses

One pulse proved short for a veteran that reconnects on a staggered
restart: with only five seconds of quiet, allocation could resume and
reuse ids before a slower server landed its first heartbeat. Two pulses
still halves the fresh-cluster first-write stall versus the full warmup
cap, and known-fresh setups keep the "0s" override.

* master: pick once more when assign times out as growth concludes

The pick loop's final attempt can predate the growth it triggered
concluding: growth registers its volumes in the layout before clearing
the pending flag, so a timeout landing on that boundary used to shed a
hard 406 over volumes that had just arrived. Pick once more after the
loop in both the http and grpc assign paths before deciding how to
shed.

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 06:17:42 -07:00
Chris LuandDevin d15396fc4d s3tables: scope the anonymous identity's grant on the table catalogs (#12056)
* s3tables: scope the resolved anonymous identity instead of defaulting to allow

Catalog authorization fell back to the open default whenever the request
resolved to the configured anonymous identity, ignoring its grant. The
fallback now applies only when no principal was resolved (zero-config),
so anonymous requests are checked against the identity's configured
actions like any other principal. The S3 Tables API and the Iceberg and
Lance catalogs share this handler, so all three are covered.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: authenticate the catalog clients in the s3tables suites

Anonymous calls into the Lance and Iceberg catalogs are now scoped by
the anonymous identity's grant, so the suites that used to rely on the
anonymous pass authenticate like their real deployments do: x-api-key
for the Lance probes and REST drivers, client-credentials OAuth for
pyiceberg.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* worker(lance): authenticate namespace calls with the storage credential

Anonymous catalog calls are now scoped by the anonymous grant, so a
worker that holds an S3 credential sends it as x-api-key on the
namespace requests instead of relying on the anonymous pass.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: authenticate the pushdown catalog connection in catalog_lancedb

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* lance: follow catalog redirects only within the same host

reqwest forwards custom headers on a follow, so a redirect to another
host would carry the x-api-key credential to a server it was never
meant for. Keep same-host hops for proxies that normalize the path or
upgrade the scheme.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* lance: warn when the catalog api key travels in cleartext

The x-api-key pair is a real storage credential: over plain http to a
non-loopback host the network can read it. Warn at client build so the
operator sees it; https and loopback stay quiet, and the key still
sends since an http catalog is a valid deployment.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* lance: require the same origin on catalog redirects

A same-host hop can still downgrade https to http and put the api key on
the wire; matching scheme, host, and port keeps the credential on the
listener it was issued for.

* lance: bound catalog redirect hops so loops fail fast

The custom redirect policy drops reqwest's default 10-hop limit, so a
catalog that redirects back to itself would hold each call open until
the request timeout. Keep the bound alongside the origin check.

* lance: gofmt the redirect helpers

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 06:13:22 -07:00
Chris LuandDevin 39bdbc18db admin: keep read-only sessions out of the filer /etc tree (#12057)
* admin: keep read-only sessions out of the filer /etc tree

The file browser read routes are open to any authenticated session, so a
read-only login could download or view arbitrary filer paths. The filer
stores the credential and cluster configuration under /etc (identity JSON
with plaintext S3 secret keys, SSE-S3 keys, remote storage config), which
let a view-only session recover live secrets that the user API redacts.

Gate the read paths on the session role: read-only sessions get 403 for
/api/files/download, /view, /properties, /metadata on /etc paths, the
browser page redirects away, and recursive metadata exports skip the /etc
subtree for read-only sessions.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* admin: only reject real .. path components in file browser paths

path.Clean already resolves interior parent references, so any '..'
surviving in the cleaned path can only be a leading escape from a
relative input or part of a valid name. Matching on the substring
rejected legitimate entries like /buckets/reports/report..csv.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* admin: cover the read-only /etc export exclusion with a test

Pull the excluded-prefix selection into exportExcludedPrefixes so the
role-dependent /etc skip is exercised directly — the cleanReadPath
tests alone would still pass if the exclusion were dropped.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-25 06:06:21 -07:00
Chris Lu 403d51631b s3api: stop echoing stored tags and internal attributes on GET/HEAD (#12053)
* s3api: stop echoing stored tags and internal attributes on GET/HEAD

setResponseHeaders copied every entry.Extended key into the response,
only filtering xattr- and x-seaweedfs-. Stored object tags
(X-Amz-Tagging-*) and the gateway's own attributes (Seaweed-X-Amz-Acl,
-Owner, -Version-Id, -Object-Lock-Mode, ...) therefore leaked to any
caller holding s3:GetObject, and to anonymous readers on public-read
objects, without s3:GetObjectTagging or READ_ACP.

Tag count, user metadata, storage class and the real S3 headers
(x-amz-version-id, x-amz-object-lock-*) are unaffected.

* s3api: match stored tag and internal attribute keys case-insensitively
2026-10-25 06:05:06 -07:00
Chris Lu 52d91008ac ci: bump hosted runners to ubuntu-24.04
GitHub is retiring ubuntu-22.04; move all 94 runs-on pins across 40 workflows to ubuntu-24.04. rust_binaries_release: the arm64 cross step was jammy-era — noble keeps apt sources in deb822 ubuntu.sources (the sources.list edit was a silent no-op that left amd64 repos open to arm64 and 404'd) and ports suites must say noble. Pin deb822 stanzas to amd64 and add noble ports entries.
2026-10-24 23:07:28 -07:00
317 changed files with 24217 additions and 6406 deletions

No files matched your search

+2 -1
View File
@@ -20,4 +20,5 @@ ignore-regex = \b[a-z]+[A-Z]\w*\b|\b[A-Z][a-z]+[A-Z]\w*\b
# unknwon: GitHub username / Go module path (`github.com/unknwon/goconfig`)
# atleast: CLI mode literal string in test/benchmark/fuse_db/bin/sqlite_verify.py
# sme: local variable for a *streamMutateError in mount tests
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme
# nin: AWS S3 Vectors "$nin" filter operator literal (API-defined, cannot rename)
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme,nin
+3 -3
View File
@@ -33,7 +33,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4.39.0
uses: github/codeql-action/init@v4.39.1
# Override language selection by uncommenting this and choosing your languages
with:
languages: go
@@ -41,7 +41,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v4.39.0
uses: github/codeql-action/autobuild@v4.39.1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -55,4 +55,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4.39.0
uses: github/codeql-action/analyze@v4.39.1
+34 -4
View File
@@ -24,7 +24,7 @@ jobs:
# ── Pre-build the Rust binaries natively ────────────────────────────
build-rust-binaries:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
strategy:
matrix:
include:
@@ -44,7 +44,12 @@ jobs:
- name: Install musl tools (amd64)
if: ${{ !matrix.cross }}
run: sudo apt-get install -y musl-tools
run: |
sudo apt-get install -y musl-tools
# C deps (aws-lc-sys) must compile against musl headers, not the host
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
# __isoc23_strtol) don't exist in musl and fail the link.
echo "CC_x86_64_unknown_linux_musl=musl-gcc" >> "$GITHUB_ENV"
- name: Install cross-compilation tools (arm64)
if: matrix.cross
@@ -53,6 +58,31 @@ jobs:
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
# aws-lc-sys compiles against glibc headers, which redirect
# sscanf/strtol to C23 __isoc23_* symbols musl does not provide.
# Link a tiny forwarding shim so those references resolve to the
# musl implementations. Prototypes are declared manually: including
# glibc headers here would re-redirect the calls back to __isoc23_*.
cat > /tmp/isoc23-shim.c <<'SHIM'
#include <stdarg.h>
extern int vsscanf(const char *s, const char *fmt, va_list ap);
extern long strtol(const char *nptr, char **endptr, int base);
int __isoc23_sscanf(const char *s, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int r = vsscanf(s, fmt, ap);
va_end(ap);
return r;
}
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
return strtol(nptr, endptr, base);
}
SHIM
aarch64-linux-gnu-gcc -O2 -c /tmp/isoc23-shim.c -o /tmp/isoc23-shim.o
# link-args land after libc on the link line; rescan musl libc so
# the shim's own vsscanf/strtol references resolve, and libgcc for
# the fp128 builtins musl's vfscanf/floatscan pull in on aarch64.
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=-Clink-arg=/tmp/isoc23-shim.o -Clink-arg=-lc -Clink-arg=-lgcc" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
if: runner.environment == 'github-hosted'
@@ -175,14 +205,14 @@ jobs:
- name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -141,7 +141,7 @@ jobs:
- name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
+38 -8
View File
@@ -66,7 +66,7 @@ jobs:
# ── Pre-build the Rust binaries natively ────────────────────────────
build-rust-binaries:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
strategy:
matrix:
include:
@@ -88,7 +88,12 @@ jobs:
- name: Install musl tools (amd64)
if: ${{ !matrix.cross }}
run: sudo apt-get install -y musl-tools
run: |
sudo apt-get install -y musl-tools
# C deps (aws-lc-sys) must compile against musl headers, not the host
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
# __isoc23_strtol) don't exist in musl and fail the link.
echo "CC_x86_64_unknown_linux_musl=musl-gcc" >> "$GITHUB_ENV"
- name: Install cross-compilation tools (arm64)
if: matrix.cross
@@ -97,6 +102,31 @@ jobs:
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
# aws-lc-sys compiles against glibc headers, which redirect
# sscanf/strtol to C23 __isoc23_* symbols musl does not provide.
# Link a tiny forwarding shim so those references resolve to the
# musl implementations. Prototypes are declared manually: including
# glibc headers here would re-redirect the calls back to __isoc23_*.
cat > /tmp/isoc23-shim.c <<'SHIM'
#include <stdarg.h>
extern int vsscanf(const char *s, const char *fmt, va_list ap);
extern long strtol(const char *nptr, char **endptr, int base);
int __isoc23_sscanf(const char *s, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int r = vsscanf(s, fmt, ap);
va_end(ap);
return r;
}
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
return strtol(nptr, endptr, base);
}
SHIM
aarch64-linux-gnu-gcc -O2 -c /tmp/isoc23-shim.c -o /tmp/isoc23-shim.o
# link-args land after libc on the link line; rescan musl libc so
# the shim's own vsscanf/strtol references resolve, and libgcc for
# the fp128 builtins musl's vfscanf/floatscan pull in on aarch64.
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=-Clink-arg=/tmp/isoc23-shim.o -Clink-arg=-lc -Clink-arg=-lgcc" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
if: runner.environment == 'github-hosted'
@@ -259,13 +289,13 @@ jobs:
buildkitd-config: /tmp/buildkitd.toml
- name: Login to Docker Hub
if: needs.setup.outputs.publish == 'true'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
if: needs.setup.outputs.publish == 'true'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -313,7 +343,7 @@ jobs:
fi
- name: Login to GHCR
if: needs.setup.outputs.publish == 'true'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -414,7 +444,7 @@ jobs:
output: trivy-results.sarif
exit-code: '0'
- name: Upload Trivy scan results to GitHub Security
uses: github/codeql-action/upload-sarif@v4.39.0
uses: github/codeql-action/upload-sarif@v4.39.1
if: always()
with:
sarif_file: trivy-results.sarif
@@ -481,12 +511,12 @@ jobs:
ghcr.io/chrislusf/seaweedfs
tags: type=raw,value=${{ github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag || 'latest' }},suffix=${{ steps.config.outputs.tag_suffix }}
- name: Login to Docker Hub
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -58,7 +58,7 @@ jobs:
-
name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
@@ -47,7 +47,7 @@ jobs:
# amd64 and arm64 without QEMU, turning a 5-hour emulated cargo build into
# ~15 minutes of native compilation.
build-rust-binaries:
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
strategy:
matrix:
include:
@@ -67,7 +67,12 @@ jobs:
- name: Install musl tools (amd64)
if: ${{ !matrix.cross }}
run: sudo apt-get install -y musl-tools
run: |
sudo apt-get install -y musl-tools
# C deps (aws-lc-sys) must compile against musl headers, not the host
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
# __isoc23_strtol) don't exist in musl and fail the link.
echo "CC_x86_64_unknown_linux_musl=musl-gcc" >> "$GITHUB_ENV"
- name: Install cross-compilation tools (arm64)
if: matrix.cross
@@ -76,6 +81,31 @@ jobs:
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
echo "CFLAGS_aarch64_unknown_linux_musl=-U_FORTIFY_SOURCE" >> "$GITHUB_ENV"
# aws-lc-sys compiles against glibc headers, which redirect
# sscanf/strtol to C23 __isoc23_* symbols musl does not provide.
# Link a tiny forwarding shim so those references resolve to the
# musl implementations. Prototypes are declared manually: including
# glibc headers here would re-redirect the calls back to __isoc23_*.
cat > /tmp/isoc23-shim.c <<'SHIM'
#include <stdarg.h>
extern int vsscanf(const char *s, const char *fmt, va_list ap);
extern long strtol(const char *nptr, char **endptr, int base);
int __isoc23_sscanf(const char *s, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int r = vsscanf(s, fmt, ap);
va_end(ap);
return r;
}
long __isoc23_strtol(const char *nptr, char **endptr, int base) {
return strtol(nptr, endptr, base);
}
SHIM
aarch64-linux-gnu-gcc -O2 -c /tmp/isoc23-shim.c -o /tmp/isoc23-shim.o
# link-args land after libc on the link line; rescan musl libc so
# the shim's own vsscanf/strtol references resolve, and libgcc for
# the fp128 builtins musl's vfscanf/floatscan pull in on aarch64.
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS=-Clink-arg=/tmp/isoc23-shim.o -Clink-arg=-lc -Clink-arg=-lgcc" >> "$GITHUB_ENV"
- name: Cache cargo registry and target
if: runner.environment == 'github-hosted'
@@ -258,7 +288,7 @@ jobs:
- name: Login to GHCR
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -348,7 +378,7 @@ jobs:
- name: Login to GHCR
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -370,7 +400,7 @@ jobs:
- name: Login to Docker Hub
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
@@ -483,7 +513,7 @@ jobs:
variant: large_disk
steps:
- name: Login to GHCR
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -511,7 +541,7 @@ jobs:
- name: Upload Trivy scan results to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v4.39.0
uses: github/codeql-action/upload-sarif@v4.39.1
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
@@ -535,13 +565,13 @@ jobs:
latest_tag: latest_large_disk
steps:
- name: Login to Docker Hub
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GHCR
uses: docker/login-action@v4.6.0
uses: docker/login-action@v4.7.0
with:
registry: ghcr.io
username: ${{ secrets.GHCR_USERNAME }}
@@ -90,13 +90,13 @@ jobs:
echo "seaweedfs_ref=$seaweed" >> "$GITHUB_OUTPUT"
- name: Set up QEMU
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v1
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v1
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
- name: Login to Docker Hub
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v1
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
+1 -1
View File
@@ -32,7 +32,7 @@ defaults:
jobs:
e2e:
name: FUSE Mount
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- name: Check out code into the Go module directory
+1 -1
View File
@@ -28,7 +28,7 @@ permissions:
jobs:
ec-integration-tests:
name: EC Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- name: Set up Go 1.x
+1 -1
View File
@@ -28,7 +28,7 @@ permissions:
jobs:
fuse-dlm-integration:
name: FUSE DLM Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
+1 -1
View File
@@ -33,7 +33,7 @@ permissions:
jobs:
fuse-failover:
name: FUSE Volume Server Failover
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
+1 -1
View File
@@ -26,7 +26,7 @@ permissions:
jobs:
fuse-integration:
name: FUSE Integration Testing
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 50
steps:
+1 -1
View File
@@ -34,7 +34,7 @@ permissions:
jobs:
fuse-p2p-integration:
name: FUSE P2P Peer Chunk Sharing
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
+2 -2
View File
@@ -32,7 +32,7 @@ defaults:
jobs:
kms-provider-tests:
name: KMS Provider Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -78,7 +78,7 @@ jobs:
s3-kms-e2e-tests:
name: S3 KMS End-to-End Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
@@ -30,7 +30,7 @@ permissions:
jobs:
master-cold-start-tests:
name: Master Cold Start Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out code
@@ -37,7 +37,7 @@ env:
jobs:
metadata-subscribe-integration:
name: Metadata Subscribe Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
+1 -1
View File
@@ -30,7 +30,7 @@ permissions:
jobs:
multi-master-failover-tests:
name: Multi-Master Failover Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out code
+1 -1
View File
@@ -27,7 +27,7 @@ permissions:
jobs:
pjdfstest:
name: pjdfstest
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
+1 -1
View File
@@ -28,7 +28,7 @@ permissions:
jobs:
plugin-worker:
name: "Plugin Worker: ${{ matrix.worker }}"
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
strategy:
fail-fast: false
+2 -2
View File
@@ -520,7 +520,7 @@ jobs:
- name: Comment PR with results
if: github.event_name == 'pull_request' && always()
uses: actions/github-script@v7
uses: actions/github-script@v9
with:
script: |
const fs = require('fs');
@@ -755,7 +755,7 @@ jobs:
- name: Create compliance issue if tests fail
if: failure()
uses: actions/github-script@v7
uses: actions/github-script@v9
with:
script: |
const issue = await github.rest.issues.create({
+124
View File
@@ -0,0 +1,124 @@
name: "Rust Vector Tests"
on:
pull_request:
branches: [ master ]
paths:
- 'seaweed-vector/**'
- 'seaweed-worker/**'
- 'seaweed-common/**'
- 'weed/pb/plugin.proto'
- 'weed/pb/vector.proto'
- 'weed/pb/vector_pb/**'
- 'weed/s3api/**'
- 'weed/command/**'
- 'test/vectors/**'
- '.github/workflows/rust-vector-tests.yml'
push:
branches: [ master, main ]
paths:
- 'seaweed-vector/**'
- 'seaweed-worker/**'
- 'seaweed-common/**'
- 'weed/pb/plugin.proto'
- 'weed/pb/vector.proto'
- 'weed/pb/vector_pb/**'
- 'weed/s3api/**'
- 'weed/command/**'
- 'test/vectors/**'
- '.github/workflows/rust-vector-tests.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
permissions:
contents: read
jobs:
rust-vector-build:
name: Rust Vector Build and Unit Tests
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Fingerprint build toolchain
id: toolchain
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and target
if: runner.environment == 'github-hosted'
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-vector/target/release
key: rust-vector-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-vector/Cargo.lock') }}
restore-keys: |
rust-vector-${{ steps.toolchain.outputs.fingerprint }}-
# lance's build scripts compile their own protos and look for a protoc.
# Point them at the one protoc-bin-vendored ships, so no job depends on a
# system package and every build sees the same version.
- name: Use the vendored protoc
run: |
cd seaweed-vector
cargo fetch
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build the vector crates
run: cd seaweed-vector && cargo build --release
- name: Run unit tests
run: cd seaweed-vector && cargo test --release --workspace
vectors-e2e:
name: S3 Vectors End-to-End
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Build weed
run: go build -o test/vectors/weed ./weed
- uses: dtolnay/rust-toolchain@stable
# Same as the unit-test job: lance's build scripts need a protoc; use
# the vendored one so no system package is required.
- name: Use the vendored protoc
run: |
cd seaweed-vector
cargo fetch
version=$(awk '/^name = "protoc-bin-vendored-linux-x86_64"$/{found=1; next} found && /^version = /{gsub(/"/,"",$3); print $3; exit}' Cargo.lock)
test -n "$version" || { echo "protoc-bin-vendored-linux-x86_64 is not in Cargo.lock" >&2; exit 1; }
protoc=$(find ~/.cargo/registry/src -path "*protoc-bin-vendored-linux-x86_64-$version/bin/protoc" | head -1)
test -x "$protoc" || { echo "no vendored protoc $version in the registry" >&2; exit 1; }
echo "PROTOC=$protoc" >> "$GITHUB_ENV"
- name: Build weed-vector-server
run: cargo build --release --manifest-path seaweed-vector/Cargo.toml -p weed-vector-server
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install test deps
run: pip install boto3 pytest
- name: Run the s3vectors conformance subset
working-directory: test/vectors
run: |
cp ../../seaweed-vector/target/release/weed-vector-server weed-vector-server
./run_test.sh
@@ -54,7 +54,7 @@ jobs:
build-test-binaries:
name: Build Test Binaries
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -113,7 +113,7 @@ jobs:
rust-unit-tests:
name: Rust Unit Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -213,7 +213,7 @@ jobs:
rust-integration-tests:
name: Rust Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
needs: [build-test-binaries]
@@ -228,7 +228,7 @@ jobs:
cache: ${{ runner.environment == 'github-hosted' }}
- name: Download test binaries
uses: actions/download-artifact@v7
uses: actions/download-artifact@v8
with:
name: rust-test-binaries
@@ -270,7 +270,7 @@ jobs:
rust-volume-go-tests:
name: Go Tests with Rust Volume (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 45
needs: [build-test-binaries]
env:
@@ -293,7 +293,7 @@ jobs:
cache: ${{ runner.environment == 'github-hosted' }}
- name: Download test binaries
uses: actions/download-artifact@v7
uses: actions/download-artifact@v8
with:
name: rust-test-binaries
+1 -1
View File
@@ -26,7 +26,7 @@ permissions:
jobs:
rust-worker-build:
name: Rust Plugin Worker Build and Unit Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
permissions:
contents: write
needs: cleanup
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
strategy:
matrix:
include:
+16 -8
View File
@@ -15,7 +15,7 @@ jobs:
build-rust-volume-linux:
permissions:
contents: write
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
strategy:
matrix:
include:
@@ -37,9 +37,13 @@ jobs:
if: matrix.cross
run: |
sudo dpkg --add-architecture arm64
sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
# noble keeps apt sources in deb822 ubuntu.sources, not sources.list —
# pin them to amd64 so apt does not probe arm64 indexes on
# archive/security.ubuntu.com (they 404).
sudo sed -i '/^Types: deb$/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
for suite in noble noble-updates noble-security; do
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports $suite main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
done
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu libssl-dev:arm64
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
@@ -120,7 +124,7 @@ jobs:
build-rust-worker-linux:
permissions:
contents: write
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
strategy:
matrix:
include:
@@ -146,9 +150,13 @@ jobs:
if: matrix.cross
run: |
sudo dpkg --add-architecture arm64
sudo sed -i 's/^deb /deb [arch=amd64] /' /etc/apt/sources.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy main restricted universe multiverse" | sudo tee /etc/apt/sources.list.d/arm64.list
echo "deb [arch=arm64] http://ports.ubuntu.com/ jammy-updates main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
# noble keeps apt sources in deb822 ubuntu.sources, not sources.list —
# pin them to amd64 so apt does not probe arm64 indexes on
# archive/security.ubuntu.com (they 404).
sudo sed -i '/^Types: deb$/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
for suite in noble noble-updates noble-security; do
echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports $suite main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/arm64.list
done
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
+1 -1
View File
@@ -30,7 +30,7 @@ permissions:
jobs:
s3-etag-acl-tests:
name: S3 ETag + ACL Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Check out code
@@ -22,7 +22,7 @@ permissions:
jobs:
tests:
name: S3 Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
+1 -1
View File
@@ -25,7 +25,7 @@ defaults:
jobs:
s3-filer-group-tests:
name: S3 Filer Group Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
+11 -11
View File
@@ -26,7 +26,7 @@ defaults:
jobs:
s3-versioning-tests:
name: S3 Versioning Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
matrix:
@@ -97,7 +97,7 @@ jobs:
s3-versioning-compatibility:
name: S3 Versioning Compatibility Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -146,7 +146,7 @@ jobs:
s3-cors-compatibility:
name: S3 CORS Compatibility Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -195,7 +195,7 @@ jobs:
s3-retention-tests:
name: S3 Retention Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
matrix:
@@ -266,7 +266,7 @@ jobs:
s3-lifecycle-tests:
name: S3 Lifecycle Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
strategy:
fail-fast: false
@@ -339,7 +339,7 @@ jobs:
s3-checksum-tests:
name: S3 Checksum Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -398,7 +398,7 @@ jobs:
s3-cors-tests:
name: S3 CORS Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
matrix:
@@ -469,7 +469,7 @@ jobs:
s3-retention-worm:
name: S3 Retention WORM Integration Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -519,7 +519,7 @@ jobs:
s3-versioning-stress:
name: S3 Versioning Stress Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 35
steps:
@@ -588,7 +588,7 @@ jobs:
s3-tagging-tests:
# CI job for S3 object tagging tests
name: S3 Tagging Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -644,7 +644,7 @@ jobs:
s3-remote-cache-tests:
name: S3 Remote Cache Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
+4 -4
View File
@@ -34,7 +34,7 @@ jobs:
# Unit tests for IAM components
iam-unit-tests:
name: IAM Unit Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -81,7 +81,7 @@ jobs:
# S3 IAM integration tests with SeaweedFS services
s3-iam-integration-tests:
name: S3 IAM Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
strategy:
matrix:
@@ -202,7 +202,7 @@ jobs:
# Distributed IAM tests
s3-iam-distributed-tests:
name: S3 IAM Distributed Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
@@ -263,7 +263,7 @@ jobs:
# Performance and stress tests
s3-iam-performance-tests:
name: S3 IAM Performance Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
# Dedicated job for Keycloak integration tests
s3-keycloak-integration-tests:
name: S3 Keycloak Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -21,7 +21,7 @@ permissions:
jobs:
s3-versioning-regressions:
name: S3 Versioning Regression Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
@@ -75,7 +75,7 @@ jobs:
s3-delete-regressions:
name: S3 Delete Regression Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -114,7 +114,7 @@ jobs:
s3-distributed-lock-regressions:
name: S3 Distributed Lock Regression Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
+5 -5
View File
@@ -38,7 +38,7 @@ jobs:
# Unit tests for policy components
policy-unit-tests:
name: S3 Policy Unit Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -82,7 +82,7 @@ jobs:
# S3 Policy Variables Integration Tests
s3-policy-variables-tests:
name: S3 Policy Variables Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
@@ -192,7 +192,7 @@ jobs:
# S3 Policy Enforcement Integration Tests
s3-policy-enforcement-tests:
name: S3 Policy Enforcement Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
matrix:
@@ -317,7 +317,7 @@ jobs:
# Trusted Proxy Detection Tests
trusted-proxy-tests:
name: Trusted Proxy Detection Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -405,7 +405,7 @@ jobs:
# S3 Policy Shell Integration Tests
s3-policy-shell-tests:
name: S3 Policy Shell Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -30,7 +30,7 @@ permissions:
jobs:
proxy-signature-tests:
name: S3 Proxy Signature Verification Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Check out code into the Go module directory
@@ -24,7 +24,7 @@ permissions:
jobs:
s3-sdk-v2-routing-tests:
name: S3 SDK V2 Routing Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out code
+1 -1
View File
@@ -46,7 +46,7 @@ permissions:
jobs:
snowflake-s3compat-tests:
name: Snowflake S3Compat API tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
env:
WORK_DIR: /tmp/seaweedfs-snowflake-tests
+1 -1
View File
@@ -20,7 +20,7 @@ permissions:
jobs:
s3-spark-issue-repro-tests:
name: S3 Spark Issue Reproduction Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
+7 -7
View File
@@ -36,7 +36,7 @@ defaults:
jobs:
s3-sse-integration-tests:
name: S3 SSE Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
matrix:
@@ -111,7 +111,7 @@ jobs:
s3-sse-compatibility:
name: S3 SSE Compatibility Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -160,7 +160,7 @@ jobs:
s3-sse-metadata-persistence:
name: S3 SSE Metadata Persistence Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -210,7 +210,7 @@ jobs:
s3-sse-copy-operations:
name: S3 SSE Copy Operations Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
@@ -260,7 +260,7 @@ jobs:
s3-sse-multipart:
name: S3 SSE Multipart Upload Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
@@ -310,7 +310,7 @@ jobs:
s3-sse-performance:
name: S3 SSE Performance Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 35
# Only run performance tests on master branch pushes to avoid overloading PR testing
if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/main')
@@ -361,7 +361,7 @@ jobs:
s3-volume-encryption:
name: S3 Volume Encryption Test
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
+20 -20
View File
@@ -23,7 +23,7 @@ permissions:
jobs:
s3-tables-tests:
name: S3 Tables Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -88,7 +88,7 @@ jobs:
iceberg-catalog-tests:
name: Iceberg Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -153,7 +153,7 @@ jobs:
trino-iceberg-catalog-tests:
name: Trino Iceberg Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -227,7 +227,7 @@ jobs:
dremio-iceberg-catalog-tests:
name: Dremio Iceberg Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -304,7 +304,7 @@ jobs:
doris-iceberg-catalog-tests:
name: Doris Iceberg Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 35
steps:
@@ -381,7 +381,7 @@ jobs:
clickhouse-iceberg-catalog-tests:
name: ClickHouse Iceberg Catalog Integration Tests (${{ matrix.tag }})
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
@@ -470,7 +470,7 @@ jobs:
olake-iceberg-catalog-tests:
name: OLake Iceberg Catalog Integration Tests (${{ matrix.tag }})
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
@@ -585,7 +585,7 @@ jobs:
polaris-integration-tests:
name: Polaris Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -657,7 +657,7 @@ jobs:
spark-iceberg-catalog-tests:
name: Spark Iceberg Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -731,7 +731,7 @@ jobs:
risingwave-catalog-tests:
name: RisingWave Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -806,7 +806,7 @@ jobs:
sts-integration-tests:
name: STS Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -905,7 +905,7 @@ jobs:
lakekeeper-integration-tests:
name: Lakekeeper Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -969,7 +969,7 @@ jobs:
unity-catalog-integration-tests:
name: Unity Catalog Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -1046,7 +1046,7 @@ jobs:
lancedb-namespace-tests:
name: LanceDB Namespace Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -1120,7 +1120,7 @@ jobs:
table-lifecycle-tests:
name: Table Lifecycle Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
@@ -1189,7 +1189,7 @@ jobs:
duckdb-lance-tests:
name: DuckDB Lance Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
@@ -1268,7 +1268,7 @@ jobs:
spark-lance-namespace-tests:
name: Spark Lance Namespace Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 40
steps:
@@ -1346,7 +1346,7 @@ jobs:
s3-tables-build-verification:
name: S3 Tables Build Verification
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -1412,7 +1412,7 @@ jobs:
s3-tables-fmt-check:
name: S3 Tables Format Check
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
@@ -1464,7 +1464,7 @@ jobs:
s3-tables-vet:
name: S3 Tables Go Vet Check
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
+25 -11
View File
@@ -34,7 +34,7 @@ permissions:
jobs:
basic-s3-tests:
name: Basic S3 tests (KV store)
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Check out code into the Go module directory
@@ -380,14 +380,21 @@ jobs:
s3tests/functional/test_s3.py::test_copy_object_ifnonematch_good \
s3tests/functional/test_s3.py::test_lifecycle_set \
s3tests/functional/test_s3.py::test_lifecycle_get \
s3tests/functional/test_s3.py::test_lifecycle_set_filter \
s3tests/functional/test_s3.py::test_lifecycle_expiration \
s3tests/functional/test_s3.py::test_lifecyclev2_expiration
s3tests/functional/test_s3.py::test_lifecycle_set_filter
# The expiration tests race the lifecycle worker's meta-log replay;
# under the suite's write flood a shard can trail an object's PUT
# event past the test's fixed sleep window. One retry absorbs it.
lifecycle_expiration() {
tox -- s3tests/functional/test_s3.py::test_lifecycle_expiration \
s3tests/functional/test_s3.py::test_lifecyclev2_expiration
}
lifecycle_expiration || { echo "lifecycle expiration tests flaked; retry 1"; lifecycle_expiration; } || { echo "lifecycle expiration tests flaked; retry 2"; lifecycle_expiration; }
# cleanup() trap handles worker/server kill + data dir wipe.
versioning-tests:
name: S3 Versioning & Object Lock tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Check out code into the Go module directory
@@ -558,7 +565,7 @@ jobs:
cors-tests:
name: S3 CORS tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out code into the Go module directory
@@ -684,7 +691,7 @@ jobs:
copy-tests:
name: SeaweedFS Custom S3 Copy tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out code into the Go module directory
@@ -787,7 +794,7 @@ jobs:
sql-store-tests:
name: Basic S3 tests (SQL store)
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Check out code into the Go module directory
@@ -1250,9 +1257,16 @@ jobs:
s3tests/functional/test_s3.py::test_copy_object_ifnonematch_good \
s3tests/functional/test_s3.py::test_lifecycle_set \
s3tests/functional/test_s3.py::test_lifecycle_get \
s3tests/functional/test_s3.py::test_lifecycle_set_filter \
s3tests/functional/test_s3.py::test_lifecycle_expiration \
s3tests/functional/test_s3.py::test_lifecyclev2_expiration
s3tests/functional/test_s3.py::test_lifecycle_set_filter
# The expiration tests race the lifecycle worker's meta-log replay;
# under the suite's write flood a shard can trail an object's PUT
# event past the test's fixed sleep window. One retry absorbs it.
lifecycle_expiration() {
tox -- s3tests/functional/test_s3.py::test_lifecycle_expiration \
s3tests/functional/test_s3.py::test_lifecyclev2_expiration
}
lifecycle_expiration || { echo "lifecycle expiration tests flaked; retry 1"; lifecycle_expiration; } || { echo "lifecycle expiration tests flaked; retry 2"; lifecycle_expiration; }
# cleanup() trap handles worker/server kill + data dir wipe.
+1 -1
View File
@@ -29,7 +29,7 @@ permissions:
jobs:
samba-integration:
name: samba-integration
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
+1 -1
View File
@@ -29,7 +29,7 @@ env:
jobs:
sftp-integration:
name: SFTP Integration Testing
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
+1 -1
View File
@@ -28,7 +28,7 @@ permissions:
jobs:
tls-rotation-tests:
name: TLS Rotation Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Set up Go 1.x
+1 -1
View File
@@ -24,7 +24,7 @@ defaults:
jobs:
tus-integration-tests:
name: TUS Protocol Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
@@ -28,7 +28,7 @@ permissions:
jobs:
vacuum-integration-tests:
name: Vacuum Integration Tests
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Set up Go 1.x
@@ -35,7 +35,7 @@ env:
jobs:
build-weed:
name: Build SeaweedFS Binary
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
@@ -68,7 +68,7 @@ jobs:
volume-server-integration-tests:
name: Volume Server Integration Tests (${{ matrix.test-type }} - Shard ${{ matrix.shard }})
runs-on: ubuntu-22.04
runs-on: ubuntu-24.04
timeout-minutes: 45
needs: [build-weed]
strategy:
@@ -88,7 +88,7 @@ jobs:
cache: ${{ runner.environment == 'github-hosted' }}
- name: Download binary
uses: actions/download-artifact@v7
uses: actions/download-artifact@v8
with:
name: weed-binary
+8 -8
View File
@@ -115,8 +115,8 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Jille/raft-grpc-transport v1.6.1
github.com/ThreeDotsLabs/watermill v1.5.2
github.com/a-h/templ v0.3.1070
github.com/ThreeDotsLabs/watermill v1.5.3
github.com/a-h/templ v0.3.1100
github.com/apache/cassandra-gocql-driver/v2 v2.1.2
github.com/apache/iceberg-go v0.7.0
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
@@ -129,7 +129,7 @@ require (
github.com/cespare/xxhash/v2 v2.3.0
github.com/cognusion/imaging v1.0.4
github.com/fluent/fluent-logger-golang v1.10.1
github.com/getsentry/sentry-go v0.49.0
github.com/getsentry/sentry-go v0.50.0
github.com/go-ldap/ldap/v3 v3.4.14
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
@@ -142,11 +142,11 @@ require (
github.com/minio/crc64nvme v1.1.1
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.32.0
github.com/pkg/sftp v1.13.11
github.com/pkg/sftp v1.13.12
github.com/rabbitmq/amqp091-go v1.15.0
github.com/rclone/rclone v1.75.1
github.com/rdleal/intervalst v1.5.0
github.com/redis/go-redis/v9 v9.22.0
github.com/redis/go-redis/v9 v9.23.0
github.com/schollz/progressbar/v3 v3.19.1
github.com/seaweedfs/go-fuse/v2 v2.9.4
github.com/shirou/gopsutil/v4 v4.26.7
@@ -294,9 +294,9 @@ require (
cloud.google.com/go/iam v1.13.0 // indirect
cloud.google.com/go/monitoring v1.30.0 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.2
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.2
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 // indirect
github.com/Azure/go-ntlmssp v0.1.1 // indirect
@@ -314,7 +314,7 @@ require (
github.com/ProtonMail/go-srp v0.0.7 // indirect
github.com/PuerkitoBio/goquery v1.12.0 // indirect
github.com/abbot/go-http-auth v0.4.0 // indirect
github.com/andybalholm/brotli v1.2.6 // indirect
github.com/andybalholm/brotli v1.2.7 // indirect
github.com/andybalholm/cascadia v1.3.4 // indirect
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
+16 -16
View File
@@ -34,14 +34,14 @@ filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.2 h1:utpeoEeZjd+A8J41zvoLsOOrqXHhX1Kx/X/tCW9dEYQ=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.2/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3 h1:qgnWTiWs1G7AqcKZegFvkJD1bmXJcaDU3uC0ELSgZ5U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3/go.mod h1:XtxD48QPInqoj+GMlcRlXHEYsoOxFnP6w2JgIZ9rDS4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE=
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0 h1:m/sWOGCREuSBqg2htVQTBY8nOZpyajYztF0vUvSZTuM=
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0/go.mod h1:Pu5Zksi2KrU7LPbZbNINx6fuVrUp/ffvpxdDj+i8LeE=
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 h1:FbH3BbSb4bvGluTesZZ+ttN/MDsnMmQP36OSnDuSXqw=
@@ -116,12 +116,12 @@ github.com/Shopify/sarama v1.38.1 h1:lqqPUPQZ7zPqYlWpTh+LQ9bhYNu2xJL6k1SJN4WVe2A
github.com/Shopify/sarama v1.38.1/go.mod h1:iwv9a67Ha8VNa+TifujYoWGxWnu2kNVAQdSdZ4X2o5g=
github.com/Shopify/toxiproxy/v2 v2.5.0 h1:i4LPT+qrSlKNtQf5QliVjdP08GyAH8+BUIc9gT0eahc=
github.com/Shopify/toxiproxy/v2 v2.5.0/go.mod h1:yhM2epWtAmel9CB8r2+L+PCmhH6yH2pITaPAo7jxJl0=
github.com/ThreeDotsLabs/watermill v1.5.2 h1:0ES33Eq1jEsP/pWvtE4n8bE0bs+9Jq7boT7wGBCVY6Q=
github.com/ThreeDotsLabs/watermill v1.5.2/go.mod h1:i9/968UriGphWfEbfMuYSD1qFbYRjb0mE0r+rV0FPp4=
github.com/ThreeDotsLabs/watermill v1.5.3 h1:GoTR7fW1ZT+itzUv/w3VB6Um1B7oTBrOWjJ8sOA9XqU=
github.com/ThreeDotsLabs/watermill v1.5.3/go.mod h1:i9/968UriGphWfEbfMuYSD1qFbYRjb0mE0r+rV0FPp4=
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb h1:wumPkzt4zaxO4rHPBrjDK8iZMR41C1qs7njNqlacwQg=
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb/go.mod h1:QiYsIBRQEO+Z4Rz7GoI+dsHVneZNONvhczuA+llOZNM=
github.com/a-h/templ v0.3.1070 h1:3iCOXHXqFXa99OQzgkUOLJbNzv/QjFGLwKZkBAg+ADA=
github.com/a-h/templ v0.3.1070/go.mod h1:iIqB3g2RHBe/WlnPwa+Bvhh1TKXHWLRnBD9NWHOLm78=
github.com/a-h/templ v0.3.1100 h1:lQhjVs1IL+M6QWUvojaFBd21+kzwATppSyWkWB9oHoM=
github.com/a-h/templ v0.3.1100/go.mod h1:j1WAOR7749mlo1AxFLQ7qbDFW5VwyoqszRTlKqEHN9M=
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 h1:iLDOF0rdGTrol/q8OfPIIs5kLD8XvA2q75o6Uq/tgak=
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0/go.mod h1:DrEWcQJjz7t5iF2duaiyhg4jyoF0kxOD6LtECNGkZ/Q=
github.com/aalpar/deheap v1.1.2 h1:MABHLcnjqsffb8GLkUFDigqpBBxOMz0DoKM9QfELeTw=
@@ -144,8 +144,8 @@ github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktp
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/anchore/go-lzo v0.1.1 h1:IwL/fvkdtlIrYIXck6WxZ3nb8WjjHziYYmGxlooyOnM=
github.com/anchore/go-lzo v0.1.1/go.mod h1:3kLx0bve2oN1iDwgM1U5zGku1Tfbdb0No5qp1eL1fIk=
github.com/andybalholm/brotli v1.2.6 h1:ftYnfj6usCp+UGV5kSJ3+chpMQgU+gJf/AxsUQ52REI=
github.com/andybalholm/brotli v1.2.6/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
@@ -474,8 +474,8 @@ github.com/geoarrow/geoarrow-go v0.0.0-20260403143023-f54751c3e3a1 h1:8VcjuP5pKZ
github.com/geoarrow/geoarrow-go v0.0.0-20260403143023-f54751c3e3a1/go.mod h1:XMOIOA5J96jEzAOpBROPyz0n14sHsooeF+y2FtGdrCY=
github.com/geoffgarside/ber v1.2.0 h1:/loowoRcs/MWLYmGX9QtIAbA+V/FrnVLsMMPhwiRm64=
github.com/geoffgarside/ber v1.2.0/go.mod h1:jVPKeCbj6MvQZhwLYsGwaGI52oUorHoHKNecGT85ZCc=
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
@@ -1005,8 +1005,8 @@ github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE=
github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0=
github.com/pkg/sftp v1.13.12 h1:Myhzy/ZzLPnCtE2F2WtDHsgs8RfgMnH2gfbHuCJhkMU=
github.com/pkg/sftp v1.13.12/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0=
github.com/pkg/xattr v0.4.12 h1:rRTkSyFNTRElv6pkA3zpjHpQ90p/OdHQC1GmGh1aTjM=
github.com/pkg/xattr v0.4.12/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
@@ -1063,8 +1063,8 @@ github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5X
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
github.com/rdleal/intervalst v1.5.0/go.mod h1:xO89Z6BC+LQDH+IPQQw/OESt5UADgFD41tYMUINGpxQ=
github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/redis/rueidis v1.0.77 h1:ZR41bgJcm7oRFb3aSDPrRhC0eonDSrPzjvvZvHIlNjM=
github.com/redis/rueidis v1.0.77/go.mod h1:L8mnCQJJaSNL6I4pIR6Rz732HTGS9vmuXm0yT9dRvjo=
github.com/redis/rueidis/rueidiscompat v1.0.77 h1:S1xiLQsFv8XQ46e0LelC8ihGqbDzVRocXXZLzVAeh64=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.50"
appVersion: "4.51"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.50.0
version: 4.51.0
+1037 -1034
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

+21 -1
View File
@@ -166,6 +166,10 @@ message Entry {
repeated FileChunk chunks = 3;
FuseAttributes attributes = 4;
map<string, bytes> extended = 5;
// filer-local commit timestamp of the version stored here: the meta log
// event's ts_ns for the mutation that produced this entry, or 0 for
// entries written before the field existed
int64 commit_ts_ns = 6;
bytes hard_link_id = 7;
int32 hard_link_counter = 8; // only exists in hard link meta data
bytes content = 9; // if not empty, the file content
@@ -281,6 +285,7 @@ message WriteCondition {
IF_EXTENDED_NOT_EQUAL = 7; // fail if present and extended[ext_key] == ext_value
IF_EXTENDED_TIME_ELAPSED = 8; // fail if present and extended[ext_key] (unix seconds) is in the future
IF_CHUNKS_EQUAL = 9; // fail unless the stored chunk fid multiset equals fids (absent entry = no chunks)
IF_ENTRY_EQUAL = 10; // fail unless the stored entry equals expected_entry
}
// Clause is one primitive comparison. IF_ETAG_MATCH holds when the current
// entry's ETag equals any value in etags; IF_ETAG_NOT_MATCH holds when it
@@ -309,6 +314,7 @@ message WriteCondition {
string gate_key = 7; // IF_EXTENDED_TIME_ELAPSED: only enforce when extended[gate_key] == gate_value
string gate_value = 8; // gate value (e.g. retention mode COMPLIANCE for governance bypass)
repeated string fids = 9; // chunk fid strings for IF_CHUNKS_EQUAL
Entry expected_entry = 10; // whole-entry comparison for IF_ENTRY_EQUAL
}
repeated Clause clauses = 1; // all must hold (logical AND)
}
@@ -323,6 +329,7 @@ enum FilerError {
EXISTING_IS_FILE = 4; // cannot overwrite file with directory
ENTRY_ALREADY_EXISTS = 5; // O_EXCL and entry already exists
PRECONDITION_FAILED = 6; // WriteCondition not satisfied
READ_ONLY = 7; // path matches a read-only storage rule (e.g. bucket over quota)
}
// ObjectMutation is one entry-level change applied by ObjectTransaction. All
@@ -351,6 +358,7 @@ message ObjectMutation {
bytes content = 11; // PATCH_EXTENDED: new Entry.content when set_content
bool touch_mtime = 12; // PATCH_EXTENDED: set the entry's Mtime to now (e.g. a metadata-replace copy)
bool remove_empty_parent = 13; // DELETE: also remove the parent directory when the delete leaves it empty (best-effort)
bool keep_remote_object = 14; // DELETE: leave the object on the mounted remote storage
}
// Recompute re-derives a pointer entry (directory/name on the mutation) from the
@@ -388,6 +396,8 @@ message ObjectTransactionRequest {
string condition_key = 6; // if set, evaluate the condition against this entry instead of lock_key (still locking lock_key)
string route_key = 7; // ring key identifying the owner filer; a non-owner forwards the whole transaction to it
bool is_moved = 8; // set on a forwarded transaction so the receiver applies it locally instead of forwarding again
string request_id = 9; // idempotency token: the owner records the outcome and replays it on a retried request instead of re-applying
string condition_alt_key = 10; // if the condition's entry is absent, evaluate it against this entry instead (e.g. null slot, else latest version)
}
message ObjectTransactionResponse {
@@ -477,6 +487,7 @@ message UpdateEntryRequest {
// the write, under the filer's per-path lock. The caller must route the
// key's writes to this entry's owner filer for the check to be authoritative.
WriteCondition condition = 6;
bool is_moved = 7; // set on a forwarded request so the owner applies it locally
}
message UpdateEntryResponse {
SubscribeMetadataResponse metadata_event = 1;
@@ -513,7 +524,9 @@ message DeleteEntryRequest {
bool ignore_recursive_error = 6;
bool is_from_other_cluster = 7;
repeated int32 signatures = 8;
int64 if_not_modified_after = 9;
int64 if_not_modified_after = 9; // unix time in seconds
bool keep_remote_object = 10;
int64 if_not_modified_after_ns = 11; // unix time in nanoseconds; overrides if_not_modified_after when set
}
message DeleteEntryResponse {
@@ -573,6 +586,9 @@ message AssignVolumeResponse {
// fsync is the storage rule's fsync decision for the assigned path, so the
// client can carry it onto the volume server upload request.
bool fsync = 11;
// error_code classifies error for callers that must branch on it; error
// keeps the human-readable text for clients that predate the field.
FilerError error_code = 12;
}
message LookupVolumeRequest {
@@ -709,6 +725,10 @@ message TraverseBfsMetadataRequest {
message TraverseBfsMetadataResponse {
string directory = 1;
Entry entry = 2;
// The sender's per-path commit timestamp (see meta_path_ts.go): the newest
// event time this filer committed for the path, 0 when unrecorded so
// subscribers fall back to the entry's mtime.
int64 entry_ts_ns = 3;
}
message LogEntry {
+6832
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
# Vector query engine for SeaweedFS Lance table buckets.
#
# `core` is the engine: open a table through the Lance namespace and run
# top-K over it. The crate layout follows vector_buckets.md; a `server`
# crate with the VectorService gRPC endpoint lands with the S3 Vectors
# milestone.
[workspace]
resolver = "2"
members = ["crates/core", "crates/server"]
[workspace.package]
version = "0.1.0"
edition = "2024"
# The edition needs 1.85; the lance dependency tree needs more. Same floor as
# seaweed-worker, which this workspace path-depends on.
rust-version = "1.94.1"
# No common root manifest links this tree to seaweed-worker or
# seaweed-common; keep the lint policy identical to theirs.
[workspace.lints.clippy]
needless_update = "allow"
undocumented_unsafe_blocks = "warn"
[workspace.dependencies]
anyhow = "1"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+41
View File
@@ -0,0 +1,41 @@
[package]
name = "weed-vector-core"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "Vector query engine over SeaweedFS Lance table buckets"
[lib]
name = "weed_vector_core"
[[bin]]
name = "weed-vector"
path = "src/main.rs"
[dependencies]
# The catalog client and dataset-opening helper the maintenance worker uses.
# A path dependency because the two trees are separate cargo workspaces with
# no common root manifest.
weed-lance-worker = { path = "../../../seaweed-worker/crates/lance" }
lance = { version = "10", default-features = false, features = ["aws"] }
lance-index = "10"
lance-linalg = "10"
lance-table = "10"
arrow-array = "58"
arrow-cast = "58"
arrow-schema = "58"
roaring = "0.11"
anyhow.workspace = true
clap = { version = "4", features = ["derive", "env"] }
futures = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
[dev-dependencies]
tempfile = "3"
[lints]
workspace = true
+201
View File
@@ -0,0 +1,201 @@
//! Which fragments the vector index covers, and which it has not reached yet.
use std::collections::BTreeMap;
use anyhow::{Context, Result};
use lance::Dataset;
use lance::index::DatasetIndexExt;
use roaring::RoaringBitmap;
/// How much of the dataset one named index covers at this version.
#[derive(Debug, serde::Serialize)]
pub struct IndexCoverage {
pub index_name: String,
/// Physical index segments: the IndexMetadata deltas sharing the name.
pub segments: usize,
/// False when any delta of this index lacks a fragment bitmap: the index
/// exists but which fragments it covers is unknown.
pub coverage_known: bool,
pub indexed_fragments: Vec<u64>,
pub unindexed_fragments: Vec<u64>,
pub unindexed_rows: usize,
}
/// Coverage for every index built on `vector_column` at this version.
pub async fn coverage(dataset: &Dataset, vector_column: &str) -> Result<Vec<IndexCoverage>> {
let field = dataset
.schema()
.field(vector_column)
.with_context(|| format!("no such column {vector_column}"))?;
let mut by_name: BTreeMap<String, Vec<Option<RoaringBitmap>>> = BTreeMap::new();
for index in dataset.load_indices().await?.iter() {
if index.fields != [field.id] {
continue;
}
by_name
.entry(index.name.clone())
.or_default()
.push(index.fragment_bitmap.clone());
}
let all: RoaringBitmap = dataset.fragments().iter().map(|f| f.id as u32).collect();
let mut out = Vec::new();
for (name, bitmaps) in by_name {
let coverage_known = bitmaps.iter().all(|b| b.is_some());
let mut indexed = RoaringBitmap::new();
for bitmap in bitmaps.iter().flatten() {
indexed |= bitmap;
}
// The bitmap records what the index covered when built; fragments
// the manifest has since dropped are not part of this version.
let indexed = indexed & &all;
let unindexed = &all - &indexed;
let mut unindexed_rows = 0;
for fragment in dataset.get_fragments() {
// physical_rows counts deleted rows too, and may be absent in the
// manifest; count live rows instead.
if unindexed.contains(fragment.id() as u32) {
unindexed_rows += fragment.count_rows(None).await?;
}
}
out.push(IndexCoverage {
index_name: name,
segments: bitmaps.len(),
coverage_known,
indexed_fragments: indexed.iter().map(|id| id as u64).collect(),
unindexed_rows,
unindexed_fragments: unindexed.iter().map(|id| id as u64).collect(),
});
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query::{Query, ann, flat};
use crate::table::VectorTable;
use crate::testing::{DIM, append_dataset, vectors, write_dataset};
use lance::index::vector::VectorIndexParams;
use lance_index::IndexType;
use lance_linalg::distance::DistanceType;
use tempfile::TempDir;
async fn indexed_dataset(dir: &TempDir, tags: &[&str]) -> Dataset {
let mut dataset = write_dataset(dir, &vectors(tags.len(), DIM), tags).await;
let params = VectorIndexParams::ivf_flat(4, DistanceType::L2);
dataset
.create_index(
&["vector"],
IndexType::Vector,
Some("vidx".to_string()),
&params,
true,
)
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
dataset
}
#[tokio::test]
async fn coverage_reports_the_unindexed_fragment() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir, &["a"; 64]).await;
append_dataset(&mut dataset, &vectors(4, DIM), &["b"; 4]).await;
let coverages = coverage(&dataset, "vector").await.unwrap();
assert_eq!(coverages.len(), 1);
let cov = &coverages[0];
assert_eq!(cov.index_name, "vidx");
assert_eq!(cov.segments, 1);
assert_eq!(cov.indexed_fragments, vec![0]);
assert_eq!(cov.unindexed_fragments.len(), 1);
assert_eq!(cov.unindexed_rows, 4);
}
#[tokio::test]
async fn ann_searches_unindexed_fragments() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir, &["a"; 64]).await;
append_dataset(&mut dataset, &[vec![9.0; DIM]], &["b"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let hits = ann(
&dataset,
&table,
&Query {
vector: vec![9.0; DIM],
k: 1,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
},
)
.await
.unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].key, "k64");
assert!(hits[0].distance < 1e-6);
}
#[tokio::test]
async fn prefiltered_ann_matches_filtered_flat() {
let dir = TempDir::new().unwrap();
let tags: Vec<&str> = (0..64)
.map(|i| if i % 2 == 0 { "a" } else { "b" })
.collect();
let mut dataset = indexed_dataset(&dir, &tags).await;
append_dataset(&mut dataset, &vectors(4, DIM), &["a"; 4]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: vectors(1, DIM).remove(0),
k: 10,
filter: Some("tag = 'a'".to_string()),
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
};
let filtered = ann(&dataset, &table, &query).await.unwrap();
let exact = flat(&dataset, &table, &query).await.unwrap();
// equal-distance hits have no specified order between the two scans
let mut filtered_keys = filtered.iter().map(|h| &h.key).collect::<Vec<_>>();
let mut exact_keys = exact.iter().map(|h| &h.key).collect::<Vec<_>>();
filtered_keys.sort();
exact_keys.sort();
assert_eq!(filtered_keys, exact_keys);
assert!(filtered.len() <= 10);
assert!(filtered.iter().all(|h| h.key != "k1"));
}
#[tokio::test]
async fn pinned_version_ignores_newer_commits() {
let dir = TempDir::new().unwrap();
let mut dataset = write_dataset(&dir, &vectors(4, DIM), &["a"; 4]).await;
let pinned = dataset
.checkout_version(dataset.version().version)
.await
.unwrap();
append_dataset(&mut dataset, &vectors(4, DIM), &["b"; 4]).await;
assert_eq!(pinned.count_rows(None).await.unwrap(), 4);
let table = VectorTable::resolve(&pinned, None, None).unwrap();
let hits = flat(
&pinned,
&table,
&Query {
vector: vectors(1, DIM).remove(0),
k: 10,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
},
)
.await
.unwrap();
assert_eq!(hits.len(), 4);
assert!(hits.iter().all(|h| h.row_id < 4));
}
}
+18
View File
@@ -0,0 +1,18 @@
//! Vector queries over the Lance tables the SeaweedFS namespace registers.
//!
//! A table bucket's rows carry a key column, a fixed-size float vector column,
//! and metadata columns. This crate resolves that layout and runs top-K over
//! the whole dataset: index-accelerated where an ANN index exists, exact where
//! it does not, always covering the fragments no index has reached yet.
pub mod coverage;
pub mod query;
pub mod table;
#[cfg(test)]
mod testing;
#[cfg(test)]
mod verify;
pub use coverage::IndexCoverage;
pub use query::{Hit, Query};
pub use table::VectorTable;
+305
View File
@@ -0,0 +1,305 @@
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use weed_lance_worker::catalog::{NamespaceClient, parse_id};
use weed_lance_worker::dataset::{self, FallbackOptions};
use weed_vector_core::coverage;
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
/// Mirrors `weed-worker`'s flags where the two touch the same thing: the
/// namespace is WEED_LANCE_NAMESPACE and the fallback storage credentials are
/// the same env vars.
#[derive(Parser, Debug)]
#[command(name = "weed-vector", about = "SeaweedFS vector query spike")]
struct Args {
/// Lance namespace the tables live in.
#[arg(
long,
default_value = "http://localhost:9101",
env = "WEED_LANCE_NAMESPACE"
)]
namespace: String,
/// Storage credentials to use where the namespace vends none.
#[arg(long, env = "WEED_S3_ACCESS_KEY")]
access_key: Option<String>,
#[arg(long, env = "WEED_S3_SECRET_KEY")]
secret_key: Option<String>,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Debug)]
enum Command {
/// A table's location, version, vector layout and index coverage.
Describe {
/// Delimiter-joined table id, e.g. bucket$table.
id: String,
#[arg(long)]
vector_column: Option<String>,
#[arg(long)]
key_column: Option<String>,
},
/// Which fragments each vector index covers.
Coverage {
id: String,
#[arg(long)]
vector_column: Option<String>,
#[arg(long)]
key_column: Option<String>,
},
/// A top-K query over the whole dataset.
Query {
id: String,
/// Comma-separated floats, e.g. --vector 0.1,0.2,0.3,0.4
#[arg(long, allow_hyphen_values = true)]
vector: String,
#[arg(long, default_value = "10")]
k: usize,
/// Lance SQL filter over the metadata columns.
#[arg(long)]
filter: Option<String>,
/// l2, cosine or dot.
#[arg(long, default_value = "l2")]
metric: String,
/// Exact scan, no index.
#[arg(long)]
flat: bool,
/// Filter the top-K rows after ranking (Lance's default); off keeps
/// the filter before the ANN search.
#[arg(long)]
postfilter: bool,
/// Pin the query to this committed version.
#[arg(long)]
version: Option<u64>,
#[arg(long)]
vector_column: Option<String>,
#[arg(long)]
key_column: Option<String>,
#[arg(long)]
nprobes: Option<usize>,
},
/// Fetch rows by key.
Get {
id: String,
keys: Vec<String>,
#[arg(long)]
vector_column: Option<String>,
#[arg(long)]
key_column: Option<String>,
},
}
/// `id` is a delimiter-joined table id; when it looks like a URI (`s3://...`,
/// `/path/...`, `file://...`) the dataset is opened directly, skipping the
/// namespace — useful for a spike run against a local dataset.
async fn open_dataset(
client: &NamespaceClient,
id: &str,
fallback: &FallbackOptions,
) -> Result<lance::Dataset> {
if id.contains("://") || id.starts_with('/') {
let mut builder = lance::dataset::builder::DatasetBuilder::from_uri(id);
if !fallback.is_empty() {
builder = builder.with_storage_options(fallback.clone());
}
return builder.load().await.with_context(|| format!("open {id}"));
}
let table = dataset::open(client, &parse_id(id), fallback).await?;
Ok(table.dataset)
}
#[tokio::main]
async fn main() -> Result<()> {
weed_lance_worker::tls::install_default_crypto_provider();
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
let args = Args::parse();
let mut fallback = FallbackOptions::new();
if let (Some(access), Some(secret)) = (args.access_key, args.secret_key) {
fallback.insert("aws_access_key_id".to_string(), access);
fallback.insert("aws_secret_access_key".to_string(), secret);
}
let client = NamespaceClient::new(args.namespace).with_fallback(&fallback);
match args.command {
Command::Describe {
id,
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &fallback).await?;
let schema: arrow_schema::Schema = dataset.schema().into();
let resolved =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref());
let vector = match resolved {
Err(e) if vector_column.is_some() || key_column.is_some() => return Err(e),
r => r.ok(),
};
let coverages = match &vector {
Some(v) => coverage::coverage(&dataset, &v.vector_column).await?,
None => Vec::new(),
};
println!(
"{}",
serde_json::json!({
"id": id,
"uri": dataset.uri(),
"version": dataset.version().version,
"fragments": dataset.get_fragments().len(),
"rows": dataset.count_rows(None).await?,
"schema": schema.fields().iter().map(|f| serde_json::json!({
"name": f.name(),
"type": f.data_type().to_string(),
"nullable": f.is_nullable(),
})).collect::<Vec<_>>(),
"vector": vector.map(|v| serde_json::json!({
"vector_column": v.vector_column,
"dimension": v.dimension,
"key_column": v.key_column,
"metadata_columns": v.metadata_columns,
})),
"coverage": coverages,
})
);
}
Command::Coverage {
id,
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &fallback).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
let coverages = coverage::coverage(&dataset, &vector.vector_column).await?;
println!("{}", serde_json::to_string_pretty(&coverages)?);
}
Command::Get {
id,
keys,
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &fallback).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
for batch in query::get(&dataset, &vector, &keys).await? {
println!("{}", arrow_cast::pretty::pretty_format_batches(&[batch])?);
}
}
Command::Query {
id,
vector,
k,
filter,
metric,
flat,
postfilter,
version,
vector_column,
key_column,
nprobes,
} => {
let opened = open_dataset(&client, &id, &fallback).await?;
let dataset = match version {
Some(v) => opened.checkout_version(v).await?,
None => opened,
};
let vector_table =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
let vector: Vec<f32> = vector
.split(',')
.map(|part| part.trim().parse::<f32>())
.collect::<std::result::Result<_, _>>()
.context("--vector takes comma-separated floats")?;
let distance = match metric.as_str() {
"l2" | "euclidean" => lance_linalg::distance::DistanceType::L2,
"cosine" => lance_linalg::distance::DistanceType::Cosine,
"dot" | "dotproduct" => lance_linalg::distance::DistanceType::Dot,
other => bail!("unknown metric {other}: l2, cosine or dot"),
};
let query = Query {
vector,
k,
filter,
postfilter,
distance,
nprobes,
};
let hits = if flat {
query::flat(&dataset, &vector_table, &query).await?
} else {
query::ann(&dataset, &vector_table, &query).await?
};
println!("{}", serde_json::to_string_pretty(&hits)?);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vector_flag_takes_hyphenated_floats() {
let args = Args::try_parse_from([
"weed-vector",
"query",
"t",
"--vector",
"-1,-1,-1,-1",
"--k",
"3",
])
.unwrap();
match args.command {
Command::Query { vector, k, .. } => {
assert_eq!(vector, "-1,-1,-1,-1");
assert_eq!(k, 3);
}
_ => panic!("expected query"),
}
}
#[test]
fn column_flags_on_get_describe_coverage() {
for argv in [
vec!["weed-vector", "get", "t", "k1"],
vec!["weed-vector", "describe", "t"],
vec!["weed-vector", "coverage", "t"],
] {
let mut argv = argv;
argv.extend(["--vector-column", "v", "--key-column", "kk"]);
let args = Args::try_parse_from(argv).unwrap();
let (v, k) = match args.command {
Command::Get {
vector_column,
key_column,
..
}
| Command::Describe {
vector_column,
key_column,
..
}
| Command::Coverage {
vector_column,
key_column,
..
} => (vector_column, key_column),
_ => panic!("unexpected subcommand"),
};
assert_eq!(v.as_deref(), Some("v"));
assert_eq!(k.as_deref(), Some("kk"));
}
}
}
+299
View File
@@ -0,0 +1,299 @@
//! Top-K queries over a [`VectorTable`]: exact flat scan, or the ANN index
//! with a flat pass over the fragments it does not cover yet.
use anyhow::{Context, Result, bail};
use arrow_array::{Array, Float32Array, RecordBatch, StringArray, UInt64Array};
use futures::TryStreamExt;
use lance::Dataset;
use lance::dataset::scanner::Scanner;
use lance_linalg::distance::DistanceType;
use crate::table::VectorTable;
const DISTANCE_COLUMN: &str = "_distance";
const ROW_ID_COLUMN: &str = "_rowid";
/// One vector search request.
#[derive(Debug, Clone)]
pub struct Query {
pub vector: Vec<f32>,
pub k: usize,
/// A Lance SQL filter over the metadata columns.
pub filter: Option<String>,
/// Filter the top-K rows after ranking instead of the eligible rows
/// before it. Lance's default post-filters and can return fewer than k
/// results while eligible neighbours go unreported; keep it off for
/// S3 Vectors filter semantics.
pub postfilter: bool,
pub distance: DistanceType,
pub nprobes: Option<usize>,
}
/// One row of a top-K answer.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hit {
/// The key column value, or the row id when the table has no key column.
pub key: String,
/// Raw Lance `_distance` in the query's metric.
pub distance: f32,
pub row_id: u64,
}
/// Exact top-K over every fragment, ignoring any index.
pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
run(scanner(dataset, table, query, false)?, table).await
}
/// Top-K with the ANN index where it covers the fragment and a flat pass over
/// the rest. Whether the index is used is Lance's decision per fragment, so
/// rows written after the last index build are always candidates.
pub async fn ann(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
run(scanner(dataset, table, query, true)?, table).await
}
/// Fetch rows by key.
pub async fn get(
dataset: &Dataset,
table: &VectorTable,
keys: &[String],
) -> Result<Vec<RecordBatch>> {
let Some(key_column) = &table.key_column else {
bail!("the table has no key column to look up");
};
if keys.is_empty() {
return Ok(Vec::new());
}
let list = keys
.iter()
.map(|k| format!("'{}'", k.replace('\'', "''")))
.collect::<Vec<_>>()
.join(", ");
let mut scanner = dataset.scan();
scanner
.filter(&format!("`{}` in ({list})", key_column.replace('`', "``")))?
.with_row_id();
scanner
.try_into_stream()
.await?
.try_collect()
.await
.context("scan by keys")
}
fn scanner(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
use_index: bool,
) -> Result<Scanner> {
if query.vector.len() != table.dimension {
bail!(
"query dim({}) does not match the table's dim({})",
query.vector.len(),
table.dimension
);
}
let vector = Float32Array::from(query.vector.clone());
let mut scanner = dataset.scan();
scanner
.nearest(&table.vector_column, &vector, query.k)?
.distance_metric(query.distance)
.use_index(use_index)
.with_row_id();
if let Some(filter) = &query.filter {
scanner.filter(filter)?;
scanner.prefilter(!query.postfilter);
}
if let Some(nprobes) = query.nprobes {
scanner.nprobes(nprobes);
}
let mut columns = Vec::new();
if let Some(key) = &table.key_column {
columns.push(key.clone());
}
columns.push(DISTANCE_COLUMN.to_string());
columns.push(ROW_ID_COLUMN.to_string());
scanner.project(&columns)?;
Ok(scanner)
}
async fn run(scanner: Scanner, table: &VectorTable) -> Result<Vec<Hit>> {
let mut stream = scanner.try_into_stream().await?;
let mut out = Vec::new();
while let Some(batch) = stream.try_next().await? {
out.extend(hits(&batch, table)?);
}
Ok(out)
}
fn hits(batch: &RecordBatch, table: &VectorTable) -> Result<Vec<Hit>> {
let distances = batch
.column_by_name(DISTANCE_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<Float32Array>())
.context("the scan did not return a _distance column")?;
let row_ids = batch
.column_by_name(ROW_ID_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<UInt64Array>())
.context("the scan did not return a _rowid column")?;
let keys = table.key_column.as_ref().and_then(|name| {
batch
.column_by_name(name)
.and_then(|c| c.as_any().downcast_ref::<StringArray>())
});
if table.key_column.is_some() && keys.is_none() {
bail!("key column did not come back as Utf8");
}
(0..batch.num_rows())
.map(|i| {
let key = match keys {
Some(keys) if !keys.is_null(i) => keys.value(i).to_string(),
Some(_) => bail!(
"key column {} has a null at row {i}",
table.key_column.as_deref().unwrap_or_default()
),
None => row_ids.value(i).to_string(),
};
Ok(Hit {
key,
distance: distances.value(i),
row_id: row_ids.value(i),
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::table::VectorTable;
use crate::testing::{DIM, write_dataset};
use tempfile::TempDir;
fn l2(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
}
#[tokio::test]
async fn flat_returns_exact_top_k() {
let dir = TempDir::new().unwrap();
let vectors = vec![
vec![1.0, 0.0, 0.0, 0.0],
vec![0.9, 0.1, 0.0, 0.0],
vec![0.0, 1.0, 0.0, 0.0],
vec![0.0, 0.0, 1.0, 0.0],
];
let dataset = write_dataset(&dir, &vectors, &["a", "b", "a", "b"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: vec![1.0, 0.0, 0.0, 0.0],
k: 2,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
};
let hits = flat(&dataset, &table, &query).await.unwrap();
assert_eq!(hits.len(), 2);
assert_eq!(hits[0].key, "k0");
assert!(hits[0].distance <= hits[1].distance);
let mut brute: Vec<(String, f32)> = vectors
.iter()
.enumerate()
.map(|(i, v)| (format!("k{i}"), l2(&query.vector, v)))
.collect();
brute.sort_by(|a, b| a.1.total_cmp(&b.1));
for (hit, (key, distance)) in hits.iter().zip(brute.iter()) {
assert_eq!(&hit.key, key);
assert!((hit.distance - distance).abs() < 1e-5);
}
}
#[tokio::test]
async fn flat_applies_the_filter() {
let dir = TempDir::new().unwrap();
let vectors = vec![
vec![1.0, 0.0, 0.0, 0.0],
vec![0.9, 0.1, 0.0, 0.0],
vec![0.0, 1.0, 0.0, 0.0],
];
let dataset = write_dataset(&dir, &vectors, &["a", "b", "a"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let hits = flat(
&dataset,
&table,
&Query {
vector: vec![1.0, 0.0, 0.0, 0.0],
k: 3,
filter: Some("tag = 'a'".to_string()),
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
},
)
.await
.unwrap();
assert_eq!(hits.len(), 2);
assert_eq!(hits[0].key, "k0");
assert_eq!(hits[1].key, "k2");
}
#[tokio::test]
async fn get_fetches_rows_by_key() {
let dir = TempDir::new().unwrap();
let vectors = vec![vec![1.0; DIM], vec![2.0; DIM], vec![3.0; DIM]];
let dataset = write_dataset(&dir, &vectors, &["a", "b", "c"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let batches = get(&dataset, &table, &["k0".to_string(), "k2".to_string()])
.await
.unwrap();
let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(rows, 2);
}
#[tokio::test]
async fn query_rejects_a_wrong_dimension() {
let dir = TempDir::new().unwrap();
let vectors = vec![vec![1.0; DIM]];
let dataset = write_dataset(&dir, &vectors, &["a"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: vec![1.0; DIM + 1],
k: 1,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
};
assert!(flat(&dataset, &table, &query).await.is_err());
}
#[tokio::test]
async fn ann_matches_flat_without_an_index() {
let dir = TempDir::new().unwrap();
let vectors = vec![
vec![1.0, 0.0, 0.0, 0.0],
vec![0.0, 1.0, 0.0, 0.0],
vec![0.0, 0.0, 1.0, 0.0],
];
let dataset = write_dataset(&dir, &vectors, &["a", "b", "c"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: vec![1.0, 0.0, 0.0, 0.0],
k: 2,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
};
let indexed = ann(&dataset, &table, &query).await.unwrap();
let exact = flat(&dataset, &table, &query).await.unwrap();
assert_eq!(
indexed.iter().map(|h| &h.key).collect::<Vec<_>>(),
exact.iter().map(|h| &h.key).collect::<Vec<_>>()
);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! The columns a vector query needs, resolved from a table's Arrow schema.
use anyhow::{Context, Result, bail};
use arrow_schema::DataType;
use lance::Dataset;
/// The default name for the vector column, matching what the S3 Vectors API
/// writes.
const DEFAULT_VECTOR_COLUMN: &str = "vector";
/// The default name for the key column.
const DEFAULT_KEY_COLUMN: &str = "key";
/// Layout of a Lance table used as a vector index.
#[derive(Debug, Clone)]
pub struct VectorTable {
/// The row key column; `None` falls back to `_rowid` in results.
pub key_column: Option<String>,
pub vector_column: String,
pub dimension: usize,
pub metadata_columns: Vec<String>,
}
impl VectorTable {
/// Resolve the vector layout of `dataset`. `vector_column` and
/// `key_column` override detection: the vector column defaults to the one
/// named `vector`, or the sole fixed-size float list when unambiguous.
pub fn resolve(
dataset: &Dataset,
vector_column: Option<&str>,
key_column: Option<&str>,
) -> Result<Self> {
let schema: arrow_schema::Schema = dataset.schema().into();
resolve_schema(&schema, vector_column, key_column)
}
}
pub(crate) fn resolve_schema(
schema: &arrow_schema::Schema,
vector_column: Option<&str>,
key_column: Option<&str>,
) -> Result<VectorTable> {
let vector_column = match vector_column {
Some(name) => name.to_string(),
None => detect_vector_column(schema)?,
};
let field = schema
.field_with_name(&vector_column)
.with_context(|| format!("no such column {vector_column}"))?;
let dimension = vector_dimension(field.data_type())
.with_context(|| format!("column {vector_column} is not a fixed-size float vector"))?;
let key_column = match key_column {
Some(name) => {
let field = schema
.field_with_name(name)
.with_context(|| format!("no such column {name}"))?;
if field.data_type() != &DataType::Utf8 {
bail!("key column {name} is not Utf8");
}
Some(name.to_string())
}
None => detect_key_column(schema),
};
let metadata_columns = schema
.fields()
.iter()
.map(|f| f.name().clone())
.filter(|name| name != &vector_column && Some(name) != key_column.as_ref())
.collect();
Ok(VectorTable {
key_column,
vector_column,
dimension,
metadata_columns,
})
}
fn detect_vector_column(schema: &arrow_schema::Schema) -> Result<String> {
let mut named = None;
let mut candidates = Vec::new();
for field in schema.fields() {
if vector_dimension(field.data_type()).is_none() {
continue;
}
if field.name() == DEFAULT_VECTOR_COLUMN {
named = Some(field.name().clone());
}
candidates.push(field.name().clone());
}
if let Some(name) = named {
return Ok(name);
}
match candidates.as_slice() {
[only] => Ok(only.clone()),
[] => bail!("no fixed-size float vector column found"),
many => bail!("several vector columns, pick one of: {}", many.join(", ")),
}
}
fn detect_key_column(schema: &arrow_schema::Schema) -> Option<String> {
schema
.field_with_name(DEFAULT_KEY_COLUMN)
.ok()
.filter(|f| f.data_type() == &DataType::Utf8)
.map(|f| f.name().clone())
}
fn vector_dimension(data_type: &DataType) -> Option<usize> {
let DataType::FixedSizeList(child, dimension) = data_type else {
return None;
};
match child.data_type() {
DataType::Float16 | DataType::Float32 | DataType::Float64 => Some(*dimension as usize),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use arrow_schema::{Field, Schema};
use std::sync::Arc;
fn vector_field(name: &str, dim: i32) -> Field {
Field::new(
name,
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), dim),
false,
)
}
#[test]
fn resolve_prefers_the_column_named_vector() {
let schema = Schema::new(vec![
Field::new("key", DataType::Utf8, false),
vector_field("embedding", 4),
vector_field("vector", 8),
Field::new("tag", DataType::Utf8, true),
]);
let table = resolve_schema(&schema, None, None).unwrap();
assert_eq!(table.vector_column, "vector");
assert_eq!(table.dimension, 8);
assert_eq!(table.key_column.as_deref(), Some("key"));
assert_eq!(table.metadata_columns, vec!["embedding", "tag"]);
}
#[test]
fn resolve_uses_the_sole_vector_column() {
let schema = Schema::new(vec![
vector_field("embedding", 4),
Field::new("tag", DataType::Utf8, true),
]);
let table = resolve_schema(&schema, None, None).unwrap();
assert_eq!(table.vector_column, "embedding");
assert_eq!(table.key_column, None);
}
#[test]
fn resolve_rejects_ambiguous_vector_columns() {
let schema = Schema::new(vec![vector_field("a", 4), vector_field("b", 4)]);
assert!(resolve_schema(&schema, None, None).is_err());
}
#[test]
fn resolve_rejects_a_non_vector_column() {
let schema = Schema::new(vec![
Field::new("vector", DataType::Utf8, true),
vector_field("embedding", 4),
]);
assert!(resolve_schema(&schema, Some("vector"), None).is_err());
let table = resolve_schema(&schema, None, Some("vector")).unwrap();
assert_eq!(table.vector_column, "embedding");
assert_eq!(table.key_column.as_deref(), Some("vector"));
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Small Lance datasets for the query and coverage tests.
use std::sync::Arc;
use arrow_array::{
FixedSizeListArray, RecordBatch, RecordBatchIterator, StringArray, types::Float32Type,
};
use arrow_schema::{DataType, Field, Schema};
use lance::Dataset;
use lance::dataset::WriteParams;
use tempfile::TempDir;
pub const DIM: usize = 4;
fn vector_column(vectors: &[Vec<f32>], dim: usize) -> FixedSizeListArray {
FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
vectors
.iter()
.map(|v| Some(v.iter().copied().map(Some).collect::<Vec<_>>())),
dim as i32,
)
}
pub fn schema(dim: usize) -> Arc<Schema> {
Arc::new(Schema::new(vec![
Field::new("key", DataType::Utf8, false),
Field::new(
"vector",
DataType::FixedSizeList(
Arc::new(Field::new("item", DataType::Float32, true)),
dim as i32,
),
false,
),
Field::new("tag", DataType::Utf8, true),
]))
}
pub fn batch(offset: usize, vectors: &[Vec<f32>], tags: &[&str], dim: usize) -> RecordBatch {
let keys: Vec<String> = (0..vectors.len())
.map(|i| format!("k{}", offset + i))
.collect();
RecordBatch::try_new(
schema(dim),
vec![
Arc::new(StringArray::from(keys)),
Arc::new(vector_column(vectors, dim)),
Arc::new(StringArray::from(
tags.iter().map(|t| Some(t.to_string())).collect::<Vec<_>>(),
)),
],
)
.unwrap()
}
pub async fn write_dataset(dir: &TempDir, vectors: &[Vec<f32>], tags: &[&str]) -> Dataset {
write_dataset_at(dir.path().to_str().unwrap(), vectors, tags).await
}
pub async fn write_dataset_at(uri: &str, vectors: &[Vec<f32>], tags: &[&str]) -> Dataset {
let dim = vectors[0].len();
let reader = RecordBatchIterator::new(
vec![Ok(batch(0, vectors, tags, dim))].into_iter(),
schema(dim),
);
Dataset::write(reader, uri, None).await.unwrap()
}
/// Deterministic non-trivial vectors for index coverage tests.
pub fn vectors(rows: usize, dim: usize) -> Vec<Vec<f32>> {
(0..rows)
.map(|i| {
(0..dim)
.map(|j| ((i * 31 + j * 17) % 97) as f32 / 97.0)
.collect()
})
.collect()
}
/// Commit a new version whose fragment is not yet covered by the index the
/// dataset had before.
pub async fn append_dataset(dataset: &mut Dataset, vectors: &[Vec<f32>], tags: &[&str]) {
let offset = dataset.count_rows(None).await.unwrap();
let dim = vectors[0].len();
let reader = RecordBatchIterator::new(
vec![Ok(batch(offset, vectors, tags, dim))].into_iter(),
schema(dim),
);
dataset
.append(reader, Some(WriteParams::default()))
.await
.unwrap();
}
+201
View File
@@ -0,0 +1,201 @@
//! The spike's exit gate: the engine's answers must equal what a bare Lance
//! `scan().nearest()` produces on the same pinned version, and no eligible
//! row — indexed or not — may be missing.
use arrow_array::{Float32Array, UInt64Array};
use futures::TryStreamExt;
use lance::Dataset;
use lance::index::DatasetIndexExt;
use lance::index::vector::VectorIndexParams;
use lance_index::IndexType;
use lance_index::optimize::OptimizeOptions;
use lance_linalg::distance::DistanceType;
use tempfile::TempDir;
use crate::coverage::coverage;
use crate::query::{self, Query};
use crate::table::VectorTable;
use crate::testing::{self, DIM};
async fn indexed_dataset(dir: &TempDir) -> Dataset {
let mut dataset = testing::write_dataset(dir, &testing::vectors(64, DIM), &["a"; 64]).await;
let params = VectorIndexParams::ivf_flat(4, DistanceType::L2);
dataset
.create_index(
&["vector"],
IndexType::Vector,
Some("vidx".to_string()),
&params,
true,
)
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
dataset
}
fn query_for(vector: Vec<f32>, k: usize) -> Query {
Query {
vector,
k,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
}
}
/// The reference path: a bare scanner over the same dataset handle.
async fn reference(dataset: &Dataset, vector: &[f32], k: usize) -> Vec<(u64, f32)> {
let mut scanner = dataset.scan();
scanner
.nearest("vector", &Float32Array::from(vector.to_vec()), k)
.unwrap()
.distance_metric(DistanceType::L2)
.nprobes(4)
.with_row_id();
let mut stream = scanner.try_into_stream().await.unwrap();
let mut rows = Vec::new();
while let Some(batch) = stream.try_next().await.unwrap() {
let ids = batch
.column_by_name("_rowid")
.unwrap()
.as_any()
.downcast_ref::<UInt64Array>()
.unwrap();
let distances = batch
.column_by_name("_distance")
.unwrap()
.as_any()
.downcast_ref::<Float32Array>()
.unwrap();
for i in 0..batch.num_rows() {
rows.push((ids.value(i), distances.value(i)));
}
}
rows
}
async fn assert_matches_reference(dataset: &Dataset, vector: &[f32], k: usize) {
let table = VectorTable::resolve(dataset, None, None).unwrap();
let hits = query::ann(dataset, &table, &query_for(vector.to_vec(), k))
.await
.unwrap();
let expected = reference(dataset, vector, k).await;
assert_eq!(hits.len(), expected.len());
for (hit, (row_id, distance)) in hits.iter().zip(expected.iter()) {
assert_eq!(hit.row_id, *row_id);
assert!((hit.distance - distance).abs() < 1e-6, "{}", hit.key);
}
}
#[tokio::test]
async fn ann_matches_lance_reference() {
let dir = TempDir::new().unwrap();
let dataset = indexed_dataset(&dir).await;
assert_matches_reference(&dataset, &testing::vectors(1, DIM)[0], 10).await;
}
#[tokio::test]
async fn ann_matches_reference_over_unindexed_fragments() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir).await;
testing::append_dataset(&mut dataset, &testing::vectors(8, DIM), &["a"; 8]).await;
let cov = &coverage(&dataset, "vector").await.unwrap()[0];
assert_eq!(cov.unindexed_fragments.len(), 1);
assert_eq!(cov.unindexed_rows, 8);
for vector in testing::vectors(4, DIM) {
assert_matches_reference(&dataset, &vector, 10).await;
}
}
#[tokio::test]
async fn ann_matches_reference_across_segments() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir).await;
testing::append_dataset(&mut dataset, &testing::vectors(32, DIM), &["a"; 32]).await;
dataset
.optimize_indices(&OptimizeOptions::append())
.await
.unwrap();
let cov = &coverage(&dataset, "vector").await.unwrap()[0];
assert_eq!(cov.segments, 2);
assert!(cov.unindexed_fragments.is_empty());
for vector in testing::vectors(4, DIM) {
assert_matches_reference(&dataset, &vector, 10).await;
}
}
#[tokio::test]
async fn deletes_are_not_returned() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir).await;
dataset.delete("key = 'k0'").await.unwrap();
assert_matches_reference(&dataset, &testing::vectors(1, DIM)[0], 10).await;
}
/// Writes a small indexed dataset with unindexed rows to
/// $WEED_VECTOR_SPIKE_DIR for exercising the `weed-vector` CLI:
///
/// WEED_VECTOR_SPIKE_DIR=/tmp/vds cargo test make_spike_dataset -- --ignored
/// weed-vector describe /tmp/vds
/// weed-vector coverage /tmp/vds
/// weed-vector query /tmp/vds --vector 0,0,0,0 --k 5
#[tokio::test]
#[ignore]
async fn make_spike_dataset() {
let dir = std::env::var("WEED_VECTOR_SPIKE_DIR").expect("set WEED_VECTOR_SPIKE_DIR");
let mut dataset = testing::write_dataset_at(&dir, &testing::vectors(64, DIM), &["a"; 64]).await;
let params = VectorIndexParams::ivf_flat(4, DistanceType::L2);
dataset
.create_index(
&["vector"],
IndexType::Vector,
Some("vidx".to_string()),
&params,
true,
)
.await
.unwrap();
dataset.checkout_latest().await.unwrap();
testing::append_dataset(&mut dataset, &testing::vectors(8, DIM), &["b"; 8]).await;
}
#[tokio::test]
async fn query_at_pinned_version_survives_maintenance() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir).await;
let pinned = dataset
.checkout_version(dataset.version().version)
.await
.unwrap();
testing::append_dataset(&mut dataset, &testing::vectors(8, DIM), &["b"; 8]).await;
dataset
.optimize_indices(&OptimizeOptions::default())
.await
.unwrap();
assert_eq!(pinned.count_rows(None).await.unwrap(), 64);
let vector = testing::vectors(1, DIM)[0].clone();
let hits = query::ann(
&pinned,
&VectorTable::resolve(&pinned, None, None).unwrap(),
&query_for(vector.clone(), 10),
)
.await
.unwrap();
let expected = reference(&pinned, &vector, 10).await;
assert_eq!(hits.len(), expected.len());
assert!(hits.iter().all(|h| h.row_id < 64));
for (hit, (row_id, distance)) in hits.iter().zip(expected.iter()) {
assert_eq!(hit.row_id, *row_id);
assert!((hit.distance - distance).abs() < 1e-6);
}
assert_matches_reference(&dataset, &vector, 10).await;
}
+42
View File
@@ -0,0 +1,42 @@
[package]
name = "weed-vector-server"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "VectorService gRPC server over SeaweedFS Lance table buckets"
[lib]
name = "weed_vector_server"
[[bin]]
name = "weed-vector-server"
path = "src/main.rs"
[dependencies]
weed-vector-core = { path = "../core" }
weed-lance-worker = { path = "../../../seaweed-worker/crates/lance" }
lance = { version = "10", default-features = false, features = ["aws"] }
lance-linalg = "10"
arrow-array = "58"
arrow-cast = "58"
arrow-schema = "58"
prost = "0.14"
prost-types = "0.14"
reqwest = { version = "0.12", default-features = false }
tonic = { version = "0.14", features = ["tls-aws-lc"] }
tonic-prost = "0.14"
anyhow.workspace = true
clap = { version = "4", features = ["derive", "env"] }
futures = "0.3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
[build-dependencies]
tonic-prost-build = "0.14"
protoc-bin-vendored = "3"
[lints]
workspace = true
+16
View File
@@ -0,0 +1,16 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var_os("PROTOC").is_none() {
// SAFETY: a build script's main runs single-threaded before anything
// else in this process, so no other thread can be reading the
// environment concurrently.
unsafe {
std::env::set_var("PROTOC", protoc_bin_vendored::protoc_bin_path()?);
}
}
tonic_prost_build::configure()
.build_server(true)
.build_client(true)
.compile_protos(&["../../../weed/pb/vector.proto"], &["../../../weed/pb/"])?;
println!("cargo:rerun-if-changed=../../../weed/pb/vector.proto");
Ok(())
}
+9
View File
@@ -0,0 +1,9 @@
//! The VectorService gRPC server the S3 gateway talks to.
pub mod service;
pub mod pb {
pub mod vector {
tonic::include_proto!("vector_pb");
}
}
+47
View File
@@ -0,0 +1,47 @@
use anyhow::Result;
use clap::Parser;
use tonic::transport::Server;
use weed_lance_worker::catalog::NamespaceClient;
use weed_lance_worker::dataset::FallbackOptions;
use weed_vector_server::pb::vector::vector_service_server::VectorServiceServer;
use weed_vector_server::service::VectorServer;
/// The VectorService the S3 gateway fans vector calls out to.
#[derive(Parser)]
struct Args {
/// Lance Namespace base URL, e.g. http://localhost:8888/lance.
#[arg(
long,
env = "WEED_VECTOR_NAMESPACE",
default_value = "http://localhost:8888/lance"
)]
namespace: String,
/// gRPC listen address.
#[arg(long, env = "WEED_VECTOR_LISTEN", default_value = "127.0.0.1:8080")]
listen: String,
/// object_store option fallback for deployments that vend no credentials:
/// key=value, repeatable.
#[arg(long = "storage-option", value_parser = parse_option)]
storage_options: Vec<(String, String)>,
}
fn parse_option(s: &str) -> Result<(String, String), String> {
s.split_once('=')
.map(|(k, v)| (k.to_string(), v.to_string()))
.ok_or_else(|| "expected key=value".to_string())
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse();
let fallback: FallbackOptions = args.storage_options.into_iter().collect();
let client = NamespaceClient::new(args.namespace.clone()).with_fallback(&fallback);
let service = VectorServer::new(client, fallback);
tracing::info!(namespace = %args.namespace, listen = %args.listen, "weed-vector-server");
Server::builder()
.add_service(VectorServiceServer::new(service))
.serve(args.listen.parse()?)
.await?;
Ok(())
}
+615
View File
@@ -0,0 +1,615 @@
use anyhow::{Result, bail};
use arrow_array::{Array, ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use futures::TryStreamExt;
use lance::Dataset;
use lance::dataset::ProjectionRequest;
use lance::dataset::WriteParams;
use lance::dataset::{MergeInsertBuilder, WhenMatched, WhenNotMatched};
use lance::io::ObjectStoreParams;
use lance::io::StorageOptionsAccessor;
use lance_linalg::distance::DistanceType;
use prost_types::{ListValue, Struct, Value, value::Kind};
use std::collections::BTreeMap;
use std::sync::Arc;
use tonic::{Request, Response, Status};
use weed_lance_worker::catalog::NamespaceClient;
use weed_lance_worker::dataset::{self, FallbackOptions};
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
use crate::pb::vector::{self as pb, vector_service_server::VectorService};
fn internal(err: impl Into<anyhow::Error>) -> Status {
Status::internal(format!("{:#}", err.into()))
}
fn invalid(err: impl Into<anyhow::Error>) -> Status {
Status::invalid_argument(format!("{:#}", err.into()))
}
fn open_status(err: anyhow::Error) -> Status {
let missing = err.chain().any(|cause| {
cause
.downcast_ref::<reqwest::Error>()
.is_some_and(|e| e.status() == Some(reqwest::StatusCode::NOT_FOUND))
|| cause.downcast_ref::<lance::Error>().is_some_and(|e| {
matches!(
e,
lance::Error::DatasetNotFound { .. }
| lance::Error::NotFound { .. }
| lance::Error::VersionNotFound { .. }
)
})
});
if missing {
Status::not_found(format!("{:#}", err))
} else {
Status::unavailable(format!("{:#}", err))
}
}
const KEY_COLUMN: &str = "key";
const METADATA_COLUMN: &str = "metadata";
const VECTOR_COLUMN: &str = "vector";
fn schema_for(
dimension: usize,
metric: pb::DistanceMetric,
non_filterable: &[String],
) -> Arc<Schema> {
let vector_field = Field::new(
VECTOR_COLUMN,
DataType::FixedSizeList(
Arc::new(Field::new("item", DataType::Float32, false)),
dimension as i32,
),
false,
)
.with_metadata(
[(
"distance_metric".to_string(),
metric.as_str_name().to_string(),
)]
.into_iter()
.collect(),
);
let mut metadata_field = Field::new(METADATA_COLUMN, DataType::Utf8, true);
if !non_filterable.is_empty() {
metadata_field = metadata_field.with_metadata(
[(
"non_filterable_metadata_keys".to_string(),
serde_json::to_string(non_filterable).unwrap_or_default(),
)]
.into_iter()
.collect(),
);
}
Arc::new(Schema::new(vec![
Field::new(KEY_COLUMN, DataType::Utf8, false),
vector_field,
metadata_field,
]))
}
fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Result<RecordBatch> {
let mut seen = std::collections::HashSet::new();
for vector in vectors {
if !seen.insert(vector.key.as_str()) {
bail!("duplicate key in request: {}", vector.key);
}
}
let keys = StringArray::from(vectors.iter().map(|v| v.key.as_str()).collect::<Vec<_>>());
// Check every vector's length before flattening: equal totals would
// still let a short vector borrow from the next one's values.
if vectors.iter().any(|v| v.data.len() != dimension) {
bail!("a vector's data length does not match the index dimension");
}
let flat = vectors
.iter()
.flat_map(|v| v.data.iter().copied())
.collect::<Vec<_>>();
let values: ArrayRef = Arc::new(Float32Array::from(flat));
let vectors_array = FixedSizeListArray::try_new(
Field::new("item", DataType::Float32, false).into(),
dimension as i32,
values,
None,
)?;
let metas = vectors
.iter()
.map(|v| {
v.metadata
.as_ref()
.map(|m| serde_json::to_string(&struct_to_json(m)))
.transpose()
})
.collect::<Result<Vec<_>, _>>()?;
RecordBatch::try_new(
schema,
vec![
Arc::new(keys),
Arc::new(vectors_array),
Arc::new(StringArray::from(metas)),
],
)
.map_err(Into::into)
}
fn struct_to_json(s: &Struct) -> serde_json::Value {
serde_json::Value::Object(
s.fields
.iter()
.map(|(k, v)| (k.clone(), value_to_json(v)))
.collect(),
)
}
fn value_to_json(v: &Value) -> serde_json::Value {
match &v.kind {
None | Some(Kind::NullValue(_)) => serde_json::Value::Null,
Some(Kind::NumberValue(n)) => serde_json::json!(n),
Some(Kind::StringValue(s)) => serde_json::json!(s),
Some(Kind::BoolValue(b)) => serde_json::json!(b),
Some(Kind::StructValue(s)) => struct_to_json(s),
Some(Kind::ListValue(l)) => {
serde_json::Value::Array(l.values.iter().map(value_to_json).collect())
}
}
}
fn json_to_value(v: serde_json::Value) -> Value {
let kind = match v {
serde_json::Value::Null => Kind::NullValue(0),
serde_json::Value::Bool(b) => Kind::BoolValue(b),
serde_json::Value::Number(n) => Kind::NumberValue(n.as_f64().unwrap_or(0.0)),
serde_json::Value::String(s) => Kind::StringValue(s),
serde_json::Value::Array(items) => Kind::ListValue(ListValue {
values: items.into_iter().map(json_to_value).collect(),
}),
serde_json::Value::Object(map) => Kind::StructValue(json_to_struct(map)),
};
Value { kind: Some(kind) }
}
fn json_to_struct(map: serde_json::Map<String, serde_json::Value>) -> Struct {
Struct {
fields: map
.into_iter()
.map(|(k, v)| (k, json_to_value(v)))
.collect::<BTreeMap<_, _>>(),
}
}
fn parse_struct(s: &str) -> Result<Struct> {
let v: serde_json::Value = serde_json::from_str(s)?;
match v {
serde_json::Value::Object(map) => Ok(json_to_struct(map)),
_ => bail!("metadata is not a JSON object"),
}
}
fn key_list(keys: &[String]) -> String {
format!(
"`{KEY_COLUMN}` in ({})",
keys.iter()
.map(|k| format!("'{}'", k.replace('\'', "''")))
.collect::<Vec<_>>()
.join(", ")
)
}
fn rows_as_vectors(
batches: &[RecordBatch],
return_data: bool,
return_metadata: bool,
) -> Vec<pb::Vector> {
let mut out = Vec::new();
for batch in batches {
let Some(keys) = batch
.column_by_name(KEY_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<StringArray>())
else {
continue;
};
let vectors = batch
.column_by_name(VECTOR_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<FixedSizeListArray>());
let metas = batch
.column_by_name(METADATA_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<StringArray>());
for i in 0..batch.num_rows() {
let data = match (return_data, vectors) {
(true, Some(list)) => list
.value(i)
.as_any()
.downcast_ref::<Float32Array>()
.map(|a| a.values().to_vec())
.unwrap_or_default(),
_ => Vec::new(),
};
let metadata = match (return_metadata, metas) {
(true, Some(m)) if !m.is_null(i) => parse_struct(m.value(i)).ok(),
_ => None,
};
out.push(pb::Vector {
key: keys.value(i).to_string(),
data,
metadata,
});
}
}
out
}
pub struct VectorServer {
client: NamespaceClient,
fallback: FallbackOptions,
}
impl VectorServer {
pub fn new(client: NamespaceClient, fallback: FallbackOptions) -> Self {
Self { client, fallback }
}
async fn open(&self, table: &pb::Table) -> Result<Dataset> {
let opened = dataset::open(&self.client, &table.id, &self.fallback).await?;
let mut dataset = opened.dataset;
if table.version != 0 {
dataset = dataset.checkout_version(table.version).await?;
}
Ok(dataset)
}
}
#[tonic::async_trait]
impl VectorService for VectorServer {
async fn create_index(
&self,
request: Request<pb::CreateIndexRequest>,
) -> Result<Response<pb::CreateIndexResponse>, Status> {
let req = request.into_inner();
let metric = req.distance_metric();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dimension = req.dimension as usize;
// S3 Vectors caps at 4096; reject beyond it instead of letting an
// oversized request build a huge Arrow schema.
if dimension == 0 || dimension > 4096 {
return Err(Status::invalid_argument("dimension must be 1..=4096"));
}
let description = self
.client
.declare_table(&table.id, None)
.await
.map_err(internal)?;
let mut options = self.fallback.clone();
options.extend(description.storage_options.clone());
let schema = schema_for(dimension, metric, &req.non_filterable_metadata_keys);
let empty = RecordBatch::new_empty(schema.clone());
let reader = arrow_array::RecordBatchIterator::new(vec![Ok(empty)].into_iter(), schema);
let dataset = Dataset::write(
reader,
&description.location,
Some(WriteParams {
store_params: Some(ObjectStoreParams {
storage_options_accessor: Some(Arc::new(
StorageOptionsAccessor::with_static_options(options),
)),
..Default::default()
}),
..Default::default()
}),
)
.await
.map_err(internal)?;
Ok(Response::new(pb::CreateIndexResponse {
version: dataset.version().version,
}))
}
async fn drop_index(
&self,
_request: Request<pb::DropIndexRequest>,
) -> Result<Response<pb::DropIndexResponse>, Status> {
// Dropping is a catalog decision; the gateway deletes the table record.
Err(Status::unimplemented("drop through the catalog"))
}
async fn put_vectors(
&self,
request: Request<pb::PutVectorsRequest>,
) -> Result<Response<pb::PutVectorsResponse>, Status> {
let req = request.into_inner();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open(&table).await.map_err(open_status)?;
if req.vectors.is_empty() {
return Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
}));
}
let dimension = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN))
.map_err(invalid)?
.dimension;
let batch = batch_of(
&req.vectors,
dimension,
Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema())),
)
.map_err(invalid)?;
// Upsert by key in one merge commit: no window where the old rows are
// already deleted, and a losing writer fails the request instead of
// leaving duplicate keys.
let mut builder =
MergeInsertBuilder::try_new(Arc::new(dataset), vec![KEY_COLUMN.to_string()])
.map_err(internal)?;
builder.when_matched(WhenMatched::UpdateAll);
builder.when_not_matched(WhenNotMatched::InsertAll);
let (dataset, _stats) = builder
.try_build()
.map_err(internal)?
.execute_batches(vec![batch])
.await
.map_err(internal)?;
Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
}))
}
async fn get_vectors(
&self,
request: Request<pb::GetVectorsRequest>,
) -> Result<Response<pb::GetVectorsResponse>, Status> {
let req = request.into_inner();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open(&table).await.map_err(open_status)?;
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
let batches = query::get(&dataset, &resolved, &req.keys)
.await
.map_err(internal)?;
Ok(Response::new(pb::GetVectorsResponse {
vectors: rows_as_vectors(&batches, req.return_data, req.return_metadata),
}))
}
async fn delete_vectors(
&self,
request: Request<pb::DeleteVectorsRequest>,
) -> Result<Response<pb::DeleteVectorsResponse>, Status> {
let req = request.into_inner();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let mut dataset = self.open(&table).await.map_err(open_status)?;
if !req.keys.is_empty() {
dataset
.delete(&key_list(&req.keys))
.await
.map_err(internal)?;
}
Ok(Response::new(pb::DeleteVectorsResponse {
version: dataset.version().version,
}))
}
async fn list_vectors(
&self,
request: Request<pb::ListVectorsRequest>,
) -> Result<Response<pb::ListVectorsResponse>, Status> {
let req = request.into_inner();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open(&table).await.map_err(open_status)?;
let offset: u64 = if req.next_token.is_empty() {
0
} else {
req.next_token
.parse()
.map_err(|_| Status::invalid_argument("invalid next_token"))?
};
let mut columns = vec![KEY_COLUMN.to_string()];
if req.return_data {
columns.push(VECTOR_COLUMN.to_string());
}
if req.return_metadata {
columns.push(METADATA_COLUMN.to_string());
}
// An unset max_results arrives as 0; page it like S3 Vectors does.
const DEFAULT_PAGE: u32 = 500;
const MAX_PAGE: u32 = 1000;
let page = match req.max_results {
0 => DEFAULT_PAGE,
n => n.min(MAX_PAGE),
};
let mut scanner = dataset.scan();
scanner
.project(&columns)
.map_err(internal)?
.limit(Some(page as i64), Some(offset as i64))
.map_err(internal)?;
let batches: Vec<RecordBatch> = scanner
.try_into_stream()
.await
.map_err(internal)?
.try_collect()
.await
.map_err(internal)?;
let rows = batches.iter().map(|b| b.num_rows()).sum::<usize>();
let next = offset + rows as u64;
let next_token = if rows == page as usize && rows > 0 {
next.to_string()
} else {
String::new()
};
Ok(Response::new(pb::ListVectorsResponse {
vectors: rows_as_vectors(&batches, req.return_data, req.return_metadata),
next_token,
}))
}
async fn query_vectors(
&self,
request: Request<pb::QueryVectorsRequest>,
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
let req = request.into_inner();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open(&table).await.map_err(open_status)?;
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
if req.query_vector.len() != resolved.dimension {
return Err(Status::invalid_argument(format!(
"query vector carries {} floats, the index dimension is {}",
req.query_vector.len(),
resolved.dimension
)));
}
if req.top_k == 0 {
return Err(Status::invalid_argument("top_k must be positive"));
}
// The index's configured metric lives in the vector field's metadata.
let distance = match dataset
.schema()
.field(VECTOR_COLUMN)
.and_then(|f| f.metadata.get("distance_metric").map(String::as_str))
{
Some("COSINE") => DistanceType::Cosine,
Some("DOT_PRODUCT") => DistanceType::Dot,
_ => DistanceType::L2,
};
let query = Query {
vector: req.query_vector,
k: req.top_k as usize,
filter: if req.filter.is_empty() {
None
} else {
Some(req.filter)
},
postfilter: req.postfilter,
distance,
nprobes: None,
};
let hits = query::ann(&dataset, &resolved, &query)
.await
.map_err(internal)?;
// One batched read for every hit's columns; keyed by the hit key so
// row order does not matter.
let mut metas: std::collections::HashMap<String, Option<Struct>> =
std::collections::HashMap::new();
let mut data_map: std::collections::HashMap<String, Vec<f32>> =
std::collections::HashMap::new();
if (req.return_metadata || req.return_data) && !hits.is_empty() {
let row_ids: Vec<u64> = hits.iter().map(|h| h.row_id).collect();
let mut columns = vec![KEY_COLUMN];
if req.return_metadata {
columns.push(METADATA_COLUMN);
}
if req.return_data {
columns.push(VECTOR_COLUMN);
}
let batch = dataset
.take_rows(
&row_ids,
ProjectionRequest::from_columns(columns, dataset.schema()),
)
.await
.map_err(internal)?;
let keys = batch
.column_by_name(KEY_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<StringArray>());
let meta_col = batch
.column_by_name(METADATA_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<StringArray>());
let data_col = batch
.column_by_name(VECTOR_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<FixedSizeListArray>());
if let Some(keys) = keys {
for i in 0..batch.num_rows() {
let key = keys.value(i).to_string();
if let Some(meta_col) = meta_col {
metas.insert(
key.clone(),
if meta_col.is_null(i) {
None
} else {
parse_struct(meta_col.value(i)).ok()
},
);
}
if let Some(data_col) = data_col {
data_map.insert(
key,
data_col
.value(i)
.as_any()
.downcast_ref::<Float32Array>()
.map(|a| a.values().to_vec())
.unwrap_or_default(),
);
}
}
}
}
let mut vectors = Vec::with_capacity(hits.len());
for hit in &hits {
vectors.push(pb::QueryResult {
key: hit.key.clone(),
distance: if req.return_distance {
hit.distance
} else {
0.0
},
metadata: metas.remove(&hit.key).flatten(),
data: data_map.remove(&hit.key).unwrap_or_default(),
});
}
Ok(Response::new(pb::QueryVectorsResponse { vectors }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn batch_of_rejects_a_ragged_vector() {
let vectors = vec![
pb::Vector {
key: "a".to_string(),
data: vec![1.0, 2.0],
metadata: None,
},
pb::Vector {
key: "b".to_string(),
data: vec![1.0; 4],
metadata: None,
},
];
let schema = schema_for(4, pb::DistanceMetric::L2, &[]);
assert!(batch_of(&vectors, 4, schema).is_err());
}
#[test]
fn batch_of_rejects_a_repeated_key() {
let schema = schema_for(4, pb::DistanceMetric::L2, &[]);
let vectors = vec![
pb::Vector {
key: "a".to_string(),
data: vec![1.0; 4],
metadata: None,
},
pb::Vector {
key: "a".to_string(),
data: vec![2.0; 4],
metadata: None,
},
];
assert!(batch_of(&vectors, 4, schema).is_err());
}
}
+1
View File
@@ -4601,6 +4601,7 @@ dependencies = [
"futures",
"hex",
"http-body 1.0.1",
"httpdate",
"hyper",
"hyper-util",
"image",
+1
View File
@@ -51,6 +51,7 @@ prost-types = "0.14"
# HTTP server
axum = { version = "0.8", features = ["multipart"] }
http-body = "1"
httpdate = "1"
hyper = { version = "1", features = ["full"] }
hyper-util = { version = "0.1", features = ["tokio", "service", "server-auto", "http1", "http2"] }
tower = { version = "0.5", features = ["util"] }
+19
View File
@@ -352,6 +352,25 @@ pub enum MinFreeSpace {
Bytes(u64),
}
impl MinFreeSpace {
/// Mirrors Go's MinFreeSpace.IsLow.
pub fn is_low(&self, free_bytes: u64, total_bytes: u64) -> bool {
match self {
MinFreeSpace::Percent(pct) => free_bytes as f64 / total_bytes as f64 * 100.0 < *pct,
MinFreeSpace::Bytes(min) => free_bytes < *min,
}
}
/// Free bytes above the floor; mirrors Go's MinFreeSpace.AvailableSpace.
pub fn available_space(&self, free_bytes: u64, total_bytes: u64) -> u64 {
let floor = match self {
MinFreeSpace::Percent(pct) => (total_bytes as f64 * pct / 100.0) as u64,
MinFreeSpace::Bytes(min) => *min,
};
free_bytes.saturating_sub(floor)
}
}
/// Convert single-dash long options to double-dash for clap compatibility.
/// Go's `flag` package uses `-port`, clap expects `--port`.
/// This allows both `-port 8080` and `--port 8080` to work.
+149 -63
View File
@@ -20,7 +20,9 @@ use crate::storage::erasure_coding::ec_shard::{ShardId, shard_id_try_from};
use crate::storage::erasure_coding::ecj_merge::EcjIdDecoder;
use crate::storage::needle::needle::{self, Needle};
use crate::storage::types::*;
use crate::storage::volume::VolumeSpec;
use crate::storage::volume::{
PREALLOCATE_SUPPORTED, VolumeSpec, allocated_file_size, preallocate_file,
};
use super::grpc_client::{
GrpcDialOptions, VolumeServerGrpcClient, connect_channel, connect_channel_guarded,
@@ -2067,8 +2069,13 @@ impl VolumeServer for VolumeGrpcService {
let source_status_before =
fetch_source_status_before(&mut client, req.volume_id, vid).await;
let source = SourceVolumeStatus::fetch(&mut client, req.volume_id).await?;
let dest = self.plan_copy_destination(&req, vid, &source, had_existing_volume)?;
dest.write_note(vid, &req.source_data_node)?;
let preallocate_size = self.copy_preallocate_size(&source).await;
let dest =
self.plan_copy_destination(&req, vid, &source, had_existing_volume, preallocate_size)?;
if let Err(e) = dest.write_note(vid, &req.source_data_node) {
dest.release_reservation(&self.state.store.read().unwrap());
return Err(e);
}
let (tx, rx) =
tokio::sync::mpsc::channel::<Result<volume_server_pb::VolumeCopyResponse, Status>>(16);
@@ -2079,6 +2086,7 @@ impl VolumeServer for VolumeGrpcService {
source,
source_status_before,
dest,
preallocate_size,
tx,
};
@@ -2088,8 +2096,11 @@ impl VolumeServer for VolumeGrpcService {
// races a departing caller is the one case where the existing
// file-only cleanup leaves the volume loaded in memory.
let mut mounted = false;
if let Err(e) = job.run(&mut client, &mut mounted).await {
job.cleanup_failed_copy(e, mounted).await;
match job.run(&mut client, &mut mounted).await {
Ok(()) => job
.dest
.commit_reservation(&job.state.store.read().unwrap()),
Err(e) => job.cleanup_failed_copy(e, mounted).await,
}
});
@@ -5625,6 +5636,11 @@ struct CopyDestination {
disk_type: DiskType,
/// A remote-backed volume only lands its .idx/.vif locally; the .dat stays in the tier.
has_remote_dat: bool,
/// The disk and headroom charge held by reserve_free_location; the copy
/// settles it as its bytes land on disk, and a failed copy releases only
/// what is still promised.
loc_idx: usize,
reserved_space: std::sync::atomic::AtomicU64,
}
impl CopyDestination {
@@ -5640,6 +5656,27 @@ impl CopyDestination {
.map_err(|e| Status::internal(format!("write .note for volume {}: {}", vid, e)))?;
Ok(())
}
/// Bytes the copy put on disk stop needing the headroom charge, so a
/// slow copy does not count its own .dat against the free space a
/// second reservation needs.
fn settle_reservation(&self, store: &crate::storage::store::Store, n: u64) {
let n = n.min(self.reserved_space.load(Ordering::Relaxed));
if n > 0 {
store.commit_free_location(self.loc_idx, n);
self.reserved_space.fetch_sub(n, Ordering::Relaxed);
}
}
fn release_reservation(&self, store: &crate::storage::store::Store) {
store.release_free_location(self.loc_idx, self.reserved_space.swap(0, Ordering::Relaxed));
}
/// The copied bytes are on disk now, so the pending charge ends without
/// refunding the cache — the charge and the landed usage cancel out.
fn commit_reservation(&self, store: &crate::storage::store::Store) {
store.commit_free_location(self.loc_idx, self.reserved_space.swap(0, Ordering::Relaxed));
}
}
impl VolumeGrpcService {
@@ -5674,6 +5711,36 @@ impl VolumeGrpcService {
Ok(volume_server_client(channel))
}
/// Query master for the .dat reservation a copy will make, as Go's
/// VolumeCopy does before picking a destination. A remote-backed volume
/// lands no .dat, so only a local copy needs the reservation.
async fn copy_preallocate_size(&self, source: &SourceVolumeStatus) -> i64 {
let has_remote_dat = source
.volume_info
.as_ref()
.map(|vi| !vi.files.is_empty())
.unwrap_or(false);
if !has_remote_dat {
let master = self.state.current_master().await;
let grpc_addr = super::heartbeat::to_grpc_address(&master);
match super::heartbeat::try_get_master_configuration(
&grpc_addr,
self.state.outgoing_grpc_tls.as_ref(),
)
.await
{
Ok(resp) if resp.volume_preallocate => {
return resp.volume_size_limit_m_b as i64 * 1024 * 1024;
}
Ok(_) => {}
Err(e) => {
tracing::warn!("get master {} configuration: {}", master, e);
}
}
}
0
}
/// Picks the destination disk and, under the same write lock, drops a
/// pre-existing local replica so its slot counts as free for the pick.
fn plan_copy_destination(
@@ -5682,6 +5749,7 @@ impl VolumeGrpcService {
vid: VolumeId,
vol_info: &SourceVolumeStatus,
had_existing_volume: bool,
preallocate_size: i64,
) -> Result<CopyDestination, Status> {
let requested_disk_type = if !req.disk_type.is_empty() {
DiskType::from_string(&req.disk_type)
@@ -5694,17 +5762,24 @@ impl VolumeGrpcService {
.as_ref()
.map(|vi| !vi.files.is_empty())
.unwrap_or(false);
let needed_space = if has_remote_dat {
let mut needed_space = if has_remote_dat {
vol_info.idx_file_size
} else {
vol_info.dat_file_size
};
if !has_remote_dat && PREALLOCATE_SUPPORTED && preallocate_size as u64 > needed_space {
// the .dat reserves the master's volume size limit up front, so
// the location must fit the reservation, not just the copied
// bytes (Go's neededSpace)
needed_space = preallocate_size as u64;
}
// Find a free disk location using Go's Store.FindFreeLocation
// Find a free disk location using Go's Store.ReserveFreeLocation
// semantics; the slot of the replica being replaced counts as free.
let (data_base, idx_base, selected_disk_type) = {
let ((data_base, idx_base, selected_disk_type), loc_idx) = {
let mut store = self.state.store.write().unwrap();
let Some(loc_idx) = store.find_free_location_predicate(
let Some(loc_idx) = store.reserve_free_location(
needed_space,
|loc| {
loc.disk_type == requested_disk_type
&& loc.available_space.load(Ordering::Relaxed) > needed_space
@@ -5723,9 +5798,12 @@ impl VolumeGrpcService {
loc.disk_type.clone(),
);
if had_existing_volume {
delete_existing_replica(&mut store, vid, vol_info)?;
if let Err(e) = delete_existing_replica(&mut store, vid, vol_info) {
store.release_free_location(loc_idx, needed_space);
return Err(e);
}
}
selected
(selected, loc_idx)
};
if had_existing_volume {
self.state.volume_state_notify.notify_one();
@@ -5741,6 +5819,8 @@ impl VolumeGrpcService {
idx_base_name,
disk_type: selected_disk_type,
has_remote_dat,
loc_idx,
reserved_space: std::sync::atomic::AtomicU64::new(needed_space),
})
}
}
@@ -5753,6 +5833,7 @@ struct VolumeCopyJob {
source: SourceVolumeStatus,
source_status_before: Option<volume_server_pb::VolumeStatusResponse>,
dest: CopyDestination,
preallocate_size: i64,
tx: tokio::sync::mpsc::Sender<Result<volume_server_pb::VolumeCopyResponse, Status>>,
}
@@ -5782,15 +5863,24 @@ impl VolumeCopyJob {
};
let mut throttler = WriteThrottler::new(io_byte_per_second);
self.preallocate_dat().await?;
let dat_on_disk = self.preallocate_dat().await?;
let dest = &self.dest;
let store = &self.state.store;
let mut settle = |landed: i64| {
if landed > 0 {
dest.settle_reservation(&store.read().unwrap(), landed as u64);
}
};
let mut progress = CopyProgress {
tx,
next_report_target: &mut next_report_target,
report_interval,
throttler: &mut throttler,
settle: &mut settle,
};
self.transfer_files(client, &mut progress).await?;
self.transfer_files(client, &mut progress, dat_on_disk)
.await?;
let source_status_after =
fetch_source_status_after(client, self.req.volume_id, vid, tx).await?;
@@ -5799,64 +5889,39 @@ impl VolumeCopyJob {
.await
}
/// Query master for preallocation settings (matching Go VolumeCopy behavior).
async fn preallocate_dat(&self) -> Result<(), Status> {
let (state, vid, tx) = (&self.state, self.vid, &self.tx);
/// Reserve the .dat's full size up front, matching Go's VolumeCopy
/// CreateVolumeFile. Returns the bytes the filesystem actually holds —
/// settled at once, since statfs already counts them — which a failed
/// fallocate reports as 0 so the write progress settles them instead.
async fn preallocate_dat(&self) -> Result<u64, Status> {
let (data_base_name, has_remote_dat) =
(&self.dest.data_base_name, self.dest.has_remote_dat);
let mut preallocate_size: i64 = 0;
if !has_remote_dat {
let master = state.current_master().await;
let grpc_addr = super::heartbeat::to_grpc_address(&master);
// Race the master-configuration RPC against the caller's
// response channel: a stalled master (or a slow leader
// election) would otherwise hold the task and its .note
// past a departing caller, since the per-chunk checks in
// copy_file_from_source are never reached.
let config = tokio::select! {
res = super::heartbeat::try_get_master_configuration(
&grpc_addr,
state.outgoing_grpc_tls.as_ref(),
) => res,
_ = tx.closed() => {
return Err(Status::cancelled(format!(
"volume {} copy cancelled by caller",
vid
)));
}
};
match config {
Ok(resp) => {
if resp.volume_preallocate {
preallocate_size = resp.volume_size_limit_m_b as i64 * 1024 * 1024;
}
}
Err(e) => {
tracing::warn!("get master {} configuration: {}", master, e);
}
}
if preallocate_size > 0 {
let dat_path = format!("{}.dat", data_base_name);
let file = std::fs::File::create(&dat_path).map_err(|e| {
Status::internal(format!(
"create preallocated volume file {}: {}",
dat_path, e
))
})?;
file.set_len(preallocate_size as u64).map_err(|e| {
Status::internal(format!("preallocate volume file {}: {}", dat_path, e))
})?;
}
let preallocate_size = self.preallocate_size;
if preallocate_size <= 0 || has_remote_dat {
return Ok(0);
}
Ok(())
let dat_path = format!("{}.dat", data_base_name);
let file = std::fs::File::create(&dat_path).map_err(|e| {
Status::internal(format!(
"create preallocated volume file {}: {}",
dat_path, e
))
})?;
preallocate_file(&file, preallocate_size as u64);
let allocated = allocated_file_size(&file);
self.dest
.settle_reservation(&self.state.store.read().unwrap(), allocated);
Ok(allocated)
}
/// Pull the .dat (unless it stays in the remote tier), .idx and .vif.
/// dat_on_disk is how much of the .dat statfs already counts, so only
/// writes past it settle the charge.
async fn transfer_files(
&self,
client: &mut VolumeServerGrpcClient,
progress: &mut CopyProgress<'_>,
dat_on_disk: u64,
) -> Result<(), Status> {
let (req, vol_info) = (&self.req, &self.source);
let (data_base_name, idx_base_name, has_remote_dat) = (
@@ -5864,7 +5929,9 @@ impl VolumeCopyJob {
&self.dest.idx_base_name,
self.dest.has_remote_dat,
);
// Copy .dat file
// Copy .dat file. Writing in place into the just-preallocated file
// keeps its fallocated blocks — truncating would free them at open
// and re-spend the headroom as the bytes stream back in.
if !has_remote_dat {
let dat_path = format!("{}.dat", data_base_name);
let dat_modified_ts_ns = copy_file_from_source(
@@ -5877,9 +5944,10 @@ impl VolumeCopyJob {
stop_offset: vol_info.dat_file_size,
dest_path: &dat_path,
ext: ".dat",
is_append: false,
is_append: self.preallocate_size > 0,
ignore_source_not_found: true,
report_progress: true,
settle_skip: dat_on_disk as i64,
},
progress,
)
@@ -5904,6 +5972,7 @@ impl VolumeCopyJob {
is_append: false,
ignore_source_not_found: false,
report_progress: false,
settle_skip: 0,
},
progress,
)
@@ -5927,6 +5996,7 @@ impl VolumeCopyJob {
is_append: false,
ignore_source_not_found: true,
report_progress: false,
settle_skip: 0,
},
progress,
)
@@ -6096,6 +6166,8 @@ impl VolumeCopyJob {
let _ = std::fs::remove_file(format!("{}.idx", idx_base_name));
let _ = std::fs::remove_file(format!("{}.vif", data_base_name));
let _ = std::fs::remove_file(&note_path);
self.dest
.release_reservation(&state.store.read().unwrap());
let _ = tx.send(Err(e)).await;
}
}
@@ -6294,6 +6366,9 @@ struct CopyFileSpec<'a> {
ignore_source_not_found: bool,
/// Whether this file's bytes are reported back to the caller as progress.
report_progress: bool,
/// Bytes of this file statfs already counts (a fallocated .dat); only
/// writes past it settle the copy's headroom charge.
settle_skip: i64,
}
/// Progress reporting and throttling shared by every file of one volume copy.
@@ -6302,6 +6377,8 @@ struct CopyProgress<'a> {
next_report_target: &'a mut i64,
report_interval: i64,
throttler: &'a mut WriteThrottler,
/// Settles the headroom charge for bytes newly visible to statfs.
settle: &'a mut (dyn FnMut(i64) + Send),
}
/// Mirrors Go's checkVolumeFileExtension: the client-supplied Ext that
@@ -6353,6 +6430,7 @@ where
is_append,
ignore_source_not_found,
report_progress,
settle_skip,
} = *spec;
let progress_tx = progress.tx;
let copy_req = volume_server_pb::CopyFileRequest {
@@ -6411,6 +6489,7 @@ where
let mut progressed_bytes: i64 = 0;
let mut modified_ts_ns: i64 = 0;
let mut settled_bytes: i64 = 0;
// The source stream's message() future is the one await in this loop that
// can hang indefinitely: a stalled source (slow disk, network partition,
@@ -6445,6 +6524,11 @@ where
file.write_all(&resp.file_content)
.map_err(|e| Status::internal(format!("write file {}: {}", dest_path, e)))?;
progressed_bytes += resp.file_content.len() as i64;
// Writes past settle_skip are new usage statfs can see; the
// copy's headroom charge settles as they land.
let landed = (progressed_bytes - settle_skip).max(0);
(progress.settle)(landed - settled_bytes);
settled_bytes = landed;
// A throttled copy sleeps seconds at a time; wake for a departing
// caller instead of finishing the nap first.
tokio::select! {
@@ -8931,12 +9015,14 @@ mod tests {
is_append: false,
ignore_source_not_found: true,
report_progress: true,
settle_skip: 0,
},
&mut CopyProgress {
tx: &tx,
next_report_target: &mut next_report_target,
report_interval: 128 * 1024 * 1024,
throttler: &mut throttler,
settle: &mut |_| {},
},
)
.await
+516 -31
View File
@@ -555,6 +555,7 @@ async fn lookup_volume(
.send()
.await
.map_err(|e| format!("lookup request failed: {}", e))?;
let status = resp.status();
let result: LookupResult = resp
.json()
.await
@@ -562,7 +563,18 @@ async fn lookup_volume(
if let Some(err) = result.error
&& !err.is_empty()
{
return Err(err);
// Mirror Go: a missing volume arrives as a per-volume error in an
// answered lookup (HTTP 404), meaning "no locations" — a real master
// failure (e.g. 503 while warming up) stays an error so proxy mode
// can tell missing data (404) from a failed lookup (500).
if status != StatusCode::NOT_FOUND {
return Err(err);
}
tracing::debug!("volume {} lookup: {}", volume_id, err);
} else if !status.is_success() && status != StatusCode::NOT_FOUND {
// A non-success answer without an error body (e.g. an intermediary's
// 503 as `{}`) is a failed lookup, not a missing volume.
return Err(format!("lookup failed: {}", status));
}
Ok(result.locations.unwrap_or_default())
}
@@ -812,6 +824,7 @@ async fn do_replicated_request(
/// Extracted request info needed for proxy/redirect (avoids borrowing Request across await).
struct ProxyRequestInfo {
method: Method,
original_headers: HeaderMap,
original_query: String,
path: String,
@@ -823,12 +836,14 @@ fn build_proxy_request_info(
path: &str,
headers: &HeaderMap,
query_string: &str,
method: &Method,
) -> Option<ProxyRequestInfo> {
// Go redirects to "vid,fid" built from parseURLPath, so the extension must
// already be off the fid here (volume_server_handlers_read.go:128-137).
let parsed = parse_needle_path(path)?;
Some(ProxyRequestInfo {
method: method.clone(),
original_headers: headers.clone(),
original_query: query_string.to_string(),
path: path.to_string(),
@@ -856,7 +871,11 @@ async fn proxy_or_redirect_to_target(
Ok(locs) => locs,
Err(e) => {
tracing::warn!("volume lookup failed for {}: {}", vid.0, e);
return StatusCode::NOT_FOUND.into_response();
// Go: master lookup failure is 500 in proxy mode, 404 for redirect
return match state.read_mode {
ReadMode::Proxy => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
_ => StatusCode::NOT_FOUND.into_response(),
};
}
};
@@ -893,24 +912,58 @@ async fn proxy_or_redirect_to_target(
}
}
/// Hop-by-hop field names that must not be relayed: the fixed set plus every
/// field the header's own Connection values nominate (RFC 9110 7.6.1).
fn hop_by_hop_names(headers: &HeaderMap, extra: &[&str]) -> std::collections::HashSet<String> {
let mut names: std::collections::HashSet<String> = headers
.get_all(header::CONNECTION)
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(','))
.map(|token| token.trim().to_ascii_lowercase())
.filter(|token| !token.is_empty())
.collect();
for fixed in [
"connection",
"keep-alive",
"te",
"trailer",
"upgrade",
"proxy-connection",
"proxy-authenticate",
"proxy-authorization",
] {
names.insert(fixed.to_string());
}
for name in extra {
names.insert(name.to_string());
}
names
}
/// Proxy the request to the target volume server.
async fn proxy_request(
state: &VolumeServerState,
info: &ProxyRequestInfo,
target: &VolumeLocation,
) -> Response {
// Build target URL, adding proxied=true query param
// Build target URL, adding proxied=true query param. Go's query.Set
// replaces any proxied params the client sent, so a stale proxied=false
// cannot outrank the marker this hop adds.
let path = info.path.trim_start_matches('/');
// Defensively strip a `.grpcPort` suffix in case target.url carries it.
let target_http = to_http_address(&target.url);
let raw_target = if info.original_query.is_empty() {
let forwarded_query = info
.original_query
.split('&')
.filter(|kv| kv.split('=').next() != Some("proxied"))
.collect::<Vec<_>>()
.join("&");
let raw_target = if forwarded_query.is_empty() {
format!("{}/{}?proxied=true", target_http, path)
} else {
format!(
"{}/{}?{}&proxied=true",
target_http, path, info.original_query
)
format!("{}/{}?{}&proxied=true", target_http, path, forwarded_query)
};
let target_url = match normalize_outgoing_http_url(&state.outgoing_http_scheme, &raw_target) {
Ok(url) => url,
@@ -920,11 +973,21 @@ async fn proxy_request(
}
};
// Build the proxy request
let mut req_builder = state.http_client.get(&target_url);
// Build the proxy request, preserving the inbound method (Go parity:
// a client HEAD must not turn into a GET download at the replica).
let mut req_builder = state.http_client.request(info.method.clone(), &target_url);
// Forward all original headers as raw bytes, as Go does.
// Forward the original headers, as Go does — minus hop-by-hop fields.
// The proxied request carries no body, so this hop's Host and framing
// must not reach the replica either.
let hop_by_hop = hop_by_hop_names(
&info.original_headers,
&["host", "content-length", "transfer-encoding"],
);
for (name, value) in &info.original_headers {
if hop_by_hop.contains(name.as_str()) {
continue;
}
req_builder = req_builder.header(name.clone(), value.clone());
}
@@ -936,12 +999,15 @@ async fn proxy_request(
}
};
// Build response, copying headers and body from remote
// Build response, copying headers and body from remote. Hop-by-hop
// response fields describe the replica hop, not ours — Content-Length
// stays because it still describes the relayed body.
let status =
StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let resp_hop_by_hop = hop_by_hop_names(resp.headers(), &[]);
let mut response_headers = HeaderMap::new();
for (name, value) in resp.headers() {
if name.as_str().eq_ignore_ascii_case("server") {
if name.as_str().eq_ignore_ascii_case("server") || resp_hop_by_hop.contains(name.as_str()) {
continue;
}
response_headers.append(name.clone(), value.clone());
@@ -1088,14 +1154,30 @@ async fn get_or_head_handler_inner(
let has_ec_volume = state.store.read().unwrap().has_ec_volume(vid);
if !has_volume && !has_ec_volume {
return proxy_missing_volume(&state, request.uri(), request.headers(), &path, vid).await;
return proxy_missing_volume(
&state,
request.uri(),
request.headers(),
&path,
vid,
&method,
)
.await;
}
let track_download =
match check_download_limit(&state, request.uri(), request.headers(), &path, vid).await {
ControlFlow::Continue(track_download) => track_download,
ControlFlow::Break(resp) => return resp,
};
let track_download = match check_download_limit(
&state,
request.uri(),
request.headers(),
&path,
vid,
&method,
)
.await
{
ControlFlow::Continue(track_download) => track_download,
ControlFlow::Break(resp) => return resp,
};
let read_deleted = query.read_deleted.as_deref() == Some("true");
// Go reads Range once and ignores an empty value; a non-UTF-8 byte fails its parse.
@@ -1120,6 +1202,10 @@ async fn get_or_head_handler_inner(
};
let (etag, last_modified_str) = etag_and_last_modified(&n);
// A Range whose If-Range no longer matches is ignored and the whole
// content is sent, so a resumed download restarts instead of mixing
// two versions.
let range = range.filter(|_| if_range_matches(&headers, &etag, &last_modified_str));
if let Some(resp) = not_modified_response(&n, &headers, &etag, &last_modified_str) {
// A request that ends here was answered by the meta read alone.
if let Some(io_errors) = strategy.io_errors() {
@@ -1167,14 +1253,20 @@ async fn get_or_head_handler_inner(
return head_from_meta_response(&info, response_headers);
}
ReadStrategy::RangeFromSource(info) => {
return range_from_source_response(
&state,
range.as_deref().unwrap_or_default(),
info,
response_headers,
track_download,
)
.await;
return match range.as_deref() {
Some(range) => {
range_from_source_response(
&state,
range,
info,
response_headers,
track_download,
)
.await
}
// If-Range dropped the range; serve the whole content.
None => stream_response(&state, info, response_headers, track_download),
};
}
ReadStrategy::Buffered => {}
}
@@ -1267,6 +1359,7 @@ async fn proxy_missing_volume(
request_headers: &HeaderMap,
path: &str,
vid: VolumeId,
method: &Method,
) -> Response {
let query_string = uri.query().unwrap_or("").to_string();
if is_proxied_query(&query_string)
@@ -1277,7 +1370,7 @@ async fn proxy_missing_volume(
}
// For redirect, fid must be stripped of extension (Go parity: parseURLPath returns raw fid).
let info = match build_proxy_request_info(path, request_headers, &query_string) {
let info = match build_proxy_request_info(path, request_headers, &query_string, method) {
Some(info) => info,
None => return StatusCode::NOT_FOUND.into_response(),
};
@@ -1298,6 +1391,7 @@ async fn check_download_limit(
request_headers: &HeaderMap,
path: &str,
vid: VolumeId,
method: &Method,
) -> ControlFlow<Response, bool> {
if state.concurrent_download_limit <= 0 {
return ControlFlow::Continue(false);
@@ -1322,7 +1416,8 @@ async fn check_download_limit(
.is_some_and(|(_, vol)| vol.super_block().replica_placement.has_replication())
};
if should_try_replica
&& let Some(info) = build_proxy_request_info(path, request_headers, &query_string)
&& let Some(info) =
build_proxy_request_info(path, request_headers, &query_string, method)
{
return ControlFlow::Break(proxy_or_redirect_to_target(state, info, vid, true).await);
}
@@ -1557,6 +1652,31 @@ fn not_modified_response(
None
}
/// If-Range (RFC 9110 13.1.5): an entity-tag by strong comparison, or a date
/// equal to Last-Modified. The response etag here is always a strong tag.
fn if_range_matches(headers: &HeaderMap, etag: &str, last_modified_str: &Option<String>) -> bool {
let Some(raw) = headers.get(header::IF_RANGE) else {
return true;
};
let Ok(if_range) = raw.to_str() else {
return false;
};
let if_range = if_range.trim();
if if_range.is_empty() {
return true;
}
if if_range.starts_with('"') || if_range.starts_with("W/") {
return if_range == etag;
}
let Ok(date) = httpdate::parse_http_date(if_range) else {
return false;
};
last_modified_str
.as_deref()
.and_then(|lm| httpdate::parse_http_date(lm).ok())
.is_some_and(|lm| date == lm)
}
/// Weak comparison against "*" or a comma-separated entity-tag list (RFC 9110 13.1.2).
fn etag_list_matches(header: &str, etag: &str) -> bool {
if header.trim() == "*" {
@@ -5146,6 +5266,7 @@ mod tests {
#[test]
fn test_redirect_request_uses_outgoing_http_scheme() {
let info = ProxyRequestInfo {
method: Method::GET,
original_headers: HeaderMap::new(),
original_query: "collection=photos&readDeleted=true".to_string(),
path: "/3,01637037d6".to_string(),
@@ -5174,6 +5295,7 @@ mod tests {
#[test]
fn test_redirect_request_strips_grpc_port_from_target_url() {
let info = ProxyRequestInfo {
method: Method::GET,
original_headers: HeaderMap::new(),
original_query: String::new(),
path: "/3,01637037d6".to_string(),
@@ -5205,7 +5327,8 @@ mod tests {
#[test]
fn test_redirect_location_drops_extension_for_slash_form() {
let info =
build_proxy_request_info("/3/01637037d6.jpg", &HeaderMap::new(), "").expect("parses");
build_proxy_request_info("/3/01637037d6.jpg", &HeaderMap::new(), "", &Method::GET)
.expect("parses");
assert_eq!(info.vid_str, "3");
assert_eq!(info.fid_str, "01637037d6");
@@ -5299,6 +5422,66 @@ mod tests {
server.abort();
}
/// The master answers a missing volume with 404 and a per-volume `error`
/// in the lookup body. Go's LookupResult.Error never becomes the Go error
/// return — the volume server treats it as empty locations and replies
/// 404. Surfacing it as Err would make proxy-mode reads answer 500.
/// A lookup answered with any other failure status (e.g. 503 while the
/// master warms up) stays an error, like Go's transport-level failure.
#[tokio::test]
async fn test_lookup_volume_missing_volume_returns_empty() {
use axum::{Router, routing::get};
let app = Router::new().route(
"/dir/lookup",
get(|axum::extract::Query(params): axum::extract::Query<
std::collections::HashMap<String, String>,
>| async move {
let (status, error) = match params.get("volumeId").map(String::as_str) {
Some("7") => (StatusCode::NOT_FOUND, Some("volume id 7 not found")),
Some("9") => (StatusCode::SERVICE_UNAVAILABLE, None),
_ => (
StatusCode::SERVICE_UNAVAILABLE,
Some("service warming up, please retry"),
),
};
let mut body = serde_json::json!({
"volumeOrFileId": params.get("volumeId")
});
if let Some(error) = error {
body["error"] = serde_json::json!(error);
}
(status, axum::Json(body))
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let master_url = format!("127.0.0.1:{}", addr.port());
let client = reqwest::Client::new();
let locations = super::lookup_volume(&client, "http", &master_url, 7)
.await
.expect("missing volume is not a lookup failure");
assert!(locations.is_empty());
let err = super::lookup_volume(&client, "http", &master_url, 8)
.await
.expect_err("master failure is a lookup failure");
assert!(err.contains("warming up"));
let err = super::lookup_volume(&client, "http", &master_url, 9)
.await
.expect_err("a failed lookup without an error body is still a failure");
assert!(err.contains("503"));
server.abort();
}
/// A body streaming `data_size` bytes of `file` from offset 0.
fn file_streaming_body(
file: &std::fs::File,
@@ -5357,6 +5540,7 @@ mod tests {
});
let info = ProxyRequestInfo {
method: Method::GET,
original_headers: HeaderMap::new(),
original_query: String::new(),
path: "/3,01637037d6".to_string(),
@@ -5389,6 +5573,260 @@ mod tests {
server.abort();
}
/// Go now forwards the inbound method (volume_server_handlers_read.go), so
/// a client HEAD reaches the replica as HEAD, not GET.
#[tokio::test]
async fn test_proxy_request_preserves_method() {
use axum::{Router, routing::get};
use std::sync::Arc as StdArc;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
let head_count = StdArc::new(AtomicUsize::new(0));
let get_count = StdArc::new(AtomicUsize::new(0));
let app = {
let head_count = head_count.clone();
let get_count = get_count.clone();
Router::new().route(
"/{*path}",
get(move |request: axum::extract::Request| {
let head_count = head_count.clone();
let get_count = get_count.clone();
async move {
if *request.method() == Method::HEAD {
head_count.fetch_add(1, AtomicOrdering::SeqCst);
} else {
get_count.fetch_add(1, AtomicOrdering::SeqCst);
}
StatusCode::OK
}
}),
)
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let target = VolumeLocation {
url: addr.to_string(),
public_url: String::new(),
grpc_port: 0,
read_only: false,
read_only_can_delete: false,
};
let state = streaming_test_state();
for method in [Method::HEAD, Method::GET] {
let info = ProxyRequestInfo {
method,
original_headers: HeaderMap::new(),
original_query: String::new(),
path: "/3,01637037d6".to_string(),
vid_str: "3".to_string(),
fid_str: "01637037d6".to_string(),
};
let response = proxy_request(&state, &info, &target).await;
assert_eq!(response.status(), StatusCode::OK);
}
assert_eq!(head_count.load(AtomicOrdering::SeqCst), 1);
assert_eq!(get_count.load(AtomicOrdering::SeqCst), 1);
server.abort();
}
/// Go's query.Set replaces any proxied params the client sent, so the
/// forwarded query carries a single proxied=true marker — a stale
/// proxied=false cannot outrank it on the replica's first-value lookup.
#[tokio::test]
async fn test_proxy_request_replaces_stale_proxied_param() {
use axum::{Router, routing::get};
use std::sync::Arc as StdArc;
use std::sync::Mutex;
let seen = StdArc::new(Mutex::new(String::new()));
let app = {
let seen = seen.clone();
Router::new().route(
"/{*path}",
get(move |request: axum::extract::Request| {
let seen = seen.clone();
async move {
*seen.lock().unwrap() =
request.uri().query().unwrap_or("").to_string();
StatusCode::OK
}
}),
)
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let target = VolumeLocation {
url: addr.to_string(),
public_url: String::new(),
grpc_port: 0,
read_only: false,
read_only_can_delete: false,
};
let state = streaming_test_state();
let info = ProxyRequestInfo {
method: Method::GET,
original_headers: HeaderMap::new(),
original_query: "proxied=false&collection=photos&proxied".to_string(),
path: "/3,01637037d6".to_string(),
vid_str: "3".to_string(),
fid_str: "01637037d6".to_string(),
};
let response = proxy_request(&state, &info, &target).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
seen.lock().unwrap().as_str(),
"collection=photos&proxied=true"
);
server.abort();
}
/// End-to-end headers like Range reach the replica; hop-by-hop headers do
/// not — a forwarded Content-Length or Host describes this hop, not the
/// replica's, and a lying Content-Length stalls the peer's body read.
#[tokio::test]
async fn test_proxy_request_drops_hop_by_hop_headers() {
use axum::{Router, routing::get};
use std::sync::Arc as StdArc;
use std::sync::Mutex;
let seen = StdArc::new(Mutex::new(Vec::new()));
let app = {
let seen = seen.clone();
Router::new().route(
"/{*path}",
get(move |request: axum::extract::Request| {
let seen = seen.clone();
async move {
let headers: Vec<(String, String)> = request
.headers()
.iter()
.map(|(k, v)| {
(k.as_str().to_string(), v.to_str().unwrap_or("").to_string())
})
.collect();
seen.lock().unwrap().push(headers);
(
[
(header::CONNECTION, "keep-alive, x-resp-marker"),
(header::HeaderName::from_static("keep-alive"), "timeout=5"),
(header::HeaderName::from_static("x-resp-marker"), "private"),
(header::ETAG, "\"peer-etag\""),
],
request
.headers()
.get(header::RANGE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string(),
)
}
}),
)
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
let target = VolumeLocation {
url: addr.to_string(),
public_url: String::new(),
grpc_port: 0,
read_only: false,
read_only_can_delete: false,
};
let mut original_headers = HeaderMap::new();
original_headers.insert(header::RANGE, header::HeaderValue::from_static("bytes=0-3"));
original_headers.insert(
header::HOST,
header::HeaderValue::from_static("client-facing:8080"),
);
original_headers.insert(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("999"),
);
original_headers.insert(
header::TRANSFER_ENCODING,
header::HeaderValue::from_static("chunked"),
);
original_headers.insert(
header::CONNECTION,
header::HeaderValue::from_static("keep-alive, x-hop-marker"),
);
original_headers.insert(
"x-hop-marker",
header::HeaderValue::from_static("private"),
);
original_headers.insert(
"proxy-authorization",
header::HeaderValue::from_static("Basic cHJveHk6c2VjcmV0"),
);
let info = ProxyRequestInfo {
method: Method::GET,
original_headers,
original_query: String::new(),
path: "/3,01637037d6".to_string(),
vid_str: "3".to_string(),
fid_str: "01637037d6".to_string(),
};
let response = proxy_request(&streaming_test_state(), &info, &target).await;
assert_eq!(response.status(), StatusCode::OK);
let seen = seen.lock().unwrap();
let headers = seen.first().expect("peer saw a request");
assert!(
headers
.iter()
.any(|(n, v)| n == "range" && v == "bytes=0-3"),
"Range was not forwarded: {headers:?}"
);
for dropped in [
"content-length",
"transfer-encoding",
"connection",
"x-hop-marker",
"proxy-authorization",
] {
assert!(
!headers.iter().any(|(n, _)| n == dropped),
"hop-by-hop header {dropped} reached the replica: {headers:?}"
);
}
// The peer must see its own host, not the client's.
let host = headers
.iter()
.find(|(n, _)| n == "host")
.map(|(_, v)| v.as_str())
.expect("replica request has a host header");
assert_eq!(host, addr.to_string());
// End-to-end response fields reach the client; the replica's
// hop-by-hop fields and Connection-nominated markers do not.
assert_eq!(
response.headers().get(header::ETAG).unwrap(),
"\"peer-etag\""
);
for dropped in ["connection", "keep-alive", "x-resp-marker"] {
assert!(
response.headers().get(dropped).is_none(),
"hop-by-hop response header {dropped} reached the client"
);
}
server.abort();
}
fn streaming_test_state() -> Arc<VolumeServerState> {
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::store::Store;
@@ -5767,6 +6205,53 @@ mod tests {
assert!(resp.headers().contains_key(header::LAST_MODIFIED));
}
#[test]
fn test_if_range_matches() {
let etag = "\"v2\"".to_string();
let last_modified_str = Some("Sat, 24 Oct 2026 22:01:04 GMT".to_string());
let cases: Vec<(Option<&str>, bool)> = vec![
(None, true),
(Some("\"v2\""), true),
(Some("Sat, 24 Oct 2026 22:01:04 GMT"), true),
(Some("Saturday, 24-Oct-26 22:01:04 GMT"), true),
(Some("Sat Oct 24 22:01:04 2026"), true),
(Some("\"v1\""), false),
(Some("W/\"v2\""), false),
(Some("Sat, 24 Oct 2026 22:01:03 GMT"), false),
(Some("not a date"), false),
];
for (if_range, want) in cases {
let mut headers = HeaderMap::new();
if let Some(v) = if_range {
headers.insert(header::IF_RANGE, v.parse().unwrap());
}
assert_eq!(
if_range_matches(&headers, &etag, &last_modified_str),
want,
"{if_range:?}"
);
}
// A present value that is not valid UTF-8 fails the condition.
let mut headers = HeaderMap::new();
headers.insert(
header::IF_RANGE,
header::HeaderValue::from_bytes(b"\"\xff\xfev2\"").unwrap(),
);
assert!(!if_range_matches(&headers, &etag, &last_modified_str));
// No Last-Modified on the representation: a date validator fails,
// an entity-tag still applies.
let mut headers = HeaderMap::new();
headers.insert(header::IF_RANGE, "\"v2\"".parse().unwrap());
assert!(if_range_matches(&headers, &etag, &None));
headers.insert(
header::IF_RANGE,
"Sat, 24 Oct 2026 22:01:04 GMT".parse().unwrap(),
);
assert!(!if_range_matches(&headers, &etag, &None));
}
/// A GET whose needle read is parked must not hold the store lock: a
/// writer, here a real append to the same volume, must get through.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -7100,7 +7585,7 @@ mod tests {
header::RANGE,
header::HeaderValue::from_bytes(b"bytes=0-1\xff").unwrap(),
);
let info = build_proxy_request_info(&path, &headers, "").unwrap();
let info = build_proxy_request_info(&path, &headers, "", &Method::GET).unwrap();
let resp = proxy_request(&proxy_state, &info, &target).await;
assert_eq!(resp.status(), StatusCode::RANGE_NOT_SATISFIABLE);
+1 -1
View File
@@ -1190,7 +1190,7 @@ fn build_heartbeat_with_ec_status(
for (disk_id, loc) in store.locations.iter().enumerate() {
let disk_type_str = loc.disk_type.to_string();
let mut effective_max_count = loc.max_volume_count.load(Ordering::Relaxed);
if loc.is_disk_space_low.load(Ordering::Relaxed) {
if loc.is_disk_space_low.load(Ordering::Relaxed) || loc.read_only_mount {
let used_slots = loc.volumes_len() as i32
+ loc
.ec_shard_count()
+147 -11
View File
@@ -10,7 +10,7 @@ use std::io;
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tracing::warn;
use tracing::{info, warn};
use crate::config::MinFreeSpace;
use crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars;
@@ -40,7 +40,15 @@ pub struct DiskLocation {
volumes: HashMap<VolumeId, Arc<Volume>>,
ec_volumes: HashMap<VolumeId, EcVolume>,
pub is_disk_space_low: Arc<AtomicBool>,
/// Go's `DiskLocation.readOnlyMount`: dir or idx_dir is on a read-only
/// filesystem. Volumes load read-only and the location offers no free
/// slots. Fixed at startup.
pub read_only_mount: bool,
pub available_space: AtomicU64,
/// Headroom promised to in-flight copies that statfs cannot see yet.
/// Probes keep it out of available_space so they cannot re-spend it; a
/// copy that lands ends its charge, one that fails removes only its own.
pub reserved_space: AtomicU64,
// Physical filesystem capacity from the latest check_disk_space probe, reported
// to the master so balancing can see real disk fullness, not just slot counts.
pub disk_total_bytes: AtomicU64,
@@ -67,11 +75,19 @@ impl DiskLocation {
fs::create_dir_all(idx_directory)?;
idx_directory.to_string()
};
let read_only_mount = is_read_only_mount(directory) || is_read_only_mount(&idx_dir);
if read_only_mount {
info!(
"{} is on a read-only filesystem: its volumes load read-only, no new volumes",
directory
);
}
let directory_uuid = Self::generate_directory_uuid(directory)?;
Ok(DiskLocation {
directory: directory.to_string(),
idx_directory: idx_dir,
read_only_mount,
directory_uuid,
disk_type,
tags,
@@ -81,6 +97,7 @@ impl DiskLocation {
ec_volumes: HashMap::new(),
is_disk_space_low: Arc::new(AtomicBool::new(false)),
available_space: AtomicU64::new(0),
reserved_space: AtomicU64::new(0),
disk_total_bytes: AtomicU64::new(0),
disk_free_bytes: AtomicU64::new(0),
min_free_space,
@@ -97,8 +114,35 @@ impl DiskLocation {
}
let dir_uuid = uuid::Uuid::new_v4().to_string();
fs::write(path, &dir_uuid)?;
Ok(dir_uuid)
match fs::write(&path, &dir_uuid) {
Ok(()) => Ok(dir_uuid),
// The uuid file cannot be written on a read-only mount; derive a
// stable one from the directory plus its device and host so
// restarts report the same id and independent disks at the same
// path differ.
Err(_) if is_read_only_mount(directory) => {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
directory.hash(&mut h);
if let Ok(meta) = fs::metadata(directory) {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
meta.dev().hash(&mut h);
}
#[cfg(not(unix))]
{
let _ = meta;
}
}
if let Ok(host) = std::env::var("HOSTNAME") {
host.hash(&mut h);
}
let derived = (h.finish() as u128) << 64 | h.finish() as u128;
Ok(uuid::Uuid::from_u128(derived).to_string())
}
Err(e) => Err(e),
}
}
// ---- Volume management ----
@@ -715,6 +759,9 @@ impl DiskLocation {
/// Matches Go's FindFreeLocation formula:
/// free = ((MaxVolumeCount - VolumesLen()) * DataShardsCount - EcShardCount()) / DataShardsCount
pub fn free_volume_count(&self) -> i32 {
if self.read_only_mount {
return 0;
}
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let max = self.max_volume_count.load(Ordering::Relaxed);
let free_count = (max as i64 - self.volumes.len() as i64) * DATA_SHARDS_COUNT as i64
@@ -761,15 +808,16 @@ impl DiskLocation {
return;
}
let used = total.saturating_sub(free);
let is_low = match &self.min_free_space {
MinFreeSpace::Percent(pct) => {
let free_pct = (free as f64 / total as f64) * 100.0;
free_pct < *pct
}
MinFreeSpace::Bytes(min_bytes) => free < *min_bytes,
};
let is_low = self.min_free_space.is_low(free, total);
self.is_disk_space_low.store(is_low, Ordering::Relaxed);
self.available_space.store(free, Ordering::Relaxed);
// Go's DiskLocation.AvailableSpace counts only free space above the
// -volume.minFreeSpace floor, so space checks stay above it too.
self.available_space.store(
self.min_free_space
.available_space(free, total)
.saturating_sub(self.reserved_space.load(Ordering::Relaxed)),
Ordering::Relaxed,
);
self.disk_total_bytes.store(total, Ordering::Relaxed);
self.disk_free_bytes.store(free, Ordering::Relaxed);
@@ -1173,6 +1221,27 @@ impl DiskLocation {
}
}
/// Mirror of Go's `util.IsReadOnlyMount`: access(2) with W_OK answers EROFS
/// for a filesystem mounted read-only regardless of the permission bits, and
/// also for root, unlike a permission-bits check.
#[cfg(unix)]
pub(crate) fn is_read_only_mount(path: &str) -> bool {
use std::ffi::CString;
let c_path = match CString::new(path.as_bytes()) {
Ok(p) => p,
Err(_) => return false,
};
if unsafe { libc::access(c_path.as_ptr(), libc::W_OK) } == 0 {
return false;
}
io::Error::last_os_error().raw_os_error() == Some(libc::EROFS)
}
#[cfg(not(unix))]
pub(crate) fn is_read_only_mount(_path: &str) -> bool {
false
}
/// Get total and free disk space for a given path.
/// Returns (total_bytes, free_bytes).
pub fn get_disk_stats(path: &str) -> (u64, u64) {
@@ -1445,6 +1514,73 @@ mod tests {
assert!(free > 0, "expected free>0, got {free}");
}
// Mirrors Go's DiskLocation.AvailableSpace: the cached figure a copy is
// checked against counts only free space above the min-free-space floor.
#[test]
fn test_check_disk_space_counts_only_space_above_floor() {
const FLOOR: u64 = 1 << 20;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = DiskLocation::new(
dir,
dir,
0,
DiskType::HardDrive,
MinFreeSpace::Bytes(FLOOR),
Vec::new(),
)
.unwrap();
loc.check_disk_space();
assert_eq!(
loc.available_space.load(Ordering::Relaxed),
loc.disk_free_bytes
.load(Ordering::Relaxed)
.saturating_sub(FLOOR)
);
let loc = DiskLocation::new(
dir,
dir,
0,
DiskType::HardDrive,
MinFreeSpace::Bytes(u64::MAX),
Vec::new(),
)
.unwrap();
loc.check_disk_space();
assert_eq!(loc.available_space.load(Ordering::Relaxed), 0);
}
// Mirrors Go's CheckDiskSpace pending subtraction: an in-flight copy's
// charge stays out of the cache across a probe, so another copy cannot
// re-spend the headroom the live reading still shows as free.
#[test]
fn test_check_disk_space_keeps_pending_reservation_out_of_cache() {
const FLOOR: u64 = 1 << 20;
const RESERVED: u64 = 512 * 1024;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = DiskLocation::new(
dir,
dir,
0,
DiskType::HardDrive,
MinFreeSpace::Bytes(FLOOR),
Vec::new(),
)
.unwrap();
loc.reserved_space.store(RESERVED, Ordering::Relaxed);
loc.check_disk_space();
let expected = loc
.min_free_space
.available_space(
loc.disk_free_bytes.load(Ordering::Relaxed),
loc.disk_total_bytes.load(Ordering::Relaxed),
)
.saturating_sub(RESERVED);
assert_eq!(loc.available_space.load(Ordering::Relaxed), expected);
}
/// When `-dir.idx` is configured the EC `.vif` may live in the idx
/// directory; the sweep must look there too, not only the data dir.
#[test]
+489 -24
View File
@@ -20,7 +20,9 @@ use crate::storage::needle::needle::{Needle, get_actual_size};
use crate::storage::needle_map::NeedleMapKind;
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE, SuperBlock};
use crate::storage::types::*;
use crate::storage::volume::{CompactionJob, VifVolumeInfo, Volume, VolumeError, VolumeSpec};
use crate::storage::volume::{
CompactionJob, PREALLOCATE_SUPPORTED, VifVolumeInfo, Volume, VolumeError, VolumeSpec,
};
/// Mirrors Go's ensureCompactVolumeSpace, per filesystem: the new .dat lands
/// next to the old one and the new .idx next to the old index, so when the
@@ -52,6 +54,40 @@ fn ensure_compact_volume_space(v: &Volume, preallocate: u64) -> Result<(), Volum
}
}
// Create-time metadata a location must still fit after a preallocation: .vif
// always lands beside the data file; the .idx a writable volume keeps
// appending counts only when dir_idx shares the filesystem. Holding these
// back keeps an exact-fit reservation from dipping under the floor once the
// metadata is written.
const VOLUME_CREATE_VIF_BYTES: u64 = 1 << 20;
const VOLUME_CREATE_IDX_BYTES: u64 = 4 << 20;
/// Mirrors Go's hasRoomForNewVolume: a preallocated volume reserves its full
/// size up front, so it must fit in the free space above the min-free-space
/// floor. Reads the disk now rather than the once-a-probe is_disk_space_low
/// flag. A volume without preallocation reserves nothing, as does one on a
/// platform where preallocate_file is a no-op.
fn has_room_for_new_volume(
location: &DiskLocation,
preallocate: u64,
preallocate_supported: bool,
disk_stats_of: fn(&str) -> (u64, u64),
) -> bool {
if preallocate == 0 || !preallocate_supported {
return true;
}
let (all, free) = disk_stats_of(&location.directory);
if location.min_free_space.is_low(free, all) {
return false;
}
let mut need = preallocate + VOLUME_CREATE_VIF_BYTES;
if same_filesystem(&location.directory, &location.idx_directory) {
need += VOLUME_CREATE_IDX_BYTES;
}
location.min_free_space.available_space(free, all)
>= need + location.reserved_space.load(Ordering::Relaxed)
}
/// Top-level storage manager containing all disk locations and their volumes.
pub struct Store {
pub locations: Vec<DiskLocation>,
@@ -76,6 +112,13 @@ pub struct Store {
pub last_seen_topology_id: Mutex<String>,
pub vid_stamp_lock: Mutex<()>,
pub vid_stamp_dirty: std::sync::atomic::AtomicBool,
/// Reads (total, free) for a directory; a field so a test can stand in
/// for a disk that is full or near its floor. Go: diskStatusOf.
disk_stats_of: fn(&str) -> (u64, u64),
/// Whether a create actually reserves `preallocate` on this platform; a
/// field so a test can exercise the guard off Linux. Go:
/// createVolumeFilePreallocates.
preallocate_supported: bool,
}
impl Store {
@@ -99,6 +142,8 @@ impl Store {
last_seen_topology_id: Mutex::new(String::new()),
vid_stamp_lock: Mutex::new(()),
vid_stamp_dirty: std::sync::atomic::AtomicBool::new(false),
disk_stats_of: super::disk_location::get_disk_stats,
preallocate_supported: PREALLOCATE_SUPPORTED,
}
}
@@ -228,7 +273,7 @@ impl Store {
/// Find the location with fewest volumes (load-balance) of the given disk type.
/// Matches Go's FindFreeLocation: accounts for EC shards when computing free slots.
fn find_free_location(&self, disk_type: &DiskType) -> Option<usize> {
fn find_free_location(&self, disk_type: &DiskType, preallocate: u64) -> Option<usize> {
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let mut best: Option<(usize, i64)> = None; // (index, effective_free)
@@ -250,7 +295,15 @@ impl Store {
if effective_free <= 0 {
continue;
}
if loc.is_disk_space_low.load(Ordering::Relaxed) {
if loc.is_disk_space_low.load(Ordering::Relaxed) || loc.read_only_mount {
continue;
}
if !has_room_for_new_volume(
loc,
preallocate,
self.preallocate_supported,
self.disk_stats_of,
) {
continue;
}
if best.is_none() || effective_free > best.unwrap().1 {
@@ -277,7 +330,7 @@ impl Store {
let mut best: Option<(usize, i64)> = None;
for (i, loc) in self.locations.iter().enumerate() {
if !pred(loc) || loc.is_disk_space_low.load(Ordering::Relaxed) {
if !pred(loc) || loc.is_disk_space_low.load(Ordering::Relaxed) || loc.read_only_mount {
continue;
}
@@ -304,6 +357,64 @@ impl Store {
best.map(|(i, _)| i)
}
/// Mirrors Go's Store.ReserveFreeLocation: a copy's pick and its .dat
/// reservation are separate steps, so verify live space under the store
/// lock and charge need against the location's pending reservations, or
/// a second copy can spend the same headroom before the first lands.
pub fn reserve_free_location<F>(
&self,
need: u64,
pred: F,
replace_vid: Option<VolumeId>,
) -> Option<usize>
where
F: Fn(&DiskLocation) -> bool,
{
let loc_idx = self.find_free_location_predicate(
|loc| {
if loc.available_space.load(Ordering::Relaxed) <= need || !pred(loc) {
return false;
}
let (all, free) = (self.disk_stats_of)(&loc.directory);
!loc.min_free_space.is_low(free, all)
&& loc.min_free_space.available_space(free, all)
> loc.reserved_space.load(Ordering::Relaxed) + need
},
replace_vid,
)?;
let loc = &self.locations[loc_idx];
let (all, free) = (self.disk_stats_of)(&loc.directory);
loc.reserved_space.fetch_add(need, Ordering::Relaxed);
loc.available_space.store(
loc.min_free_space
.available_space(free, all)
.saturating_sub(loc.reserved_space.load(Ordering::Relaxed)),
Ordering::Relaxed,
);
Some(loc_idx)
}
/// Mirrors Go's Store.ReleaseFreeLocation: returns space
/// reserve_free_location charged when the copy it paid for does not
/// land. Removing the pending charge first keeps a probe that already
/// rebased the cache from seeing the refund twice.
pub fn release_free_location(&self, loc_idx: usize, need: u64) {
if let Some(loc) = self.locations.get(loc_idx) {
loc.reserved_space.fetch_sub(need, Ordering::Relaxed);
loc.available_space.fetch_add(need, Ordering::Relaxed);
}
}
/// Mirrors Go's Store.CommitFreeLocation: settles a reservation whose
/// copy landed. The bytes are real on disk, so only the pending charge
/// ends — the cache keeps the charge, which now matches the live usage
/// the next probe will read.
pub fn commit_free_location(&self, loc_idx: usize, need: u64) {
if let Some(loc) = self.locations.get(loc_idx) {
loc.reserved_space.fetch_sub(need, Ordering::Relaxed);
}
}
/// Returns the index of the disk that should receive a new EC
/// shard / index file for `(collection, vid)`. Selection order:
///
@@ -360,6 +471,14 @@ impl Store {
let mut best: Option<(usize, u8, usize, i64)> = None;
for (i, loc) in self.locations.iter().enumerate() {
let owned = owned_ec_shard_count(loc, vid, shard_ids);
if loc.read_only_mount {
// A read-only owner still owns the shard: placing another
// copy on a writable sibling would register it on two disks.
if owned > 0 {
return None;
}
continue;
}
let free = ec_free_shard_count(loc, data_shard_count);
if owned == 0 {
if loc.is_disk_space_low.load(Ordering::Relaxed) {
@@ -460,12 +579,14 @@ impl Store {
if self.find_volume(vid).is_some() {
return Err(VolumeError::AlreadyExists);
}
let loc_idx = self.find_free_location(&disk_type).ok_or_else(|| {
VolumeError::Io(io::Error::other(format!(
"no free location for disk type {:?}",
disk_type
)))
})?;
let loc_idx = self
.find_free_location(&disk_type, spec.preallocate)
.ok_or_else(|| {
VolumeError::Io(io::Error::other(format!(
"no free location for disk type {:?}",
disk_type
)))
})?;
self.locations[loc_idx].create_volume(vid, self.needle_map_kind, spec)
}
@@ -875,11 +996,7 @@ impl Store {
}
/// Delete a needle from a volume.
pub fn delete_volume_needle(
&self,
vid: VolumeId,
n: &mut Needle,
) -> Result<Size, VolumeError> {
pub fn delete_volume_needle(&self, vid: VolumeId, n: &mut Needle) -> Result<Size, VolumeError> {
// Match Go's DeleteVolumeNeedle: check noWriteOrDelete before proceeding.
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
if vol.is_no_write_or_delete() {
@@ -941,10 +1058,12 @@ impl Store {
for loc in &self.locations {
if loc.original_max_volume_count == 0 {
let current = loc.max_volume_count.load(Ordering::Relaxed);
let (_, free) = super::disk_location::get_disk_stats(&loc.directory);
let (all, free) = (self.disk_stats_of)(&loc.directory);
let unused_space = loc.unused_space(volume_size_limit);
let unclaimed = (free as i64) - (unused_space as i64);
// Free space under -volume.minFreeSpace is not available for new volumes.
let unclaimed =
loc.min_free_space.available_space(free, all) as i64 - unused_space as i64;
let vol_count = loc.volumes_len() as i32;
let loc_ec_shards = loc.ec_shard_count();
@@ -1761,7 +1880,7 @@ fn update_dat_replica_placement(
return Err(VolumeError::Io(io::Error::new(
e.kind(),
format!("volume {} failed to open {}: {}", vid, dat_path, e),
)))
)));
}
};
let mut header = [0u8; SUPER_BLOCK_SIZE];
@@ -1775,12 +1894,13 @@ fn update_dat_replica_placement(
let mut block = header.to_vec();
block.resize(SUPER_BLOCK_SIZE + extra_size, 0);
if extra_size > 0 {
file.read_exact(&mut block[SUPER_BLOCK_SIZE..]).map_err(|e| {
VolumeError::Io(io::Error::new(
e.kind(),
format!("volume {} failed to parse superblock: {}", vid, e),
))
})?;
file.read_exact(&mut block[SUPER_BLOCK_SIZE..])
.map_err(|e| {
VolumeError::Io(io::Error::new(
e.kind(),
format!("volume {} failed to parse superblock: {}", vid, e),
))
})?;
}
let mut super_block = SuperBlock::from_bytes(&block).map_err(|e| {
VolumeError::Io(io::Error::new(
@@ -2032,6 +2152,351 @@ mod tests {
assert_eq!(store.total_volume_count(), 1);
}
// fakeDisk stands in for the disk under a location; a preallocating
// create takes its size out of FAKE_FREE, as fallocate does on Linux.
const MIB: u64 = 1 << 20;
static FAKE_ALL: AtomicU64 = AtomicU64::new(0);
static FAKE_FREE: AtomicU64 = AtomicU64::new(0);
static FAKE_DISK_LOCK: Mutex<()> = Mutex::new(());
fn fake_disk_stats(_: &str) -> (u64, u64) {
(
FAKE_ALL.load(Ordering::Relaxed),
FAKE_FREE.load(Ordering::Relaxed),
)
}
// Store with one location whose fake disk has the given free space and a
// Bytes floor; the low-disk flag stays false, as between two probes.
fn headroom_store(dir: &str, free: u64, floor: u64) -> Store {
FAKE_ALL.store(10 * 1024 * MIB, Ordering::Relaxed);
FAKE_FREE.store(free, Ordering::Relaxed);
let mut store = Store::new(NeedleMapKind::InMemory);
store
.add_location(
dir,
dir,
10,
DiskType::HardDrive,
MinFreeSpace::Bytes(floor),
Vec::new(),
)
.unwrap();
store.disk_stats_of = fake_disk_stats;
// The fake disk behaves like fallocate on Linux: pretend creates reserve.
store.preallocate_supported = true;
store
}
// Mirrors Go's TestAddVolumeRefusesPreallocationThatCrossesFloor: the
// reservation must fit above the floor even though the once-a-probe
// is_disk_space_low flag is still false.
#[test]
fn test_add_volume_refuses_preallocation_crossing_floor() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
// 4 MiB above the floor, so an 8 MiB reservation would cross it.
let mut store = headroom_store(dir, floor + 4 * MIB, floor);
let spec = VolumeSpec {
preallocate: 8 * MIB,
..VolumeSpec::default()
};
assert!(
store
.add_volume(VolumeId(1), DiskType::HardDrive, &spec)
.is_err()
);
assert!(!store.has_volume(VolumeId(1)));
}
// Mirrors Go's TestAddVolumeAllowsPreallocationWhereUnsupported: where
// preallocate_file is a no-op the reservation never happens, so it must
// not hold the create back.
#[test]
fn test_add_volume_allows_preallocation_where_unsupported() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let mut store = headroom_store(dir, floor + MIB, floor);
store.preallocate_supported = false;
let spec = VolumeSpec {
preallocate: 8 * MIB,
..VolumeSpec::default()
};
store
.add_volume(VolumeId(1), DiskType::HardDrive, &spec)
.unwrap();
}
// Mirrors Go's TestAddVolumeAllowsPlainVolumeAboveFloor and
// TestAddVolumeAllowsMergeVolumeBelowFloor: a volume reserving nothing is
// created either way, so growth is only held back when it would cross
// the floor.
#[test]
fn test_add_volume_allows_plain_volume_anywhere() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let mut store = headroom_store(dir, floor + MIB, floor);
store
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
FAKE_FREE.store(floor - MIB, Ordering::Relaxed);
store
.add_volume(VolumeId(2), DiskType::HardDrive, &VolumeSpec::default())
.unwrap();
}
// Mirrors Go's TestGrowthLoopStopsAtFloorWhenVolumesPreallocate: the
// master keeps asking for volumes while the disk sits just above its
// floor; each created volume reserves its full size, so the disk must
// not be driven below the floor.
#[test]
fn test_growth_loop_stops_at_floor_when_volumes_preallocate() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let preallocate = MIB;
// Room for 4 preallocated volumes above the floor once each create's
// metadata allowance is held back.
let create_cost = preallocate + VOLUME_CREATE_VIF_BYTES + VOLUME_CREATE_IDX_BYTES;
let mut store = headroom_store(dir, floor + 4 * create_cost, floor);
let spec = VolumeSpec {
preallocate,
..VolumeSpec::default()
};
let mut created = 0;
for i in 1..=20u32 {
if store
.add_volume(VolumeId(i), DiskType::HardDrive, &spec)
.is_ok()
{
created += 1;
FAKE_FREE.fetch_sub(create_cost, Ordering::Relaxed);
}
}
assert!(
FAKE_FREE.load(Ordering::Relaxed) >= floor,
"free space fell below the floor after {created} volumes"
);
// Exactly the room above the floor must be used. Checking only an
// upper bound would also pass when every create fails.
assert_eq!(created, 4);
}
// Mirrors Go's TestReserveFreeLocationChargesPickedReservation: a copy's
// pick and its .dat reservation are separate steps, so the picked
// location's cached free space must carry the charge at once or a second
// copy can spend the same headroom.
#[test]
fn test_reserve_free_location_charges_picked_reservation() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let need = 30 * MIB;
// 40 MiB above the floor: room for one 30 MiB reservation, not two.
let store = headroom_store(dir, floor + 40 * MIB, floor);
store.locations[0]
.available_space
.store(40 * MIB, Ordering::Relaxed);
let pred = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
assert_eq!(
store.locations[0].available_space.load(Ordering::Relaxed),
10 * MIB
);
assert_eq!(store.reserve_free_location(need, pred, None), None);
}
// Mirrors Go's TestReserveFreeLocationRechecksLiveDisk: the cached free
// space is refreshed only once a minute, so a stale-high value must not
// admit a reservation the live disk cannot fit.
#[test]
fn test_reserve_free_location_rechecks_live_disk() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let store = headroom_store(dir, floor + 5 * MIB, floor);
store.locations[0]
.available_space
.store(100 * MIB, Ordering::Relaxed);
let pred = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
assert_eq!(store.reserve_free_location(30 * MIB, pred, None), None);
}
// Mirrors Go's TestReleaseFreeLocationRestoresReservation: a failed copy
// must return its reservation, or the headroom stays booked until the
// next disk probe and blocks retries.
#[test]
fn test_release_free_location_restores_reservation() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let need = 30 * MIB;
// 40 MiB above the floor: room for one 30 MiB reservation, not two.
let store = headroom_store(dir, floor + 40 * MIB, floor);
store.locations[0]
.available_space
.store(40 * MIB, Ordering::Relaxed);
let pred = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
store.release_free_location(0, need);
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
}
// Mirrors Go's TestReleaseFreeLocationAfterProbeRefundsOnlyOwnCharge: a
// probe between reserve and release must not resurrect the charge — the
// live reading already forgot the failed copy's pending bytes, so
// refunding them would let two copies spend the same headroom.
#[test]
fn test_release_free_location_after_probe_refunds_only_own_charge() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let need = 30 * MIB;
let store = headroom_store(dir, floor + 40 * MIB, floor);
store.locations[0]
.available_space
.store(40 * MIB, Ordering::Relaxed);
let pred = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
// Mid-copy probe stores live-above-floor minus pending (as
// check_disk_space does): the charge survives it.
let loc = &store.locations[0];
let live_above_floor = loc
.min_free_space
.available_space(FAKE_FREE.load(Ordering::Relaxed), FAKE_ALL.load(Ordering::Relaxed));
loc.available_space.store(
live_above_floor.saturating_sub(loc.reserved_space.load(Ordering::Relaxed)),
Ordering::Relaxed,
);
assert_eq!(
loc.available_space.load(Ordering::Relaxed),
10 * MIB
);
assert_eq!(store.reserve_free_location(need, pred, None), None);
// The failed copy removes only its own charge.
store.release_free_location(0, need);
assert_eq!(
loc.available_space.load(Ordering::Relaxed),
40 * MIB
);
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
assert_eq!(store.reserve_free_location(need, pred, None), None);
}
// Mirrors Go's TestCommitFreeLocationSettlesLandedReservation: a copy
// that lands ends its pending charge without refunding the cache — the
// charge and the landed bytes cancel out.
#[test]
fn test_commit_free_location_settles_landed_reservation() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let need = 30 * MIB;
let store = headroom_store(dir, floor + 40 * MIB, floor);
store.locations[0]
.available_space
.store(40 * MIB, Ordering::Relaxed);
let pred = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
FAKE_FREE.fetch_sub(need, Ordering::Relaxed); // the copied bytes are on disk
store.commit_free_location(0, need);
let loc = &store.locations[0];
assert_eq!(loc.reserved_space.load(Ordering::Relaxed), 0);
assert_eq!(
loc.available_space.load(Ordering::Relaxed),
10 * MIB
);
// The next probe reads the landed usage and the ended charge agrees.
let live_above_floor = loc
.min_free_space
.available_space(FAKE_FREE.load(Ordering::Relaxed), FAKE_ALL.load(Ordering::Relaxed));
loc.available_space.store(
live_above_floor.saturating_sub(loc.reserved_space.load(Ordering::Relaxed)),
Ordering::Relaxed,
);
assert_eq!(
loc.available_space.load(Ordering::Relaxed),
10 * MIB
);
}
// Mirrors Go's TestCommitFreeLocationSettlesAsBytesLand: a running copy
// settles its charge as its bytes land on disk, so the live-space check
// sees the written part once — in the disk reading — not again inside
// the pending charge.
#[test]
fn test_commit_free_location_settles_as_bytes_land() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
let need = 30 * MIB;
let store = headroom_store(dir, floor + 70 * MIB, floor);
store.locations[0]
.available_space
.store(70 * MIB, Ordering::Relaxed);
let pred = |loc: &DiskLocation| loc.disk_type == DiskType::HardDrive;
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
// Half the copy's bytes are on disk now; settling that much charge
// keeps the second 30 MiB reservation inside the real headroom.
FAKE_FREE.fetch_sub(15 * MIB, Ordering::Relaxed);
store.commit_free_location(0, 15 * MIB);
assert_eq!(store.reserve_free_location(need, pred, None), Some(0));
let loc = &store.locations[0];
assert_eq!(loc.reserved_space.load(Ordering::Relaxed), 45 * MIB);
assert_eq!(loc.available_space.load(Ordering::Relaxed), 10 * MIB);
}
// Mirrors Go's TestMaybeAdjustVolumeMaxIgnoresFreeSpaceInsideFloor: space
// inside the floor adds no slots.
#[test]
fn test_maybe_adjust_volume_max_ignores_free_space_inside_floor() {
let _g = FAKE_DISK_LOCK.lock().unwrap();
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let floor = 1000 * MIB;
// 90 MiB above the floor is 3 x 30 MiB volumes; the rest is headroom.
let mut store = headroom_store(dir, floor + 90 * MIB, floor);
store.volume_size_limit.store(30 * MIB, Ordering::Relaxed);
store.locations[0].original_max_volume_count = 0;
store.maybe_adjust_volume_max();
assert_eq!(
store.locations[0].max_volume_count.load(Ordering::Relaxed),
3
);
}
// Mirrors Go's TestConfigureVolumeUpdatesSuperblock: configure must leave
// the .dat header and the .vif both on the new placement.
#[test]
+5
View File
@@ -95,6 +95,11 @@ impl Store {
};
let mut failed = false;
for loc in &self.locations {
// The stamp lives on the data directory, which stays writable
// when only the index directory is read-only.
if super::disk_location::is_read_only_mount(&loc.directory) {
continue;
}
if let Err(e) = write_vid_stamp(Path::new(&loc.directory), &stamp) {
tracing::warn!("write vid stamp in {}: {}", loc.directory, e);
failed = true;
+64 -12
View File
@@ -20,6 +20,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{debug, error, info, warn};
use crate::storage::disk_location::is_read_only_mount;
use crate::storage::idx;
use crate::storage::io::read_exact_at;
use crate::storage::io_error::{IoErrorTracker, StreakMark};
@@ -1635,7 +1636,10 @@ impl Volume {
Ok(file) => {
io.dat_file = Some(file);
}
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
Err(e)
if e.kind() == io::ErrorKind::PermissionDenied
|| e.kind() == io::ErrorKind::ReadOnlyFilesystem =>
{
io.dat_file = Some(open_volume_file(OpenOptions::new().read(true), &dat_path)?);
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
}
@@ -1717,12 +1721,24 @@ impl Volume {
&& !Path::new(&self.file_name(".idx")).exists()
&& self.current_dat_file_size_io(io)? > SUPER_BLOCK_SIZE as u64
{
self.rebuild_idx_file()?;
info!(
volume_id = self.id.0,
idx = %self.file_name(".idx"),
"rebuilt the index from the data file"
);
match self.rebuild_idx_file() {
Ok(()) => info!(
volume_id = self.id.0,
idx = %self.file_name(".idx"),
"rebuilt the index from the data file"
),
// The index dir refuses writes: the in-memory loader
// rebuilds the rows to a temp file instead of skipping
// the volume (mirrors Go's rebuiltIdx path).
Err(e) if is_read_only_mount(&self.dir_idx.read().unwrap()) => {
warn!(
volume_id = self.id.0,
error = %e,
"index dir is read-only; indexing .dat in memory"
);
}
Err(e) => return Err(e),
}
}
// Recover rows that deletes on a tiered read-only volume overwrote
@@ -1742,6 +1758,13 @@ impl Volume {
),
}
// The permission bits still allow writing on a read-only mount;
// a writable .dat beside an index directory that cannot record
// the index loads as no_write_or_delete, same as Go.
if !self.no_write_flags().0 && is_read_only_mount(&self.dir_idx.read().unwrap()) {
self.set_no_write_flag(NO_WRITE_OR_DELETE, true);
}
// A crash between the .dat append and the .idx append leaves a
// .dat tail no index entry covers. Re-index complete needles and
// cut an incomplete remainder before the index loads, so the
@@ -1959,18 +1982,28 @@ impl Volume {
let nm = CompactNeedleMap::load_from_idx(&mut idx_file, self.version())?;
io.nm = Some(NeedleMap::InMemory(nm));
} else {
// Missing .idx with existing .dat could orphan needles
// Missing .idx with existing .dat could orphan needles. On a
// read-only index dir the rows still come back, from a temp
// rebuild rather than the lost index (mirrors Go's
// rebuiltIdx path); writes stay blocked by no_write_or_delete.
let dat_path = self.file_name(".dat");
if Path::new(&dat_path).exists() {
let dat_size = fs::metadata(&dat_path).map(|m| m.len()).unwrap_or(0);
let dat_size = fs::metadata(&dat_path).map(|m| m.len()).unwrap_or(0);
if dat_size > SUPER_BLOCK_SIZE as u64
&& is_read_only_mount(&self.dir_idx.read().unwrap())
{
let (mut tmp_file, tmp_path) = self.rebuild_idx_to_temp()?;
let result = CompactNeedleMap::load_from_idx(&mut tmp_file, self.version());
let _ = fs::remove_file(&tmp_path);
io.nm = Some(NeedleMap::InMemory(result?));
} else {
if dat_size > SUPER_BLOCK_SIZE as u64 {
warn!(
volume_id = self.id.0,
".idx file missing but .dat exists with data; needles may be orphaned"
);
}
io.nm = Some(NeedleMap::InMemory(CompactNeedleMap::new()));
}
io.nm = Some(NeedleMap::InMemory(CompactNeedleMap::new()));
}
} else {
// Open read-write (create if missing)
@@ -6079,10 +6112,14 @@ pub fn scan_volume_file(
Ok(())
}
/// Whether `preallocate_file` reserves blocks on this platform; off Linux it
/// is a no-op, so a create must not be charged for space it will not reserve.
pub(crate) const PREALLOCATE_SUPPORTED: bool = cfg!(target_os = "linux");
/// Reserve disk blocks for a file without changing its visible size.
/// On Linux, uses `fallocate(FALLOC_FL_KEEP_SIZE)` to actually reserve blocks.
/// On other platforms, this is a no-op.
fn preallocate_file(file: &File, size: u64) {
pub(crate) fn preallocate_file(file: &File, size: u64) {
#[cfg(target_os = "linux")]
{
use std::os::unix::io::AsRawFd;
@@ -6111,6 +6148,21 @@ fn preallocate_file(file: &File, size: u64) {
}
}
/// Bytes the filesystem holds for the file, which exceeds its size after a
/// FALLOC_FL_KEEP_SIZE preallocate — Go's AllocatedSize.
pub(crate) fn allocated_file_size(file: &File) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
return file.metadata().map(|m| m.blocks() * 512).unwrap_or(0);
}
#[cfg(not(unix))]
{
let _ = file;
0
}
}
// ============================================================================
// Tests
// ============================================================================
@@ -2,8 +2,8 @@
//! `weed/storage/volume_idx_rebuild.go`.
use std::fs::{self, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
use std::io::{self, BufWriter, Seek, Write};
use std::path::{Path, PathBuf};
use crate::storage::idx;
use crate::storage::needle::Needle;
@@ -101,6 +101,41 @@ impl Volume {
}
result
}
/// Write the volume's .idx rows to a new temporary file and return it
/// rewound for reading, for a volume whose index directory cannot hold
/// the rebuilt index. Mirrors Go's `rebuildIdxToTempFile`; the caller
/// removes the file.
pub(crate) fn rebuild_idx_to_temp(&self) -> Result<(fs::File, PathBuf), VolumeError> {
let dat_path = self.file_name(".dat");
let tmp_path = std::env::temp_dir().join(format!("weed-idx-{}", uuid::Uuid::new_v4()));
let build = || -> Result<fs::File, VolumeError> {
let tmp_file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(&tmp_path)?;
let mut scanner = VolumeFileScanner4RebuildIdx {
writer: BufWriter::new(&tmp_file),
dat_size: fs::metadata(&dat_path)?.len() as i64,
version: self.version(),
stopped: false,
};
scan_volume_file(&dat_path, &mut scanner)?;
scanner.writer.flush()?;
drop(scanner);
let mut tmp_file = tmp_file;
tmp_file.seek(io::SeekFrom::Start(0))?;
Ok(tmp_file)
};
match build() {
Ok(f) => Ok((f, tmp_path)),
Err(e) => {
let _ = fs::remove_file(&tmp_path);
Err(e)
}
}
}
}
#[cfg(test)]
@@ -34,6 +34,7 @@ struct ListTablesResponse {
pub struct NamespaceClient {
base_url: String,
http: reqwest::Client,
api_key: Option<String>,
}
/// A namespace call that has not answered by now is not going to. Without this
@@ -41,12 +42,23 @@ pub struct NamespaceClient {
/// slot open forever, and the sweep never finishes.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_REDIRECT_HOPS: usize = 10;
impl NamespaceClient {
pub fn new(base_url: impl Into<String>) -> Self {
let http = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.connect_timeout(CONNECT_TIMEOUT)
// reqwest forwards custom headers on a follow, so only a same-origin
// hop is allowed: anywhere else would carry x-api-key to a listener
// the credential was never meant for.
.redirect(reqwest::redirect::Policy::custom(|attempt| {
if may_follow(attempt.previous(), attempt.url()) {
attempt.follow()
} else {
attempt.stop()
}
}))
.build()
// The builder only fails on a bad TLS backend, which would break
// every call anyway; a client with no timeouts is worse than a panic
@@ -58,6 +70,32 @@ impl NamespaceClient {
Self {
base_url: base_url.into().trim_end_matches('/').to_string(),
http,
api_key: None,
}
}
/// The catalog accepts an S3 credential as `x-api-key`; where the worker
/// already holds one for storage it authenticates the namespace calls too.
pub fn with_fallback(mut self, fallback: &crate::dataset::FallbackOptions) -> Self {
if let (Some(access), Some(secret)) = (
fallback.get("aws_access_key_id"),
fallback.get("aws_secret_access_key"),
) {
if !protected_transport(&self.base_url) {
tracing::warn!(
"catalog url {} exposes the x-api-key credential in cleartext",
self.base_url
);
}
self.api_key = Some(format!("{access}:{secret}"));
}
self
}
fn authed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
match &self.api_key {
Some(key) => request.header("x-api-key", key),
None => request,
}
}
@@ -65,8 +103,7 @@ impl NamespaceClient {
pub async fn list_all_tables(&self) -> Result<Vec<String>> {
let url = format!("{}/v1/table", self.base_url);
let response: ListTablesResponse = self
.http
.get(&url)
.authed(self.http.get(&url))
.send()
.await
.context("list tables")?
@@ -80,8 +117,7 @@ impl NamespaceClient {
pub async fn list_namespaces(&self, id: &[String]) -> Result<Vec<String>> {
let url = format!("{}/v1/namespace/{}/list", self.base_url, encode_id(id));
let response: ListNamespacesResponse = self
.http
.get(&url)
.authed(self.http.get(&url))
.send()
.await
.context("list namespaces")?
@@ -91,6 +127,30 @@ impl NamespaceClient {
Ok(response.namespaces)
}
/// Declare a table that does not exist yet; the catalog allocates the
/// location when none is given and returns the table description.
pub async fn declare_table(
&self,
id: &[String],
location: Option<&str>,
) -> Result<TableDescription> {
let url = format!("{}/v1/table/{}/declare", self.base_url, encode_id(id));
let mut body = serde_json::json!({ "id": id, "vend_credentials": true });
if let Some(location) = location {
body["location"] = location.into();
}
let description: TableDescription = self
.authed(self.http.post(&url))
.json(&body)
.send()
.await
.context("declare table")?
.error_for_status()?
.json()
.await?;
Ok(description)
}
/// Resolve a table to a location and the credentials to reach it. The
/// credentials expire, so a long compaction re-describes rather than
/// carrying one set for the whole job.
@@ -98,8 +158,7 @@ impl NamespaceClient {
let url = format!("{}/v1/table/{}/describe", self.base_url, encode_id(id));
let body = serde_json::json!({ "id": id, "vend_credentials": true });
let description: TableDescription = self
.http
.post(&url)
.authed(self.http.post(&url))
.json(&body)
.send()
.await
@@ -111,6 +170,41 @@ impl NamespaceClient {
}
}
/// Without a hop bound a catalog that redirects to itself keeps the request
/// alive until the call timeout, so the custom policy keeps the limit the
/// default one had.
fn may_follow(previous: &[reqwest::Url], next: &reqwest::Url) -> bool {
previous.len() < MAX_REDIRECT_HOPS
&& previous.last().is_some_and(|prev| same_origin(prev, next))
}
/// A redirect stays within an origin when scheme, host, and port all match, so
/// a catalog cannot bounce the api key onto a downgraded or foreign listener.
fn same_origin(from: &reqwest::Url, to: &reqwest::Url) -> bool {
from.scheme() == to.scheme()
&& from.host_str() == to.host_str()
&& from.port_or_known_default() == to.port_or_known_default()
}
/// A catalog url protects the api key when the hop is TLS or never leaves the
/// host; anything else sends it where the network can read it.
fn protected_transport(base_url: &str) -> bool {
let Ok(url) = reqwest::Url::parse(base_url) else {
return false;
};
if url.scheme() == "https" {
return true;
}
match url.host_str() {
Some("localhost") => true,
Some(host) => host
.trim_matches(['[', ']'])
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback()),
None => false,
}
}
fn encode_id(id: &[String]) -> String {
if id.is_empty() {
DELIMITER.to_string()
@@ -127,3 +221,56 @@ pub fn parse_id(encoded: &str) -> Vec<String> {
.map(|part| part.to_string())
.collect()
}
#[cfg(test)]
mod tests {
use super::{MAX_REDIRECT_HOPS, may_follow, protected_transport, same_origin};
#[test]
fn may_follow_bounds_hops_within_the_origin() {
let url = |u: &str| reqwest::Url::parse(u).unwrap();
let first = [url("https://c.local/ns")];
let next = url("https://c.local/other");
assert!(may_follow(&first, &next));
assert!(!may_follow(&[], &next));
assert!(!may_follow(&first, &url("http://c.local/other")));
let full: Vec<_> = (0..MAX_REDIRECT_HOPS)
.map(|i| url(&format!("https://c.local/{i}")))
.collect();
assert!(!may_follow(&full, &next));
}
#[test]
fn same_origin_rejects_scheme_and_port_hops() {
for (from, to, expected) in [
("https://c.local/ns", "https://c.local/other", true),
("http://c.local", "http://c.local:80/next", true),
("https://c.local", "http://c.local/next", false),
("https://c.local:8443", "https://c.local/next", false),
("https://c.local", "https://other.local/next", false),
] {
let from = reqwest::Url::parse(from).unwrap();
let to = reqwest::Url::parse(to).unwrap();
assert_eq!(same_origin(&from, &to), expected, "{from} -> {to}");
}
}
#[test]
fn protected_transport_covers_tls_and_loopback() {
for url in [
"https://catalog.internal:8443",
"http://127.0.0.1:8080",
"http://localhost",
"http://[::1]:8080",
] {
assert!(protected_transport(url), "{url} should be protected");
}
for url in [
"http://catalog.internal",
"http://127.0.0.1.evil.test",
"not a url",
] {
assert!(!protected_transport(url), "{url} should warn");
}
}
}
@@ -55,7 +55,7 @@ impl CleanupVersionsHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone())
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
}
}
@@ -59,7 +59,7 @@ impl CompactHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone())
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
}
}
@@ -58,7 +58,7 @@ impl OptimizeIndicesHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone())
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
}
}
+1 -1
View File
@@ -78,7 +78,7 @@ impl SortHandler {
}
fn client(&self) -> NamespaceClient {
NamespaceClient::new(self.namespace_url.clone())
NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback)
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ impl PreviewProvider for LancePreview {
}
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview> {
let client = NamespaceClient::new(self.namespace_url.clone());
let client = NamespaceClient::new(self.namespace_url.clone()).with_fallback(&self.fallback);
let table = dataset::open(&client, object_id, &self.fallback).await?;
let total_rows = table.dataset.count_rows(None).await.unwrap_or(0) as i64;
@@ -244,7 +244,13 @@ func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
t.Helper()
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader("{}"))
if err != nil {
t.Fatalf("build the namespace exists request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", env.accessKey+":"+env.secretKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
}
@@ -53,7 +53,13 @@ def main():
"aws_region": "us-east-1",
}
ns = ln.connect("rest", {"uri": args.namespace_url})
ns = ln.connect(
"rest",
{
"uri": args.namespace_url,
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
},
)
ns.create_namespace(ln.CreateNamespaceRequest(id=[args.bucket], mode="EXIST_OK"))
ns.create_namespace(
ln.CreateNamespaceRequest(id=[args.bucket, args.namespace], mode="EXIST_OK")
+19 -3
View File
@@ -45,7 +45,15 @@ def seed_table(namespace_url, storage, bucket, namespace, table, rows):
LanceDB reads through the catalog; the writing half is pylance, because the
namespace records where a table lives and does not carry its data.
"""
ns = ln.connect("rest", {"uri": namespace_url})
ns = ln.connect(
"rest",
{
"uri": namespace_url,
"header.x-api-key": (
f"{storage['aws_access_key_id']}:{storage['aws_secret_access_key']}"
),
},
)
ns.create_namespace(
ln.CreateNamespaceRequest(id=[bucket], mode="EXIST_OK")
)
@@ -98,7 +106,12 @@ def main():
print(f"lancedb {lancedb.__version__} connecting to {args.namespace_url}")
db = lancedb.connect_namespace(
"rest", {"uri": args.namespace_url}, storage_options=storage
"rest",
{
"uri": args.namespace_url,
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
},
storage_options=storage,
)
# 1. The catalog is browsable: the bucket is a namespace, and the table is
@@ -190,7 +203,10 @@ def main():
# declare-and-write - rather than a hang, a 404, or a half-made table.
pushdown = lancedb.connect_namespace(
"rest",
{"uri": args.namespace_url},
{
"uri": args.namespace_url,
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
},
storage_options=storage,
namespace_client_pushdown_operations=["CreateTable"],
)
@@ -0,0 +1,87 @@
package catalog_spark
import (
"fmt"
"strings"
"testing"
)
// TestSparkPartitionByFirstColumn creates tables partitioned by their first
// column. Spark (Iceberg Java) numbers the columns of a new table from 0 and
// leaves assigning fresh IDs to the catalog, so these partition specs arrive
// with source-id 0, which the catalog used to reject as a malformed request.
func TestSparkPartitionByFirstColumn(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
env, _, _ := setupSparkTestEnv(t)
namespace := "spark_partition_" + randomString(6)
output := runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
spark.sql("CREATE NAMESPACE iceberg.%s")
print("Namespace created")
`, namespace), env.icebergRestPort, env.s3Port)
if !strings.Contains(output, "Namespace created") {
t.Fatalf("namespace creation failed, output: %s", output)
}
cases := []struct {
name string
columns string
partitionBy string
values string
wantField string
wantPartitions int
}{
{
name: "identity",
columns: "id INT, name STRING",
partitionBy: "id",
values: "(1, 'a'), (2, 'b'), (3, 'c')",
wantField: "id",
wantPartitions: 3,
},
{
name: "bucket",
columns: "id BIGINT, name STRING",
partitionBy: "bucket(1, id)",
values: "(1, 'a'), (2, 'b'), (3, 'c')",
wantField: "id_bucket",
wantPartitions: 1,
},
{
name: "days",
columns: "ts TIMESTAMP, name STRING",
partitionBy: "days(ts)",
values: "(TIMESTAMP '2026-01-01 10:00:00', 'a'), (TIMESTAMP '2026-01-01 11:00:00', 'b'), (TIMESTAMP '2026-01-02 10:00:00', 'c')",
wantField: "ts_day",
wantPartitions: 2,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
tableName := fmt.Sprintf("iceberg.%s.first_col_%s", namespace, tc.name)
output := runSparkPySQL(t, env.sparkContainer, fmt.Sprintf(`
spark.sql("CREATE TABLE %[1]s (%[2]s) USING iceberg PARTITIONED BY (%[3]s)")
spark.sql("INSERT INTO %[1]s VALUES %[4]s")
count = spark.sql("SELECT COUNT(*) AS count FROM %[1]s").collect()[0]['count']
print(f"Row count: {count}")
partitions = spark.table("%[1]s.partitions")
print(f"Partition count: {partitions.count()}")
print("Partition fields: " + ",".join(f.name for f in partitions.schema["partition"].dataType.fields))
`, tableName, tc.columns, tc.partitionBy, tc.values), env.icebergRestPort, env.s3Port)
if !strings.Contains(output, "Row count: 3") {
t.Fatalf("create/insert on a table partitioned by %s failed, output: %s", tc.partitionBy, output)
}
if want := fmt.Sprintf("Partition count: %d", tc.wantPartitions); !strings.Contains(output, want) {
t.Errorf("expected %q, output: %s", want, output)
}
if want := "Partition fields: " + tc.wantField; !strings.Contains(output, want) {
t.Errorf("expected %q, output: %s", want, output)
}
})
}
}
@@ -41,6 +41,7 @@ deployment uses whatever address the gateway answers on:
spark.sql.catalog.lance org.lance.spark.LanceNamespaceSparkCatalog
spark.sql.catalog.lance.impl rest
spark.sql.catalog.lance.uri http://seaweed:9101
spark.sql.catalog.lance.headers.x-api-key <access-key>:<secret-key>
spark.sql.catalog.lance.storage.aws_endpoint http://seaweed:8333
spark.sql.catalog.lance.storage.allow_http true
spark.sql.catalog.lance.storage.aws_access_key_id …
@@ -46,6 +46,10 @@ def main():
.config("spark.sql.catalog.lance", "org.lance.spark.LanceNamespaceSparkCatalog")
.config("spark.sql.catalog.lance.impl", "rest")
.config("spark.sql.catalog.lance.uri", args.namespace_url)
.config(
"spark.sql.catalog.lance.headers.x-api-key",
f"{args.access_key}:{args.secret_key}",
)
.config("spark.sql.catalog.lance.storage.aws_endpoint", args.s3_endpoint)
.config("spark.sql.catalog.lance.storage.allow_http", "true")
.config("spark.sql.catalog.lance.storage.aws_access_key_id", args.access_key)
@@ -239,7 +239,13 @@ func (env *environment) tableBucketExists(t *testing.T, bucket string) bool {
t.Helper()
url := fmt.Sprintf("http://%s:%d/v1/namespace/%s/exists", env.bindIP, env.lancePort, bucket)
resp, err := http.Post(url, "application/json", strings.NewReader("{}"))
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader("{}"))
if err != nil {
t.Fatalf("build the namespace exists request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", env.accessKey+":"+env.secretKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("ask the namespace whether %s exists: %v", bucket, err)
}
+2 -1
View File
@@ -99,7 +99,8 @@ def connect(args):
"uri": args.catalog_url,
"warehouse": f"s3://{args.bucket}/",
"prefix": args.bucket,
"auth": {"type": "noop"},
"oauth2-server-uri": f"{args.catalog_url}/v1/oauth/tokens",
"credential": f"{args.access_key}:{args.secret_key}",
"s3.endpoint": args.s3_endpoint,
"s3.access-key-id": args.access_key,
"s3.secret-access-key": args.secret_key,
+14 -2
View File
@@ -83,7 +83,13 @@ def tally(dataset):
def resolve(args):
"""Ask the namespace where the table lives, the way the worker does."""
namespace = ln.connect("rest", {"uri": args.namespace_url})
namespace = ln.connect(
"rest",
{
"uri": args.namespace_url,
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
},
)
table_id = [args.bucket, args.namespace, args.table]
described = namespace.describe_table(ln.DescribeTableRequest(id=table_id))
return namespace, table_id, described.location, storage_options(args, described)
@@ -115,7 +121,13 @@ def main():
args = parser.parse_args()
if args.phase == "write":
namespace = ln.connect("rest", {"uri": args.namespace_url})
namespace = ln.connect(
"rest",
{
"uri": args.namespace_url,
"header.x-api-key": f"{args.access_key}:{args.secret_key}",
},
)
for parent in ([args.bucket], [args.bucket, args.namespace]):
namespace.create_namespace(ln.CreateNamespaceRequest(id=parent, mode="EXIST_OK"))
table_id = [args.bucket, args.namespace, args.table]
+28
View File
@@ -0,0 +1,28 @@
# End-to-end S3 Vectors conformance run:
# weed mini (cluster + lance catalog) + weed s3 (s3vectors port) +
# weed-vector-server (VectorService gRPC), then boto3 s3vectors calls.
WEED := ./weed
VEC := ./weed-vector-server
.PHONY: all test build clean FORCE
all: test
# No prerequisites: go/cargo decide for themselves whether a rebuild is needed.
$(WEED): FORCE
go build -o $(WEED) ../../weed
$(VEC): FORCE
cargo build --release --manifest-path ../../seaweed-vector/Cargo.toml -p weed-vector-server
cp ../../seaweed-vector/target/release/weed-vector-server $(VEC)
FORCE:
build: $(WEED) $(VEC)
test: build
./run_test.sh
clean:
rm -f $(WEED) $(VEC)
rm -rf mini-data
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
# Spin a mini cluster plus the vectors gateway and engine, run the boto3
# conformance subset, tear everything down.
set -euo pipefail
cd "$(dirname "$0")"
DATA=mini-data
rm -rf "$DATA"
PIDS=()
cleanup() {
kill "${PIDS[@]}" 2>/dev/null || true
rm -rf "$DATA"
}
trap cleanup EXIT
./weed mini -dir "$DATA" \
-s3=false -webdav=false -admin.ui=false &
PIDS+=($!)
./weed s3 \
-filer 127.0.0.1:8888 \
-ip 127.0.0.1 \
-ip.bind 127.0.0.1 \
-port 8334 \
-port.lance 9102 \
-port.vectors 9201 \
-vectors.grpc 127.0.0.1:9301 &
PIDS+=($!)
./weed-vector-server \
--namespace http://127.0.0.1:9102 \
--listen 127.0.0.1:9301 &
PIDS+=($!)
# Any HTTP response (even an auth rejection) means the lance catalog is up.
for _ in $(seq 1 60); do
code=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9102/v1/namespace/root/list || true)
[ "$code" != "000" ] && break
sleep 1
done
[ "${code:-000}" != "000" ] || { echo "lance catalog on :9102 never came up" >&2; exit 1; }
for _ in $(seq 1 60); do
(exec 3<>/dev/tcp/127.0.0.1/9301) 2>/dev/null && break
sleep 1
done
(exec 3<>/dev/tcp/127.0.0.1/9301) 2>/dev/null || { echo "vector server on :9301 never came up" >&2; exit 1; }
python3 -m pytest -xvs s3vectors_test.py
+81
View File
@@ -0,0 +1,81 @@
"""Boto3 conformance subset for the S3 Vectors API gateway.
Run via `make test` — a mini cluster, an s3 gateway with -port.vectors, and a
weed-vector-server are up by then.
"""
import boto3
import pytest
ENDPOINT = "http://127.0.0.1:9201"
BUCKET = "vectors-bucket"
INDEX = "idx"
@pytest.fixture(scope="module")
def vectors():
return boto3.client(
"s3vectors",
endpoint_url=ENDPOINT,
aws_access_key_id="test",
aws_secret_access_key="test",
region_name="us-east-1",
)
def test_vector_lifecycle(vectors):
vectors.create_vector_bucket(vectorBucketName=BUCKET)
buckets = [b["vectorBucketName"] for b in vectors.list_vector_buckets()["vectorBuckets"]]
assert BUCKET in buckets
vectors.create_index(
vectorBucketName=BUCKET,
indexName=INDEX,
dataType="float32",
dimension=4,
distanceMetric="euclidean",
)
idx = vectors.get_index(vectorBucketName=BUCKET, indexName=INDEX)["index"]
assert idx["dimension"] == 4
vectors.put_vectors(
vectorBucketName=BUCKET,
indexName=INDEX,
vectors=[
{"key": "a", "data": {"float32": [1, 0, 0, 0]}, "metadata": {"color": "red"}},
{"key": "b", "data": {"float32": [0.95, 0.05, 0, 0]}, "metadata": {"color": "blue"}},
{"key": "c", "data": {"float32": [0.9, 0.1, 0, 0]}, "metadata": {"color": "red"}},
],
)
got = vectors.get_vectors(
vectorBucketName=BUCKET, indexName=INDEX, keys=["a"], returnData=True, returnMetadata=True
)["vectors"]
assert got[0]["key"] == "a" and got[0]["metadata"]["color"] == "red"
listed = vectors.list_vectors(vectorBucketName=BUCKET, indexName=INDEX)["vectors"]
assert sorted(v["key"] for v in listed) == ["a", "b", "c"]
hits = vectors.query_vectors(
vectorBucketName=BUCKET,
indexName=INDEX,
queryVector={"float32": [1, 0, 0, 0]},
topK=2,
returnDistance=True,
returnMetadata=True,
filter={"color": {"$eq": "red"}},
)["vectors"]
# b is the second-nearest vector but blue, so an ignored filter would
# return ["a", "b"] here.
assert [h["key"] for h in hits] == ["a", "c"]
distances = {h["key"]: h["distance"] for h in hits}
assert distances["a"] == pytest.approx(0.0, abs=1e-6)
assert distances["c"] == pytest.approx(0.02, abs=1e-4)
assert all(h["metadata"]["color"] == "red" for h in hits)
vectors.delete_vectors(vectorBucketName=BUCKET, indexName=INDEX, keys=["b"])
listed = vectors.list_vectors(vectorBucketName=BUCKET, indexName=INDEX)["vectors"]
assert sorted(v["key"] for v in listed) == ["a", "c"]
vectors.delete_index(vectorBucketName=BUCKET, indexName=INDEX)
vectors.delete_vector_bucket(vectorBucketName=BUCKET)
+19 -8
View File
@@ -14,16 +14,27 @@ WEED_BINARY := $(BUILD_DIR)/weed
.PHONY: all
all: build
# Install templ if not present
# Install templ pinned to the go.mod version so generated code matches the runtime.
# Invoke the binary in Go's install dir so a different templ earlier on PATH cannot shadow it.
TEMPL_VERSION := $(shell go list -m -f '{{.Version}}' github.com/a-h/templ)
GOBIN := $(shell go env GOBIN)
ifeq ($(GOBIN),)
ifeq ($(shell go env GOOS),windows)
GOBIN := $(shell go env GOPATH | cut -d';' -f1)/bin
else
GOBIN := $(shell go env GOPATH | cut -d: -f1)/bin
endif
endif
TEMPL := $(GOBIN)/templ
.PHONY: install-templ
install-templ:
@which templ > /dev/null || (echo "Installing templ..." && go install github.com/a-h/templ/cmd/templ@latest)
@("$(TEMPL)" version 2>/dev/null | grep -qF $(TEMPL_VERSION)) || (echo "Installing templ $(TEMPL_VERSION)..." && go install github.com/a-h/templ/cmd/templ@$(TEMPL_VERSION))
# Generate templ files
.PHONY: generate
generate: install-templ static-gz
@echo "Generating templ files..."
@templ generate ./view
@"$(TEMPL)" generate ./view
@echo "Generated: $(TEMPL_GO_FILES)"
# Regenerate the gzipped static mirror embedded into the binary
@@ -43,7 +54,7 @@ clean-templ:
.PHONY: watch
watch: install-templ
@echo "Watching for templ file changes..."
@cd $(BUILD_DIR) && templ generate --watch
@cd $(BUILD_DIR) && "$(TEMPL)" generate --watch
# Build the main weed binary with admin component
.PHONY: build
@@ -80,11 +91,11 @@ lint:
# Format the code
.PHONY: fmt
fmt:
fmt: install-templ
@echo "Formatting Go code..."
@go fmt ./...
@echo "Formatting templ files..."
@templ fmt $(VIEW_DIR)
@"$(TEMPL)" fmt $(VIEW_DIR)
# Validate static files exist
.PHONY: validate-static
@@ -164,6 +175,6 @@ $(WEED_BINARY): $(TEMPL_GO_FILES) $(GO_FILES)
@$(MAKE) build
# Auto-generate templ files when .templ files change
%_templ.go: %.templ
%_templ.go: %.templ | install-templ
@echo "Regenerating $@ from $<"
@cd $(BUILD_DIR) && templ generate
@cd $(BUILD_DIR) && "$(TEMPL)" generate
+11
View File
@@ -111,6 +111,16 @@ func (cp *ConfigPersistence) ApplyMaintenanceConfigFromToml(v TomlConfig) error
}
ecChanged = true
}
if k := "maintenance.erasure_coding.max_shard_transfers"; v.IsSet(k) {
n := v.GetInt(k)
if n < 0 {
n = 0
} else if n > math.MaxInt32 {
n = math.MaxInt32
}
ecConf.MaxShardTransfers = &n
ecChanged = true
}
if !maintenanceChanged && !vacuumChanged && !balanceChanged && !ecChanged {
return nil
@@ -239,6 +249,7 @@ var pluginConfigSections = []pluginConfigSection{
"replica_placement": stringValue,
"strict_placement": boolValue,
"free_slots_deadband": int64Value,
"max_shard_transfers": int64Value,
},
// workers read collection_filter from the admin values, not the worker values
adminKeys: map[string]func(v TomlConfig, key string) *plugin_pb.ConfigValue{
+94
View File
@@ -307,3 +307,97 @@ preferred_tags = ["fast,SSD"]
t.Errorf("preferred_tags = %v, want [fast ssd]", got)
}
}
func TestApplyMaintenanceConfigFromTomlMaxShardTransfers(t *testing.T) {
dir := t.TempDir()
cp := NewConfigPersistence(dir)
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
[maintenance.erasure_coding]
fullness_ratio = 0.9
`)); err != nil {
t.Fatalf("apply fullness: %v", err)
}
ec := erasure_coding.LoadConfigFromPersistence(cp)
if ec.MaxShardTransfers != nil {
t.Fatalf("absent key persisted as %d, want unset", *ec.MaxShardTransfers)
}
if ec.FullnessRatio != 0.9 {
t.Fatalf("fullness_ratio = %v, want 0.9", ec.FullnessRatio)
}
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
[maintenance.erasure_coding]
max_shard_transfers = 0
`)); err != nil {
t.Fatalf("apply 0: %v", err)
}
ec = erasure_coding.LoadConfigFromPersistence(cp)
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 0 {
t.Fatalf("0: got %v, want sequential 0", ec.MaxShardTransfers)
}
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
[maintenance.erasure_coding]
max_shard_transfers = 4
`)); err != nil {
t.Fatalf("apply 4: %v", err)
}
ec = erasure_coding.LoadConfigFromPersistence(cp)
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 4 {
t.Fatalf("4: got %v, want 4", ec.MaxShardTransfers)
}
if err := cp.ApplyMaintenanceConfigFromToml(tomlConfig(t, `
[maintenance.erasure_coding]
max_shard_transfers = -3
`)); err != nil {
t.Fatalf("apply negative: %v", err)
}
ec = erasure_coding.LoadConfigFromPersistence(cp)
if ec.MaxShardTransfers == nil || *ec.MaxShardTransfers != 0 {
t.Fatalf("negative: got %v, want sequential 0", ec.MaxShardTransfers)
}
}
func TestApplyPluginConfigFromTomlMaxShardTransfers(t *testing.T) {
s := newPluginServer(t)
seed := &plugin_pb.PersistedJobTypeConfig{
JobType: "erasure_coding",
AdminRuntime: &plugin_pb.AdminRuntimeConfig{Enabled: true},
}
if err := s.GetPlugin().SaveJobTypeConfig(seed); err != nil {
t.Fatalf("seed: %v", err)
}
if err := s.ApplyPluginConfigFromToml(tomlConfig(t, `
[maintenance.erasure_coding]
replica_placement = "020"
`)); err != nil {
t.Fatalf("apply placement: %v", err)
}
cfg, err := s.GetPlugin().LoadJobTypeConfig("erasure_coding")
if err != nil || cfg == nil {
t.Fatalf("load: %v %v", cfg, err)
}
if _, ok := cfg.WorkerConfigValues["max_shard_transfers"]; ok {
t.Fatal("absent max_shard_transfers was written into worker config")
}
if err := s.ApplyPluginConfigFromToml(tomlConfig(t, `
[maintenance.erasure_coding]
max_shard_transfers = 0
`)); err != nil {
t.Fatalf("apply 0: %v", err)
}
cfg, err = s.GetPlugin().LoadJobTypeConfig("erasure_coding")
if err != nil || cfg == nil {
t.Fatalf("load 0: %v %v", cfg, err)
}
got, ok := cfg.WorkerConfigValues["max_shard_transfers"]
if !ok {
t.Fatal("max_shard_transfers = 0 missing from worker config")
}
if got.GetInt64Value() != 0 {
t.Fatalf("max_shard_transfers = %d, want 0", got.GetInt64Value())
}
}
+55 -25
View File
@@ -11,6 +11,7 @@ import (
"net/http"
"os"
"path"
"slices"
"strconv"
"strings"
"time"
@@ -50,9 +51,14 @@ func NewFileBrowserHandlers(adminServer *dash.AdminServer) *FileBrowserHandlers
// ShowFileBrowser renders the file browser page
func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Request) {
// Get path from query parameter, default to root
path := defaultQuery(r.URL.Query().Get("path"), "/")
// Normalize Windows-style paths for consistency
path = util.CleanWindowsPath(path)
dirPath := path.Clean(util.CleanWindowsPath(defaultQuery(r.URL.Query().Get("path"), "/")))
if !strings.HasPrefix(dirPath, "/") {
dirPath = "/" + dirPath
}
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) && restrictedBrowserPath(dirPath) {
http.Redirect(w, r, dash.P(r.Context(), "/admin?error=Insufficient permissions"), http.StatusSeeOther)
return
}
// Get pagination parameters
lastFileName := r.URL.Query().Get("lastFileName")
@@ -66,7 +72,7 @@ func (h *FileBrowserHandlers) ShowFileBrowser(w http.ResponseWriter, r *http.Req
}
// Get file browser data with cursor-based pagination
browserData, err := h.adminServer.GetFileBrowser(path, "", lastFileName, pageSize)
browserData, err := h.adminServer.GetFileBrowser(dirPath, "", lastFileName, pageSize)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to get file browser data: "+err.Error())
return
@@ -356,14 +362,46 @@ func (h *FileBrowserHandlers) validateAndCleanFilePath(filePath string) (string,
cleanPath = "/" + cleanPath
}
// Prevent path traversal attacks
if strings.Contains(cleanPath, "..") {
// Reject parent-directory components; names merely containing ".." are valid
if slices.Contains(strings.Split(cleanPath, "/"), "..") {
return "", fmt.Errorf("path traversal not allowed")
}
return cleanPath, nil
}
// restrictedBrowserPath reports whether a cleaned path lies inside the filer's
// /etc tree, which holds the credential store and cluster configuration.
func restrictedBrowserPath(cleanPath string) bool {
return cleanPath == strings.TrimSuffix(filer.DirectoryEtcRoot, "/") ||
strings.HasPrefix(cleanPath, filer.DirectoryEtcRoot)
}
// cleanReadPath validates the request's path parameter; read-only sessions are
// denied the /etc tree so the file browser cannot serve stored credentials.
func (h *FileBrowserHandlers) cleanReadPath(w http.ResponseWriter, r *http.Request) (string, bool) {
cleanPath, err := h.validateAndCleanFilePath(r.URL.Query().Get("path"))
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return "", false
}
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) && restrictedBrowserPath(cleanPath) {
writeJSONError(w, http.StatusForbidden, "Access to this path requires admin access")
return "", false
}
return cleanPath, true
}
// exportExcludedPrefixes lists the subtrees a metadata export skips; read-only
// sessions also lose /etc so stored credentials stay out of the dump.
func exportExcludedPrefixes(r *http.Request) []string {
prefixes := []string{filer.SystemLogDir}
if dash.IsReadOnlyRole(dash.RoleFromContext(r.Context())) {
prefixes = append(prefixes, strings.TrimSuffix(filer.DirectoryEtcRoot, "/"))
}
return prefixes
}
// fetchFileContent fetches file content via the filer gRPC service. It is
// used for the "view as text" path, so the maxBytes cap matches the 1 MB
// limit the caller already applies before invoking us.
@@ -377,9 +415,8 @@ func (h *FileBrowserHandlers) fetchFileContent(filePath string, timeout time.Dur
// gRPC service, so the admin file browser keeps working even when the filer
// is started with -disableHttp=true.
func (h *FileBrowserHandlers) DownloadFile(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("path")
if filePath == "" {
writeJSONError(w, http.StatusBadRequest, "File path is required")
filePath, ok := h.cleanReadPath(w, r)
if !ok {
return
}
inline := r.URL.Query().Get("inline") == "true"
@@ -419,9 +456,8 @@ func (t *responseWriteTracker) Write(p []byte) (int, error) {
// ViewFile handles file viewing requests (for text files, images, etc.)
func (h *FileBrowserHandlers) ViewFile(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("path")
if filePath == "" {
writeJSONError(w, http.StatusBadRequest, "File path is required")
filePath, ok := h.cleanReadPath(w, r)
if !ok {
return
}
@@ -524,9 +560,8 @@ func (h *FileBrowserHandlers) ViewFile(w http.ResponseWriter, r *http.Request) {
// GetFileProperties handles file properties requests
func (h *FileBrowserHandlers) GetFileProperties(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("path")
if filePath == "" {
writeJSONError(w, http.StatusBadRequest, "File path is required")
filePath, ok := h.cleanReadPath(w, r)
if !ok {
return
}
@@ -630,23 +665,18 @@ func (h *FileBrowserHandlers) GetFileProperties(w http.ResponseWriter, r *http.R
// FullEntry stream — the format weed shell fs.meta.load reads. Directories are
// walked recursively via the filer BFS metadata stream.
func (h *FileBrowserHandlers) ExportMetadata(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Query().Get("path")
if filePath == "" {
writeJSONError(w, http.StatusBadRequest, "File path is required")
return
}
cleanPath, err := h.validateAndCleanFilePath(filePath)
if err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
cleanPath, ok := h.cleanReadPath(w, r)
if !ok {
return
}
excludedPrefixes := exportExcludedPrefixes(r)
tracker := &responseWriteTracker{ResponseWriter: w}
err = h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
err := h.adminServer.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.TraverseBfsMetadata(r.Context(), &filer_pb.TraverseBfsMetadataRequest{
Directory: cleanPath,
ExcludedPrefixes: []string{filer.SystemLogDir},
ExcludedPrefixes: excludedPrefixes,
})
if err != nil {
return err
Loaded 100 of 317 files, more files were not shown because too many files have changed in this diff. Show more