Compare commits

..
Author SHA1 Message Date
dependabot[bot] 1c779c4731 build(deps): bump github/codeql-action from 4.39.3 to 4.39.4
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.3 to 4.39.4.
- [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.3...v4.39.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-23 18:14:59 +00:00
430ca2b585 filer: path- and method-scoped gRPC tokens (scope enforcement, fail closed) (#12904)
* filer: path- and method-scoped tokens on the filesystem gRPC service

* filer: close scoped admission and compatibility gaps

* filer: test subscription key ambiguity and retained write success

* filer: assert verified peer chains survive subscription fallback

* filer: keep a hard link's count and chunks together under a scoped token

A scoped write may keep a hard link the target already has, but the link
count it sends was stored as is, and its chunks could stay on the name
with the link dropped. Either let a scoped token delete its own name and
take the chunks of a name outside its grants with it: the forged count
reaches zero, or the detached name owns the shared chunks.

The handler recheck now refuses a scoped write that changes a stored
link's count or keeps its chunks without the link. Dropping the link
together with the data, and appending to a linked file, are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: leave subscriptions with a non-scope bearer to the existing verifier

The stream interceptor refused a SubscribeMetadata or SubscribeLocalMetadata
call whose bearer does not verify under the filer key unless the bearer was
a subscription token, and it checked that token with the peer stripped. With
no subscription key, or on an mTLS peer, the existing verifier admits such a
call, so filer.sync sending another cluster's admin token stopped.

When the bearer is no filer scope, the subscription verifier now decides on
the original context, as before scoped tokens. A scoped token still reaches
the refusal for scoped subscriptions, and malformed metadata is still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse scoped writes that would make ancestors outside the grant

A scoped create, append or rename checked only its target. The filer then
creates the target's missing ancestors up to the first one it finds, and
turns that one into a directory if it is a file, dropping its ttl. A token
granted /data/proj/ws could so promote the file /data/proj, or create /q and
/q/r for a grant /q/r/ws.

The scope now walks the same ancestors before admitting the write and
refuses one outside the write grants that is missing or not a directory. A
create with skip_check_parent_directory makes no ancestors and is not
walked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: require write grants for scoped lock mutations

* filer: document scoped signatures and read-only token upgrades

* filer: enforce WORM retention for scoped mutations

* filer: refuse scoped writes through shared hard links

* filer: drop series notes from scope comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse scoped subtree mutations across WORM rules

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:45:34 -08:00
Chris LuandClaude Opus 5.5 7933dd2205 test(s3vectors): drop the worker and CLI flags #12906 removed (#12911)
* test(s3vectors): start weed-worker with only --admin

weed-worker no longer accepts --namespace, --masters or --filer-group; it
takes the Lance Namespace and the filers from admin. The worker jobs passed
all three, so the worker exited on its arguments before registering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(s3vectors): let weed-vector-cli find the namespace through the masters

weed-vector-cli dropped --namespace and looks the Lance Namespace up among
the gateways the masters list, so the index job test failed on its
arguments once the worker could register.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:41:44 -08:00
Chris LuandClaude Opus 5.5 2d570ccb2f weed-vector: compare cgroup limit paths with / separators in the test (#12919)
Windows joins with a backslash, so the Windows desktop build failed
looks_up_the_process_group_and_its_ancestors.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:41:17 -08:00
vic6996-webandvic6996-web 01df591d59 glog: make -stderrthreshold work under -logtostderr and the default -alsologtostderr (#12916)
* glog: honor an explicit -stderrthreshold under -logtostderr and the default -alsologtostderr

* glog: print the goroutine dump of a FATAL to stderr under -logtostderr

* glog: keep a FATAL's goroutine dump in JSON lines under -log_json

* glog: let an explicit -alsologtostderr=true win under -logtostderr too

---------

Co-authored-by: vic6996-web <320442181+vic6996-web@users.noreply.github.com>
2026-11-23 08:40:38 -08:00
Chris LuandClaude Opus 5.5 ae0f1a2525 mount: delete chunks overwritten before their first publication (#12910)
* mount: send covered chunks no stored entry named, so the filer deletes them

A flush compacts the handle's chunks before it publishes them, dropping
chunks later writes fully cover. The filer deletes only the chunks the
stored entry loses and the ones the request itself covers, so a chunk
uploaded and then overwritten before any publication named it (a file
rewritten in place before close, like FFmpeg's +faststart pass) was left
on the volume servers with no reference.

Both the close flush and the periodic metadata flush now carry those
chunks along in the request, after the base snapshot, when the request's
own plain chunks still cover them; the filer compacts them out and
deletes them after the commit. Chunks rewritten by a merge are stamped 0
and the filer does not look into manifests, so a chunk that would show
through again is not sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test that flushes hand covered unpublished chunks to the filer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check each covered chunk against the request's own chunks

The coverage check compacted the dropped chunks together with the
request's, so one dropped chunk could hide another. Only the request's
chunks reach the filer with it: after a merge, whose chunks are stamped
0, an older dropped chunk hidden only by a newer dropped one would show
through and the filer would delete the merged chunk instead.

Each dropped chunk is now sent only if newer visible plain chunks of the
request hide all of its range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:30:55 -08:00
Chris LuandClaude Opus 5.5 a551b7c7e6 weed-vector: size the caches itself, drop the tuning, config-dir and CLI namespace flags (#12906)
* master, s3: an S3 gateway advertises its Lance Namespace port

The gateway registers with the master already; it now says which port its
Lance Namespace listens on, and ListClusterNodes returns it, so admin can
tell workers where the catalog is instead of each deployment configuring it.

* admin: tell workers where the Lance Namespace is

Each S3 gateway that serves a Lance Namespace is now in the cluster context
admin sends with every request, and a preview request carries the context
too, so a worker can be pointed at admin alone.

* seaweed-worker: take the filers and the Lance Namespace from admin

Admin names both with every request, as it does for the Go worker, so
weed-worker needs only --admin. --namespace is used when admin names no
namespace, as an admin or gateways from before they could do so name none.
--masters and --filer-group are accepted and ignored; the filer group is the
one the filers report.

* helm: weed-worker needs only the admin address

The Lance container no longer derives a namespace URL or passes the masters
and filer group; worker.namespaceUrl, when set, is the worker's fallback.

* s3: advertise the Lance port only once its listener has bound

A gateway whose Lance port was taken kept advertising it, so workers that
picked that gateway sent every Lance request to a port nobody served.
The listener now binds before the master registration, and the port
reaches the master only when the bind succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: stop waiting for the cluster context at the caller's deadline

The admin provider builds the context with context.Background(), so a
master outage held a preview, which now loads the context before it is
sent, past its own deadline. Loading the context now returns when the
caller's context ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: keep giving the Lance worker its masters, group and namespace

A worker image pinned to 4.55 or older needs the masters and the
namespace and exits without them, and a 4.56 worker under an older admin
needs the namespace. The chart now passes all three through the
environment, which a 4.56 worker reads only when admin names nothing,
and the namespace again defaults to the S3 service's Lance port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: give admin the filer group

Admin lists filers and S3 gateways from its own group, and the Lance
worker now takes its filers from admin, so with filer.filerGroup set the
worker had no filers. Admin now gets the group; an -filerGroup in
admin.extraArgs still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-worker: drop --namespace, --masters and --filer-group

Admin names the namespace and the filers with every request, so the worker
takes them from there alone. Handlers and the preview hold the admin-fed
cluster, which also carries the signing key. The live tests get the filer
through WEED_FILER and feed it to the worker as admin would.

* helm: drop worker.namespaceUrl

A worker from 4.56 takes the namespace from admin and has no option for it,
so the value could only reach a pinned older image; the environment still
gives one the S3 service's namespace, masters and filer group.

* weed-vector: size the caches itself, and drop the tuning and config-dir flags

The engine caches a quarter of the memory it may use, its cgroup limit or
the machine's, split 2:4:1 between file reads, loaded indexes and table
metadata as the three flags' defaults were, so a small pod is not
overcommitted and a large host is used. --read-cache-mb, --index-cache-mb,
--metadata-cache-mb, --nprobes and --exact-match-limit are gone, and with
them the perf test's cold mode. --config-dir is gone too: weed mini passes
the security.toml it finds there.

* weed-vector-cli: find the Lance Namespace through the masters

A table id is looked up in the namespace of an S3 gateway the masters
list, so --namespace is gone; a local path still needs no cluster.

* helm: weed-vector sizes its own caches

vector.readCacheMB and vector.nprobes are gone with the engine's flags; an
older pinned image keeps its own defaults.

* weed-vector: size the caches from the process's own memory cgroup

A systemd service is limited in its own group below the cgroup root, which
the root's limit file does not show. The engine now reads its group from
/proc/self/cgroup and takes the smallest limit of it and its ancestors.

* mini: leave an explicit WEED_VECTOR_SECURITY_TOML to the engine

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:10:01 -08:00
6adc9f0a21 mount: read chunks with filer-issued exact-file read tokens (#12800)
* mount: read chunks with filer-issued exact-file read tokens

* mount: preserve read authorization across delayed lookups and hard links

* mount: retain response tokens across read cache eviction

* mount: keep a shared read-token lookup alive when its first caller is cancelled

Token refreshes for one entry share a singleflight lookup that ran under
the first caller's context. An interrupted read cancelled that lookup, so
every other read of the entry waiting on it got no token, went out
unauthenticated, and failed with EIO on a volume server enforcing read
JWTs. Run the lookup detached from the caller (each attempt stays bounded
by the filer RPC wait) and let a cancelled caller stop waiting at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: serve a cached chunk past the cache cutoff instead of fetching it

The full-chunk read path consulted the chunk cache only for chunks below
the cache size cutoff. Read-auth and peer-sharing mounts cache every
chunk they upload, so a read-after-write of a high-offset chunk went to
the volume, where a read-auth mount has no token before the entry is
published.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: re-track read tokens when this mount renames an open file

Writeback mounts skip their own rename event, so only the subscriber
path re-tracked an open handle's chunks. After a local rename a token
refresh looked up the vacated name and the read failed. The rename
response, the subscriber rename and the surviving hard link now share
ReadAuth.TrackHandle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:07:14 -08:00
Chris LuandClaude Opus 5.5 548d8f1b42 weed-worker: take the cluster from admin, need only --admin (#12905)
* master, s3: an S3 gateway advertises its Lance Namespace port

The gateway registers with the master already; it now says which port its
Lance Namespace listens on, and ListClusterNodes returns it, so admin can
tell workers where the catalog is instead of each deployment configuring it.

* admin: tell workers where the Lance Namespace is

Each S3 gateway that serves a Lance Namespace is now in the cluster context
admin sends with every request, and a preview request carries the context
too, so a worker can be pointed at admin alone.

* seaweed-worker: take the filers and the Lance Namespace from admin

Admin names both with every request, as it does for the Go worker, so
weed-worker needs only --admin. --namespace is used when admin names no
namespace, as an admin or gateways from before they could do so name none.
--masters and --filer-group are accepted and ignored; the filer group is the
one the filers report.

* helm: weed-worker needs only the admin address

The Lance container no longer derives a namespace URL or passes the masters
and filer group; worker.namespaceUrl, when set, is the worker's fallback.

* s3: advertise the Lance port only once its listener has bound

A gateway whose Lance port was taken kept advertising it, so workers that
picked that gateway sent every Lance request to a port nobody served.
The listener now binds before the master registration, and the port
reaches the master only when the bind succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: stop waiting for the cluster context at the caller's deadline

The admin provider builds the context with context.Background(), so a
master outage held a preview, which now loads the context before it is
sent, past its own deadline. Loading the context now returns when the
caller's context ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: keep giving the Lance worker its masters, group and namespace

A worker image pinned to 4.55 or older needs the masters and the
namespace and exits without them, and a 4.56 worker under an older admin
needs the namespace. The chart now passes all three through the
environment, which a 4.56 worker reads only when admin names nothing,
and the namespace again defaults to the S3 service's Lance port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: give admin the filer group

Admin lists filers and S3 gateways from its own group, and the Lance
worker now takes its filers from admin, so with filer.filerGroup set the
worker had no filers. Admin now gets the group; an -filerGroup in
admin.extraArgs still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-worker: drop --namespace, --masters and --filer-group

Admin names the namespace and the filers with every request, so the worker
takes them from there alone. Handlers and the preview hold the admin-fed
cluster, which also carries the signing key. The live tests get the filer
through WEED_FILER and feed it to the worker as admin would.

* helm: drop worker.namespaceUrl

A worker from 4.56 takes the namespace from admin and has no option for it,
so the value could only reach a pinned older image; the environment still
gives one the S3 service's namespace, masters and filer group.

* seaweed-worker: keep the last known namespaces while admin lists none

When a master call fails, admin still sends its cached filers but no S3
gateways. With no --namespace fallback left, that emptied the worker's
namespaces and failed every Lance job until the master answered again,
though the gateways serve the namespace without it. The namespaces are
now kept like the filers are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: run the Lance container for the filer's S3 gateway and an external admin

The container was left out whenever the chart's own S3 gateway served no
Lance namespace. A filer's embedded gateway serves one too, and an external
admin names its cluster's, so both now get it; the namespace variable for a
pinned older worker is set only when the chart's gateway serves one.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:05:54 -08:00
Chris LuandClaude Opus 5.5 381f8d2c94 volume, seaweed-volume: re-forward a deleted EC read's delete to the holders that read it deleted (#12903)
* storage: re-forward a deleted EC read's delete to the holders that read it deleted

The retry used first-success routing, which can stop at another copy of
the primary shard (a quarantined local one, or a replica that never saw
the delete) and leave the reporting holder's other disk live. Probe each
primary shard holder with a one-byte read and forward to those answering
deleted; with no such holder, fall back to normal routing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: re-forward a deleted EC read's delete to the holders that read it deleted

Mirror Go: probe each primary shard holder with a one-byte read and
forward the delete to those answering deleted, so the retry cannot stop
at another copy and leave the reporting holder's other disk live; with
no such holder, fall back to normal routing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: bound each delete-retry probe with the read-hint timeout

A holder that keeps the stream open without answering held the delete's
reply, even after the reporting holder took the delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: bound each delete-retry probe with the read-hint timeout

Mirror Go: a stalled holder's probe gives up after EC_READ_HINT_TIMEOUT
and the retry moves on to the next holder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: bound each delete a retry forwards

A holder that answers the probe deleted but stalls on the delete held the
reply and the holders after it. The Rust server already bounds this call
at 10 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:18:40 -08:00
github-actions[bot] a98c9e2718 4.55 2026-11-23 03:01:05 +00:00
Chris LuandClaude Opus 5.5 1e98014713 volume, seaweed-volume: re-forward an EC delete whose read already sees the needle deleted (#12902)
* storage: forward an EC delete again when its read already sees the needle deleted

A delete that journaled a sibling disk's copy but failed on the holder's
first copy left the first copy live, and a retry from another server read
the needle deleted from the sibling and stopped before forwarding. Forward
the delete anyway, best effort, and still answer deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: forward an EC delete again when its read already sees the needle deleted

Mirrors the Go store: batch delete and HTTP DELETE re-forward the delete,
best effort, when a holder reports the needle deleted while this server's
index still has it live, so a holder disk the failed attempt missed
records it too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: re-forward an EC delete under the requested needle id

A failed header parse inside the read can overwrite n.Id, so the
deleted-read branch looks up and forwards the id the caller asked for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:57:59 -08:00
github-actions[bot] 23e8412e5c docs: regenerate star history chart 2026-11-23 00:40:30 +00:00
Chris LuandClaude Opus 5.5 64a64ca75b volume, seaweed-volume: an EC shard copy can require a disk type (#12901)
* volume_server.proto: let an EC shard copy name the target disk type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: an EC shard copy that names a disk type lands only on that medium

With disk_id 0 the copy auto-selects a disk, and the disk that already
holds the volume or its index wins regardless of medium. A move onto an
empty disk of another medium therefore landed beside the existing copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: EC shard moves pass the target disk type to the copy

ec.balance and the ec_balance worker plan a move onto disks of one type, but
the copy only named a disk id, and the master reports 0 (auto-select) for a
disk that holds nothing yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: an EC shard copy that names a disk type lands only on that medium

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: an EC blob delete records on every local copy of the volume

A volume mounted on several disks of one server has one runtime per disk,
each with its own deletion set, and a shard read checks the runtime of the
disk holding the shard. The delete stopped at the first runtime, so a read
of a shard on another disk still returned the deleted needle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: an EC blob delete records on every local copy of the volume

Mirrors the Go handler: each disk's runtime of the volume keeps its own
deletion set, so the delete is journaled on every runtime, not the first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: a typed EC shard copy yields to the shard's file on another medium

The mount walks disks in order and loads the first file of the shard it
finds, so a copy placed on the requested medium while another disk still
holds an unmounted file of that shard could leave the old file mounted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: a typed EC shard copy yields to the shard's file on another medium

Mirrors the Go selector.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: a typed shard move refused by its pinned disk lets the server pick

Balancers pin the destination disk from the medium its mounted shards
report, which can differ from the disk's own medium after encoding spilled
onto another one. The server refuses such a disk before copying anything,
so the move now retries once with the server picking a disk of the type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: name the requested disk type in a pinned-disk refusal

Same wording as the Go server, which movers match to retry with a
server-picked disk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: an EC blob delete records on the first local copy last

A retry on this server resolves the volume through its first copy, so a
delete that fails on another copy left the first one tombstoned and the
retry stopped there. Locate the needle on every copy first, then journal
the others before the first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: an EC blob delete records on the first local copy last

Mirrors the Go handler: a retry on this server resolves the volume
through its first runtime, so that runtime journals after the others and
a failure on any other leaves it live for the retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: a local EC delete records on every local copy

When this server holds the shard, the distributed delete journals locally
instead of calling VolumeEcBlobDelete on itself, and that path journaled
only the first runtime. Record on every runtime, the first last, as the
handler does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:02:01 -08:00
Chris LuandClaude Opus 5.5 15488c1af6 storage, seaweed-volume: ask every delisted EC shard holder, keep a reinstalled hint (#12900)
* storage: ask every delisted EC shard holder for a delete

Any one delisted holder may have journaled the needle's delete, but the
hint read stopped at the first holder that answered live. Ask each one
under its own deadline and take a deleted answer from any; forget only
the holders that failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: keep an EC read hint a lookup reinstalled during a failed read

Comparing addresses cannot tell a hint from one a lookup removed and
installed again for the same holder while the read was in flight, and
that holder may have journaled a delete in between. Count hint changes
and forget failed holders only if none happened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: take a deleted EC shard answer as soon as it arrives

A deleted answer was kept only if the stream ended or failed after it;
under the read hint's timeout, a holder that stalled after answering
deleted lost the answer and the read rebuilt the needle. Return on the
deleted message instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: ask every delisted EC shard holder for a delete

Mirror Go's askEcShardReadHints: any one delisted holder may have
journaled the needle's delete, but the hint read stopped at the first
holder that answered live. Ask each one under its own timeout, take a
deleted answer from any, and forget only the holders that failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: keep an EC read hint a lookup reinstalled during a failed read

Mirror Go's ShardReadHintsRevision: comparing addresses cannot tell a
hint from one a lookup removed and installed again for the same holder
while the read was in flight. Count hint changes and forget failed
holders only if none happened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: forget failed EC read hints when another holder answers deleted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: forget failed EC read hints when another holder answers deleted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: keep EC read hint revisions unique across volume remounts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:09:11 -08:00
Chris LuandClaude Opus 5.5 c967ba4a7a storage, seaweed-volume: ask a delisted EC shard holder before rebuilding the shard (#12899)
* storage: ask a delisted EC shard holder before rebuilding the shard

A complete lookup that places a shard nowhere drops its holder from the
map deletes route by. That holder may still answer, and may be the one
that journaled a needle's delete, which the other shards cannot know.
Keep it as a read hint that reads try before reconstructing and drop
once it fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: ask a delisted EC shard holder before rebuilding the shard

Mirrors Go: a complete lookup that places a shard nowhere moves its
cached holders to read hints, which fetch_one_interval tries before
reconstructing and drops once they fail. Deletes and recovery keep
using only the placed locations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: test reads asking a delisted EC shard holder

Mirrors the Go read-path tests: a delisted holder that journaled the
delete answers before the local shards rebuild the needle, and an
unreachable one is dropped while the read rebuilds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: take only a deleted answer from a delisted EC shard holder

A delete made after the delisting is journaled on a listed holder, so
the delisted one still answers live. Returning its bytes skipped the
reconstruction that asks the listed holders and finds that delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: take only a deleted answer from a delisted EC shard holder

Mirrors Go: a live answer from a read hint may predate a delete that
went to a listed holder, so fetch_one_interval goes on to the direct
read and reconstruction instead of returning it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: bound the read asking a delisted EC shard holder

A delisted holder may have stopped answering, and the hint read had no
deadline over its stream. Only its deleted answer is used, so ask for
one byte under a short deadline; a timeout drops the hint like any
other failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: drop only the read hint a failed EC read used

A lookup can replace a shard's hint while a read of the old one is in
flight; that read's failure then dropped the new hint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: bound the read asking a delisted EC shard holder

Mirrors Go: ask the hint for one byte under EC_READ_HINT_TIMEOUT, since
only its deleted answer is used; a timeout drops the hint like any
other failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: drop only the read hint a failed EC read used

Mirrors Go: a lookup can replace a shard's hint while a read of the old
one is in flight, and that read's failure dropped the new hint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: keep fetch_one_interval's doc comment on the function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 12:28:45 -08:00
Chris LuandClaude Opus 5.5 c46dea9b6a seaweed-volume, storage: a shard the master places nowhere is not a known location (#12898)
* seaweed-volume: a shard the master places nowhere is not a known location

The master answers LookupEcVolume with every shard slot it tracks, so a
shard whose holders are all down comes back with no locations. The cache
kept those entries. They overwrote the cached address of a holder that
was only restarting, counted toward the reply's data-shard guard, which
therefore always passed, and made the map look neither short nor
complete, so it was re-checked only every 7 minutes. Nothing marked it
stale meanwhile: a read never tries a shard with no address.

A shard with no location is now left out of the reply, as Go's
cachedLookupEcShardLocations does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: count only placed shards toward an EC lookup's completeness

The master answers every shard slot, so len(ShardIdLocations) is 32
whatever is up, and the guard that should keep a partial reply from
replacing a complete cache never fired. A reply placing fewer than the
data shards now fails the lookup and leaves the cache as it was, as the
Rust server does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: fill a cold EC location cache from a partial lookup

A reply placing fewer than the data shards no longer reaches the cache
at all, so a cold cache stays empty and a read cannot go straight to a
shard whose holder is up, as it could before the guard counted placed
shards. Take the holders it names for shards the cache does not know,
without touching known shards or the refresh time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: fill a cold EC location cache from a partial lookup

write_back_shard_locations refused a reply placing fewer than the data
shards before writing anything, so a read on a cold cache kept an empty
map and could not fetch a shard directly from a holder the master did
name. A partial now fills only the shards the cache does not know,
leaves the refresh time alone and marks the map stale, as Go does. The
scrub still refuses a partial reply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: a partial EC lookup puts the holders it names first

A partial reply only filled shards the cache did not know, so a shard
that moved while the replies stayed partial kept its old address: a
failed direct read marked the map stale, the next partial reply skipped
the shard again, and the read fell back to a reconstruction that the
partial outage could not serve. A partial reply now puts the holders it
names ahead of the cached ones, which stay as fallback. Other shards and
the refresh time stay as they were.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: drop a shard the master places nowhere from the location cache

Leaving shards with no location out of the reply let a complete reply
keep a former holder's cached address for a shard the master now places
nowhere. An EC delete tried that address first: an offline peer failed
the delete without the fallback to other shard holders, and a peer that
had unmounted the volume acknowledged it without writing a tombstone.

The reply now keeps every slot and only located shards count toward its
completeness. A complete reply drops a shard it places nowhere, as Go's
delete-then-append does, and a partial reply's empty slots add nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: a partial EC lookup puts the holders it names first

fill_shard_location_gaps took a partial reply's holders only for shards
the cache did not know, so a shard that moved while the replies stayed
partial kept its old address and a read could not reach it directly.
merge_partial_shard_locations puts the holders the reply names ahead of
the cached ones, which stay as fallback, as Go does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 11:29:41 -08:00
a2df801e6d filer: rename a file over a file in place on a store without transactions (#12894)
* filer: run a file rename again when the store refuses its commit

TiKV refuses an optimistic transaction's commit when another writer
committed one of its keys after it began. A rename's transaction moves the
source key, so a concurrent write of the file, through another filer for
instance, failed the rename with "move commit error: write conflict".
Standalone writes run again after such a conflict since #12798, but a
rename's transaction belongs to the rename, and it gave up.
StreamRenameEntry also sent the rename's responses before the commit, so
the client had already moved the file locally when the store refused it.

- The TiKV store reports such a refusal as filer.ErrTransactionConflict.
- A file rename runs its transaction again after it, up to five times; the
  new run reads what the other writer stored and moves that. A rename that
  copied or deleted a remote object on the way is not run again.
- On a store whose transactions keep their writes to themselves
  (filer.IsolatingTransaction: SQL, TiKV), a file rename holds its stream
  responses until the commit: a refused rename sends none, and one that
  runs again sends them once. A directory rename still streams its
  children's responses as it moves them, which keeps the client of a long
  rename from timing out, and is not run again.
- Every failed run releases its commit stamps and rolls back, the "is not
  empty" refusal included.

Tests: filer_grpc_server_rename_conflict_test.go, with a store that keeps a
transaction's writes until its commit and can refuse it, and
tikv_store_commit_test.go (-tags tikv). On master the retry, refused-commit
and remote-file tests fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: run a rename again only when its transaction covers every write

With path-specific stores configured, the writes under their prefixes do
not go through the default store's transaction: a parent directory a rename
creates at its destination there stays when the commit is refused, and a
rename run again finds it and announces only the file's move, so peers
replaying the events never learn of the parent.

IsolatingTransaction now holds only when no path-specific store is
configured, and AtomicRenameEntry checks it too before running a rename
again, as StreamRenameEntry does through its held responses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: finish a committed rename before its held responses go out

StreamRenameEntry sent its held responses before the work the commit leaves
(metadata events, chunk deletions, remote copies). A client that stops
reading without closing the stream blocks Send on flow control, and that
work then never ran. It now runs first; the responses still follow the
commit.

A file with a remote object no longer holds its responses: its remote copy
after the commit is part of that work, and the client should not wait for
it. It streams as it moves, as before, and is not run again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: rename a file over a file in place on a store without transactions

A rename over an existing file deleted the target, then created the renamed
entry. On a store without transactions (the Redis stores, Cassandra,
MongoDB, etcd and the like) the delete shows at once, and the rename's path
locks fence only the filer running the rename, so a lookup or listing
through another filer could find neither name and return ENOENT; POSIX
rename keeps the new path resolvable throughout. A target deleted through
another filer between the rename's lookup and its delete failed the rename
outright ("no entry is found in filer store").

On such a store, a plain file renamed over a plain file is now written over
the target in one store write (Filer.ReplaceFileForRename, an InsertEntry,
which also lists the entry on Redis and drops the target's hard link after
the write). The target's chunks are still deleted after the rename, unless
the target's other hard links still use them, and subscribers get the same
delete-then-rename events. Stores with transactions keep delete-then-create:
no other reader sees the gap, and a target that went meanwhile fails the
transaction cleanly. So do setups with path-specific stores, whose stores
may take an insert over an existing entry differently (a SQL store inside a
transaction aborts it), and directories and entries with a remote object.
filer.WithoutTransactions tells the case apart; BeginTransaction marks it
next to IsolatingTransaction.

Tests: filer_grpc_server_rename_inplace_test.go. On master the target goes
missing after the delete, and a target deleted meanwhile fails the rename;
the transaction, path-specific store, directory and hard link tests guard
what stays as it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: let the store say that its transactions isolate a rename

Whether a rename's responses wait for the commit, and whether it may run
again, was inferred from the context BeginTransaction returned and from
whether any path-specific store was configured. Neither holds up:

- A store may hand back a transaction context that its writes do not use:
  YDB begins a table-service transaction, and its statements run through
  the query service outside it. A store now says so itself, through
  IsolatingTransactionStore, which the TiKV store implements. Any other
  store keeps sending a rename's responses as the entries move and does not
  run it again, as before this PR.
- A path-specific store only matters for the paths it holds.
  Filer.TransactionCovers asks whether the rename's source and destination
  live in the default store: a rename that stays there holds its responses
  and may run again, and one that writes into a path-specific store does
  neither.

A rename that may not run again still must not announce changes before its
commit, so a file with a remote object holds its responses too. So that its
remote copy after the commit does not delay them, the held responses go out
while the rename finishes, and the call returns once both are done.

A held response checks the stream's context, so a rename whose client went
away before its first response is rolled back, as when the responses go
out at once, instead of committed unseen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: read the target again and keep its parents when a rename writes in place

The in-place write skipped what delete-then-create did on its way:

- Another filer can turn the target into a directory after the rename
  looked it up, by storing a child under it. The delete refused a non-empty
  directory, while the in-place write stored the file over it and stranded
  the child. The target is now read again right before the write, and a
  directory is refused. A store without transactions has no conditional
  write, so this leaves the window the delete-first path has between its own
  read of the target and its delete.
- Another filer can delete the target's directory after the lookup.
  CreateEntry creates missing parents after its insert, and the rename
  announces them before the move; the in-place write now does the same.
- The in-place write also applies CreateEntry's checks of the name (length,
  dot segments).

Tests: a target that became a directory, and a target whose directory went,
both right after the rename's lookup.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: the SQL stores isolate their transactions too

AbstractSqlStore takes the sql.Tx its context carries for every entry call
(getTxOrDB) and every KV call (kvDB, also when KV has a pool of its own),
so the SQL stores built on it meet what IsolatingTransactionStore asks. A
file rename on them holds its responses until the commit again, as it did
before the declaration became explicit; it is never run again, since no
SQL store reports ErrTransactionConflict.

Bucket tables are created and dropped outside the transaction, which a
file rename does not do.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: write a rename in place only on a store that says its insert replaces an entry

The in-place write took "the store keeps no transaction" to mean that an
insert over an existing entry replaces it. That does not follow: the
Tarantool store's insert is an upsert that assigns only the entry's data,
so the row keeps the replaced entry's expire_at, and a file renamed over an
expiring one would expire with it.

A store now says so itself, through OverwritingStore: it keeps no
transaction, and its InsertEntry replaces the stored entry at once and
whole, with its expiry and its listing. The three Redis stores declare it:
their SET replaces value and expiry, and the insert lists the name whether
or not it was listed. Every other store keeps delete-then-create, as before
this PR. That includes the embedded default store, where each filer has a
store of its own and the rename's path locks already hide the gap.

This replaces the comparison of the context BeginTransaction returns;
BeginTransaction is back to what it was.

Tests: for each Redis store, an InsertEntry over an expiring entry leaves
the second entry, no expiry and one listing (RUN_REDIS_TESTS=1). A store
that does not declare it keeps delete-then-create, with and without
transactions. The in-place write over one of two hard links, and over the
last one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* abstract_sql: check that a transaction's writes take its own handle

sqlmock serves a pool and its transactions from one mock, so the write
expectations also pass for entry writes made through store.DB. Assert that
getTxOrDB and kvDB return the *sql.Tx the context carries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:35:57 -08:00
907c46fe47 mount: answer ESTALE for an inode the kernel holds but whose name is gone (#12887)
* mount: answer ESTALE for an inode the kernel holds but whose name is gone

A rename over an existing file drops the replaced inode's path in
InodeToPath.MovePath as soon as the rename's response arrives from the
filer, which sends it before it commits. Until the RENAME reply reaches
the kernel, the kernel still maps the name to the old inode, so an open,
stat, access or xattr call resolved in that window reaches maybeReadEntry
or AcquireHandle for an inode without a path and fails with ENOENT,
although the name exists. A rename made through another mount opens the
same window for as long as this kernel keeps the name's dentry. A process
polling a file that another one replaces with tmp + rename sees sporadic
ENOENT; a slow commit turns the window into a burst.

While the kernel has not forgotten the inode, answer ESTALE: the kernel
redoes the path walk once with LOOKUP_REVAL and opens the current entry,
as on NFS. A forgotten inode keeps ENOENT.

One writer replacing a file with tmp + os.replace and four readers opening
it in a loop on one mount, for 120 s: each reader got 897k-967k ENOENT
before (130k reads succeeded), none after (272k reads). With the readers
on a second mount that also lists the directory: 1,277-1,550 errors per
reader before, 7-13 after, at about 140 replacements a second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: answer ESTALE for a pathless inode only on Linux

Only the Linux VFS redoes a path walk on ESTALE (LOOKUP_REVAL). FUSE on
macOS and FreeBSD purges the vnode's name cache when GETATTR or OPEN
answers ENOENT, so the next lookup finds the replacing file; ESTALE skips
that purge and keeps failing until the entry times out. WinFsp maps the
unknown errno to EIO. Keep ENOENT there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:34:36 -08:00
Chris LuandClaude Opus 5.5 2037af1a37 erasure_coding: report and check the encode run when verifying a shard set (#12893)
* volume: report the encode run in VolumeEcShardsInfo

Go and Rust volume servers now fill EcShardConfig.encode_ts_ns from the
mounted EC volume's .vif, next to the block layout they already report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* erasure_coding: keep the source when holders serve different encode runs

VerifyShardsAcrossServers records each holder's encode run, and
RequireAgreedEncodeRun fails when holders that report one disagree. The
encoder checks it before deleting the source volume, so a shard set that
only looks complete by shard ids does not replace the source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* erasure_coding: refuse a holder that reports more than one encode run

A holder whose disks serve shards of different encode runs reports
MixedEncodeRuns, and RequireAgreedEncodeRun fails on it even when no
other holder answers or every other holder agrees on one run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: report mixed encode runs across local disks in VolumeEcShardsInfo

The reply listed shards from every disk under the first disk's encode
run. When the shard-bearing disks of a volume hold different nonzero
runs, Go and Rust volume servers now report MixedEncodeRuns instead, so
the source-deletion check sees the conflict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: refuse an EC shard copy of another encode run than the mounted one

VolumeEcShardsCopy committed the copied .vif and reopened replaced shards
without updating the mounted volume's encode run, so the holder kept
reporting the old run while serving the new bytes. Go and Rust volume
servers now stage the .vif before anything is committed and fail with
FailedPrecondition when it names a nonzero run different from a run this
server mounts for the volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: list only mounted shards of every disk in Rust VolumeEcShardsInfo

The Rust reply listed every shard slot of the first disk's runtime, with
unmounted slots as size-0 entries, and skipped shards mounted on other
disks. Callers build each holder's shard bits from this list, so a Rust
holder counted as holding shards it did not have. The reply now lists the
mounted shards of every local disk, each id once, as Go does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check the source encode run of an EC shard copy without a .vif

A copy that leaves out the .vif could still replace a mounted shard with
another encode run's bytes. Fetch the source .vif for the run check in
every copy, and install it only when asked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: refuse to serve EC files of a volume held from two encode runs

CopyFile looks each requested file up on its own, so a server that holds
a volume's shards on one disk from one encode run and its .vif on another
disk from a different run would hand a copier mismatched files. Refuse
the copy when the .vif files of this server disagree on a nonzero run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: refuse a rebuild whose holders serve different encode runs

The rebuild groups holders by volume id and collection only. When they
serve two encode runs, the copied shards land beside the first run's
.vif and .ecx and the rebuild regenerates from the mixed set. Before
copying, ask every holder for its run and refuse unless they agree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: bound each holder query in the rebuild's encode-run check

A holder that accepts the connection but never answers VolumeEcShardsInfo
kept the rebuild waiting forever. Give each holder its own deadline; one
that times out is skipped like an unreachable holder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: check only the rebuilder and copy sources for the encode run

The rebuild copies each shard from its first listed holder. Extra copies
are never read, so asking them for their run only adds servers that can
stall the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: do not copy from a source whose encode run went unchecked

A copy source whose VolumeEcShardsInfo query fails or times out has an
unknown run. The copy fence on the rebuilder compares a source's run with
the run the rebuilder mounts, so on a rebuilder that holds none of the
volume's shards nothing checks it, and its shards could join a rebuild of
another run. The rebuild now skips such a source like a failed copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: leave holders of shards the rebuilder has out of the run check

The rebuild uses a shard the rebuilder already holds and never reads its
other listed holders, but the run check still asked the first of them. A
stale replica listed first for such a shard refused a rebuild that would
not touch it. Pick the holders to check the way prepareDataToRecover
picks its copy sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 10:32:05 -08:00
Chris LuandClaude Opus 5.5 ec87407c0d ec balance: don't let leftover shards of an earlier encode win dedup or move (#12888)
* ecbalancer: keep the majority encode run's copy when removing a duplicate shard

The dedup kept the copy on the node with the most free slots without
comparing copies. When a failed encode left a shard behind and a retry
encoded it again elsewhere, it could keep the stale copy and delete the
fresh one. Nodes now record each disk's encode identity; when a shard's
copies differ, only a copy from the run that holds most of the volume's
shards is kept, and the shard is left alone when no run has a clear
majority or none of its copies is from that run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec.balance, ec_balance: pass each disk's encode identity to the planner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ecbalancer: keep only a complete encode run's copy, freeze conflicted volumes

A majority counted over a filtered snapshot can pick the wrong run, and a
shard left with conflicting copies could still be moved onto its other
copy by a later phase. Mixed-run duplicates are now resolved only in
favour of the one reported run that has every shard id, counted per disk,
since filters can hide shards but not add them. Otherwise the volume is
frozen: no phase of this plan moves its shards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec_balance: freeze EC volumes that still have a plain replica

Their shards belong to the encoder until the plain replicas are gone. They
stay in the plan's load counts but no phase moves or dedups them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ecbalancer: refuse dedup when an unreported run is also complete

A copy that carries no encode identity may be the newer set, so a second
complete run that does report one cannot be kept over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ecbalancer: freeze a volume whose shard copies on one node disagree

A shard held on two disks of one node at different encode runs has no
duplicate on another node, so dedup skipped it, and a later move could
take the stale copy and delete the fresh one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 10:31:31 -08:00
7cc8a8a445 filer: run a file rename again when the store refuses its commit (#12892)
* filer: run a file rename again when the store refuses its commit

TiKV refuses an optimistic transaction's commit when another writer
committed one of its keys after it began. A rename's transaction moves the
source key, so a concurrent write of the file, through another filer for
instance, failed the rename with "move commit error: write conflict".
Standalone writes run again after such a conflict since #12798, but a
rename's transaction belongs to the rename, and it gave up.
StreamRenameEntry also sent the rename's responses before the commit, so
the client had already moved the file locally when the store refused it.

- The TiKV store reports such a refusal as filer.ErrTransactionConflict.
- A file rename runs its transaction again after it, up to five times; the
  new run reads what the other writer stored and moves that. A rename that
  copied or deleted a remote object on the way is not run again.
- On a store whose transactions keep their writes to themselves
  (filer.IsolatingTransaction: SQL, TiKV), a file rename holds its stream
  responses until the commit: a refused rename sends none, and one that
  runs again sends them once. A directory rename still streams its
  children's responses as it moves them, which keeps the client of a long
  rename from timing out, and is not run again.
- Every failed run releases its commit stamps and rolls back, the "is not
  empty" refusal included.

Tests: filer_grpc_server_rename_conflict_test.go, with a store that keeps a
transaction's writes until its commit and can refuse it, and
tikv_store_commit_test.go (-tags tikv). On master the retry, refused-commit
and remote-file tests fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: run a rename again only when its transaction covers every write

With path-specific stores configured, the writes under their prefixes do
not go through the default store's transaction: a parent directory a rename
creates at its destination there stays when the commit is refused, and a
rename run again finds it and announces only the file's move, so peers
replaying the events never learn of the parent.

IsolatingTransaction now holds only when no path-specific store is
configured, and AtomicRenameEntry checks it too before running a rename
again, as StreamRenameEntry does through its held responses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: finish a committed rename before its held responses go out

StreamRenameEntry sent its held responses before the work the commit leaves
(metadata events, chunk deletions, remote copies). A client that stops
reading without closing the stream blocks Send on flow control, and that
work then never ran. It now runs first; the responses still follow the
commit.

A file with a remote object no longer holds its responses: its remote copy
after the commit is part of that work, and the client should not wait for
it. It streams as it moves, as before, and is not run again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: let the store say that its transactions isolate a rename

Whether a rename's responses wait for the commit, and whether it may run
again, was inferred from the context BeginTransaction returned and from
whether any path-specific store was configured. Neither holds up:

- A store may hand back a transaction context that its writes do not use:
  YDB begins a table-service transaction, and its statements run through
  the query service outside it. A store now says so itself, through
  IsolatingTransactionStore, which the TiKV store implements. Any other
  store keeps sending a rename's responses as the entries move and does not
  run it again, as before this PR.
- A path-specific store only matters for the paths it holds.
  Filer.TransactionCovers asks whether the rename's source and destination
  live in the default store: a rename that stays there holds its responses
  and may run again, and one that writes into a path-specific store does
  neither.

A rename that may not run again still must not announce changes before its
commit, so a file with a remote object holds its responses too. So that its
remote copy after the commit does not delay them, the held responses go out
while the rename finishes, and the call returns once both are done.

A held response checks the stream's context, so a rename whose client went
away before its first response is rolled back, as when the responses go
out at once, instead of committed unseen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: the SQL stores isolate their transactions too

AbstractSqlStore takes the sql.Tx its context carries for every entry call
(getTxOrDB) and every KV call (kvDB, also when KV has a pool of its own),
so the SQL stores built on it meet what IsolatingTransactionStore asks. A
file rename on them holds its responses until the commit again, as it did
before the declaration became explicit; it is never run again, since no
SQL store reports ErrTransactionConflict.

Bucket tables are created and dropped outside the transaction, which a
file rename does not do.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* abstract_sql: check that a transaction's writes take its own handle

sqlmock serves a pool and its transactions from one mock, so the write
expectations also pass for entry writes made through store.DB. Assert that
getTxOrDB and kvDB return the *sql.Tx the context carries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:25:17 -08:00
Chris LuandClaude Opus 5.5 856762b20d volume.fix.replication: keep every needle on copyCount survivors when trimming (#12897)
* volume.fix.replication: keep every needle on copyCount survivors when trimming

The trim refused only needles that no survivor held. When replicas have
diverged, a needle written while one survivor was down could be held only
by the doomed replica and one other survivor, so the trim left it on a
single copy while the volume still looked healthy. Count the survivors
holding each live needle and refuse unless it stays on
min(copyCount, survivors) of them; a delete on any survivor still covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* balancer: list trim candidates best first

PickOneReplicaToDelete and PickOneMisplacedVolume now return the first of
ReplicasToDelete and MisplacedVolumesToDelete, which list every replica
the pick chooses from in the same order, so a caller that refuses the
pick can try the next one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume.fix.replication: trim the next candidate when the pick is short

When the preferred replica would leave a needle short of copies, try the
next candidate in the same preference order instead of skipping the
volume. A replica that missed writes is often the only safe one to
trim, and it need not be the smallest. Index and status errors still
skip the volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume.fix.replication: fold survivor indexes into per-needle counts

countUncoveredNeedles kept every survivor's filtered index until the
check ended. Count the survivors holding each needle of the doomed
replica in a byte per needle instead, and release each survivor's index
before reading the next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume.fix.replication: test a rewrite after a delete on one survivor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 10:22:18 -08:00
Chris LuandClaude Opus 5.5 8d4ec5252a iam: evaluate credential trust policies with the policy engine (#12895)
* iam: evaluate credential trust policies with the policy engine

AssumeRoleWithCredentials and the Iceberg credential vending path checked
a role's trust policy by scanning for a matching Allow statement only, so
an explicit Deny never took effect. Evaluate the trust policy through
EvaluateTrustPolicy, as AssumeRole and AssumeRoleWithWebIdentity do, so a
matching Deny wins over an Allow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iam: keep the Federated provider match for credential trust Allows

Matching Allow statements through the shared trust matcher let
{"AWS":"*"}, "*" and empty principal objects admit credential-provider
users, and made Allow conditions fail closed on keys this path does not
supply, such as the vending duration. Keep the exact Federated provider
check for Allow and use the policy engine only to find a matching Deny,
with the requested session duration in the context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 10:20:57 -08:00
Chris LuandClaude Opus 5.5 04050e781b ci: give recursive cosign signing more than the 3m default timeout (#12896)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 10:19:54 -08:00
040ff9049c filer: roll back a stream rename refused for a non-empty target (#12886)
* filer: roll back a stream rename refused for a non-empty target

StreamRenameEntry refuses to move a directory onto a non-empty one, but
returned without ending the transaction it had begun. On a SQL store
(MySQL, Postgres and the stores built on them) that transaction keeps its
pooled connection: it was begun under context.Background(), so database/sql
never rolls it back by itself. Every such refusal holds one more connection
for the life of the filer, and once connection_max_open (50 in the scaffold)
are held, store calls wait for a connection that never comes back.

Roll the transaction back before returning, as the function's other
refusals already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: check a stream rename's target directory inside its transaction

The not-empty check listed the target under context.Background(), outside
the transaction the rename had already begun. The SQLite store's main pool
has a single connection, which the transaction holds, so every directory
rename onto an existing directory waited for that connection forever and
the filer's store stopped answering. On a bounded SQL pool, concurrent
renames that each hold a transaction can wedge the same way.

List through the transaction's context, as the child move already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:18:25 -08:00
Yip LeoandClaude Opus 5.5 78e2a4c2b4 mount: check the next inode number before AllocateInode returns it (#12884)
AllocateInode probes from the number a path hashes to while that number is
taken, but the loop re-checked the number it had just stepped off and then
advanced once more. When the first candidate was taken, it returned the
number after the first free one without looking at it, and that number can
belong to a live file.

The new entry stores the number in its attributes and the mount reports it
as st_ino, so the two files stat as the same file. A writer that replaces a
file with tmp + rename several times a second runs into it: the next temp
file hashes to the number the previous one carried to the target, and GNU mv
refuses the replacement with "are the same file". With readers holding the
replaced file open, 56 of 3446 such replacements failed that way on our
mounts; none did with this change.

Lookup's probe already checks the next number; AllocateInode now does the
same.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 10:17:25 -08:00
32d4633298 filer: list the metadata log from the scan start, not from midnight (#12885)
* filer: list the metadata log from the scan start, not from midnight

A pass over the persisted metadata log lists the start day's directory
from its first file, then skips the files before the scan start's minute.
Each filer writes up to one log file a minute, so late in the day a pass
reads up to 1440 entries per filer from the filer store to find the few
after the scan start: with three filers and a scan from 12:29, 2254
entries for 6 files.

Every disk pass pays this: SubscribeMetadata and SubscribeLocalMetadata
whenever a subscriber reads from disk (filer.sync, filer.meta.tail or an
S3 gateway resuming from an earlier position, or catching up), and
CollectLogFileRefs for chunk-capable subscribers.

List the start day from the scan start's minute, in the log file
collector and in CollectLogFileRefs. The files before it were skipped
anyway, so a pass reads the same files; later days are still listed from
their beginning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: list the whole log day on a store that does not list by name

Elasticsearch pages a directory by a hash of the entry path, not by name, so
a listing there cannot start at the scan start's minute: an inclusive start
re-reads the first page, and an exclusive one starts at an arbitrary point
of the hash order. Stores now say so through UnorderedListingStore, which
the Elasticsearch store implements, and the log passes list the whole start
day on them, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: ask the store of the log day directory whether it lists by name

The order check looked at the store of SystemLogDir. A path-specific store
can serve a day directory under it, so ask the store that lists the day.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test a log day served by a path-specific unordered store

The stub store now lists the root directory of a path-specific store, which
the translator hands it as "/".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:16:24 -08:00
b4f5b1a354 mount: hold a rename's names against this mount's own publications (#12889)
* mount: hold a rename's names against this mount's own publications

A rename of an open file can fail with EIO on a filer store with optimistic
transactions (TiKV). Rename publishes the handle's deferred create first. A
FLUSH of the same handle (a forked child closing the inherited fd, say)
that looked at the dirty flag before that publication waits on the locks,
then publishes the identical entry again while the filer moves the file,
and TiKV refuses the rename's commit on the source key ("write conflict
... reason:Optimistic"). safetensors checkpoints hit this: they write
.tmpXXXXXX and rename it while the fd is still open, and our training jobs
fork a subprocess every second.

- flushMetadataToFiler checks dirtyMetadata again under its locks and
  publishes nothing for a handle another flush has already published.
- Rename holds the publication locks of both names, in path order, across
  the filer call and the local move. A flush, chmod/utimes or xattr change
  of either name through this mount waits for it, then publishes under the
  name the rename left: lockFlushTarget (content flushes, now also the
  periodic flush) and lockNodePublication (attribute changes) resolve the
  name again after the wait. A failed rename restores the target's handle
  before the locks go.

Tests: weedfs_rename_publish_test.go, with a filer that records every
write made while a rename is in flight. On master six of the seven fail,
the incident among them (the deferred create published twice); the one
that passes guards against deadlock between renames. The chmod stress run
fails on master with ENOENT. TestFlushMergeThroughChunkProxy marks its
handle dirty before it flushes: doFlush only flushes a handle with changes,
and the clean handle it used would now publish nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: give up on an attribute change whose node keeps moving

lockNodePublication went ahead on its fourth wait even when the node had
been renamed again meanwhile, and the change went to a name the node no
longer had, without that name's lock. It now returns EAGAIN then, as the
flush path already refuses after its fourth try. The stress tests accept
EAGAIN from a chmod racing back-to-back renames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test the chmod that gives up on a file that keeps moving

The chmod waits for a name's lock that the test holds shared, so a
shared try fails exactly while the chmod is queued for it; the test
moves the file each time, four times, and expects EAGAIN with nothing
written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:11:42 -08:00
8046d5c78a fix(iceberg): keep concurrent namespace property changes (#12890)
* iceberg: keep concurrent namespace property changes

UpdateNamespaceProperties merged the request into a copy read by
GetNamespace and wrote the whole map back, so when two requests changed
different properties of the same namespace at once, both answered 200
but only one change was kept. Apply the changes inside the
compare-checked write instead, and answer 503 with Retry-After when
every attempt loses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep stored namespace properties out of a PropertyChanges answer

UpdateNamespace does not grant GetNamespace, so answering a PropertyChanges
request with the merged map let a caller allowed only to update read every
stored property, even with an empty change. Echo only what was sent, as the
Properties form does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: describe the PropertyChanges form of UpdateNamespace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-22 10:09:48 -08:00
Chris LuandClaude Opus 5.5 5afeb20ad6 s3: enforce BlockPublicPolicy and RestrictPublicBuckets for bucket policies (#12882)
* s3: refuse a public bucket policy when the bucket blocks public policies

PutBucketPolicy stored and enforced a policy granting access to every
principal even with BlockPublicPolicy set. Check the stored public access
block on the bucket entry that the policy write reads, and answer
AccessDenied for a public policy. A policy counts as public when an Allow
names a wildcard principal (or uses NotPrincipal) and no fixed-value
restricting condition such as aws:SourceIp or aws:SourceVpce narrows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep a public bucket policy from granting anonymous access under RestrictPublicBuckets

With RestrictPublicBuckets set, an anonymous request was still allowed by
a public bucket policy. The bucket policy engine now treats such an Allow
as granting nothing when the bucket restricts public buckets and its policy
is public, so the request falls through to the remaining checks instead of
reading as an explicit deny. A bucket whose configuration cannot be read is
treated as restricted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: write a bucket policy only over the extended attributes it checked

setBucketPolicy rewrote the whole bucket entry it had read, so a public
access block set between the BlockPublicPolicy check and the write was
erased and the public policy stored anyway. Send the read extended
attributes, including an absent public access block, as the update's
expected values, and redo the read and check when they changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: count more policy forms as public

An empty principal list and a principal holding a policy variable can both
match anyone, so they are public. An aws:SourceIp range wider than /8
(IPv4) or /32 (IPv6) no longer restricts a grant. An ARN condition value
with a fixed account, such as an access point ARN with a wildcard name,
does restrict it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: deny anonymous callers outright on a restricted bucket with a public policy

RestrictPublicBuckets limits a bucket with a public policy to callers of
the owning account, so dropping only the policy's own grant left public
ACLs able to serve anonymous reads. While the policy is public, the policy
engine now answers an anonymous request with a deny. It checks before and
after evaluating, so a policy replaced in between cannot let an anonymous
grant through. A bucket without a policy, or with a non-public one, is
unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: count an empty principal string as public

A principal of "" compiles to no principal check, so it matches anyone,
the same as an empty list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: write a bucket policy only over the bucket entry it checked

The policy write replaced the whole bucket entry and asserted only the
public access block key, so a bucket setting first written between the
lookup and the write (versioning, for one) was dropped. Pin the write to
the entry it read; any concurrent change fails it and the lookup retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: judge an IPv4-mapped aws:SourceIp range by its IPv4 prefix

::ffff:0.0.0.0/96 parses as a 128-bit network but matches every IPv4
caller, so it passed the /32 IPv6 bound and a public policy slipped past
BlockPublicPolicy and RestrictPublicBuckets. Apply the IPv4 /8 bound to
mapped ranges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 02:23:12 -08:00
Chris LuandClaude Opus 5.5 8ffce492fd s3: time each stage of an object write (#12883)
* s3: time each stage of an object write

SeaweedFS_s3_request_seconds times the whole handler, so a slow PUT tail
cannot be split into client upload time and server time. putToFiler now
records SeaweedFS_s3_put_stage_seconds{operation,stage} per write:
body_read (blocked on the request body), assign (volume assigns),
chunk_upload (upload time apart from body reads: waiting on chunk
uploads), and metadata (from the uploaded chunks to the committed entry).
operation is PutObject or UploadPart; no per-bucket or per-object labels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: chart the S3 PUT stage p99

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: count body reads made before putToFiler in body_read

mimeDetect reads the first bytes, and a POST upload parses the whole form,
before putToFiler starts, so a slow client showed little body_read time.
track now times every read of the request body, body_read reports the
request's total, and chunk_upload subtracts only the reads made during
the upload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: observe body_read once per request

An archive upload writes one object per member, and every write reported
the same request-wide body read time. The first write to finish now
reports it; the other stages stay per write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: name the non-read upload stage storage

The chunked upload runs volume assigns inside the chunk upload goroutines,
so its time apart from body reads covers assigns and chunk uploads, and
the uploads themselves cannot be timed from outside UploadReaderInChunks.
Call that stage storage; assign stays the summed assign time within it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: record a zero body_read for writes without a body

timeBodyReads attached no timer to bodyless requests, so a zero-byte PUT
or an UploadPartCopy recorded every stage but body_read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: observe body_read after the handler so it covers every write

An archive request writes several objects from one body. Observing
body_read at the first write's record left out the reads of the later
members. record now only marks the request, and track observes the
request-wide total once the handler returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:59:11 -08:00
Chris LuandClaude Opus 5.5 f3b838e234 ec: encode past deletes a replica missed while it was down (#12879)
* volume_replica: encode past deletes a replica missed

A delete that reaches only some replicas, for example while one is
down, leaves that replica holding the needle live. The encoder's idx
gate then refused the volume forever.

A needle live on one replica and tombstoned on another by a record
appended after that write is a delete the first replica missed.
MissedDeletes finds them; the gate leaves them out of the live-set
comparison and encodes from a replica that holds none of them, so the
EC volume does not bring them back. A tombstone older than the live
write, a needle absent on the other side, and volumes without
AppendAtNs still refuse, as does a volume where every replica missed
some delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* erasure_coding: test encoding a volume one replica missed a delete on

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: prove a missed delete from one replica's own index

AppendAtNs comes from each server's own clock, and vacuum's makeupDiff
re-stamps tombstones it carries over with the commit time, so comparing
a tombstone's AppendAtNs against another replica's write can order a
later rewrite before an older delete.

Prove the delete instead from the replica that applied it: its .idx
shows the live row the tombstone replaced, and when that record has the
same cookie, CRC and last-modified time as the needle still live on the
other replica, that very write was deleted. Replicated writes share all
three, a rewrite does not. A tombstone with no earlier write row (its
write vacuumed away) proves nothing and still refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: test a missed delete with a third replica holding no row

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: never count a needle its own replica deleted as missed

A same-content upload with the same ts after both replicas deleted the
needle matches the deleted write on cookie, CRC and last-modified. The
replica holding it has its own tombstone for the needle before that
live row, which a replica that missed the delete never has, so skip it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: count a missed delete only for a needle written once

An overwrite that keeps cookie, CRC and last-modified, such as a TTL
volume re-append or a client-set ts, also matches the write another
replica deleted. A replica whose own index replaced an earlier row for
the needle, by an overwrite or by its own delete, may hold a write made
after that delete, so it never counts as having missed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: compare capacity replicas first so a clean one is the encode source

When the preferred replica missed a delete, the gate falls back to the
first replica that holds none, and that could be one without the free
slots RequireCapacitySource needs, failing the encode although another
capacity replica was clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: keep the row an offset-0 delete removes as an earlier write

A remote-tier delete writes an offset-0 row and drops the key, so a later
identical rewrite looked written once and could count as a missed delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: refuse a missed delete whose live write is not older than the tombstone

Compaction keeps only the latest row per needle, so a same-meta rewrite
after the delete can lose the earlier row that marked it as rewritten.
Its record still carries its own append time, which then is not older
than the tombstone. The index proof still decides; the clocks only refuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume_replica: count a missed delete only when both replicas appended the write together

Compaction can drop the rows that show a replica rewrote a needle, and the
tombstone stamp is not a reliable delete time: a vacuum commit stamps
deletes made during the copy with the commit time, and replicas stamp with
their own clocks. A replicated write lands on every replica within the
forwarding time plus clock skew, so the live write and the deleted write
must also be stamped within a minute of each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:00:28 -08:00
Chris LuandClaude Opus 5.5 dda0a57584 filer: announce the directories a rename creates at its destination (#12880)
* filer: let a suppressing caller collect the parents it creates

Under suppressed metadata events, ensureParentDirectoryEntry creates
missing parent directories without announcing them and releases their
stamps, since the caller's own event covers only its entry.
WithCreatedParents keeps the suppression and also collects those
directories, with their stamps, so the caller can announce them once its
change commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: announce the directories a rename creates at its destination

A rename into a path whose parents do not exist yet created them without
metadata events. A peer filer with its own store replays events into that
store and never got the new directories: it found the moved entry by path,
but listing its new parent's parent showed nothing. The rename now
publishes a create event for each new parent ahead of its own event, after
the commit, and releases their stamps if it fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: announce a parent a rename promotes from a file to a directory

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: announce a promoted parent as replacing the file

A parent promoted from a file to a directory was announced as a create,
so a peer whose store does not upsert refused the insert over the file
row it already held and could not move past the event. Announce the
promotion with the file as the old entry, both from a plain create and
from a rename's collected parents, so a peer replays it as a replacement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep announcing a promoted parent as a create

filer.sync applies a same-path update through FilerSink.UpdateEntry, and
the destination filer refuses to turn its file into a directory, so an
event carrying the file as OldEntry stalls the sync. Ordinary writes have
always published a promotion as a create; the rename publishes the same.

This reverts commit 85760c084f.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 23:57:55 -08:00
c80bf3afac util/http: stop waiting on a response body the server stalls (#12875)
* util/http: stop waiting on a response body the server stalls

CloseResponse reads the rest of a response body so that the connection
can be reused, and StatusError reads the message a server puts in the
body of a failed request. Neither had a time limit. The client's only
read deadline covers the response headers, so when a server sent its
headers and then stopped sending the body, both blocked until the
request's context ended. Most callers pass a context that never ends.

A chunk read whose replica answered 404 or 500 this way never returned,
so it never got to the next replica. That holds for ReadUrlAsStream and
for the replica fallback of S3 copies.

Both now close the body once 5 seconds have passed. That fails the
blocked read, and the connection is dropped instead of reused. A body
that arrives in time is drained as before, and its connection is still
reused. StatusError reports the status with whatever part of the
message arrived.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* util/http: bound a body read that closing the body cannot interrupt

The limit worked by closing the body, which fails a read blocked on it.
That does not hold when the transport decodes gzip for the caller: in Go
1.26 its decoder reads the gzip header under a lock that Close also
takes. A server that announced gzip and stalled before the gzip header
kept both the read and the Close waiting, so the limit never applied.

Such a response is now read on its own goroutine, and the caller stops
waiting when the time is up. The read and the Close stay behind until
the connection dies. Every other response keeps the cheaper way, with
no goroutine.

StatusError now returns the status alone when the message did not
arrive in time. A partly read message is no longer safe to use, because
the read may still be running.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 21:13:49 -08:00
Chris LuandClaude Opus 5.5 3796162ba6 erasure_coding: clear stale EC shards on every holder the master lists (#12876)
* plugin/worker: look up a volume's EC shard holders on the master

LookupEcVolumeLocations returns every server the master currently lists
for any shard of the volume. The master's "ec volume N not found" answer
means no holders; any other failure is returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* erasure_coding: clear stale EC shards on every holder the master lists

The encode preflight and the post-distribute rollback cleared stale
shards only on the planned targets and on the EC holders detection saw.
A server that was down at detection and came back with a failed
attempt's shards was outside both, so its shards survived and ended up
beside the new encode: EC balance could later keep that stale copy as a
duplicate.

The cleanup now also asks the master for the volume's current holders
and clears every one of them. A lookup failure counts as a cleanup
failure, so the preflight retries later instead of encoding beside
shards it cannot see. Without a master address the cleanup behaves as
before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* erasure_coding: ask every master for the EC shard holders

The execution defaults keep only the first master address, so a follower
there failed every holder lookup and with it the encode preflight. The
plugin handler now hands the task the whole cluster master list, and the
lookup moves on past a master that refuses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* erasure_coding: refuse the preflight wipe when a regular replica is gone

A replayed job whose earlier run already committed the EC copy and
deleted the source would wipe those shards, now on every holder the
master lists, before failing on the missing source. Check that every
regular replica is still there before clearing anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:13:21 -08:00
Chris LuandClaude Opus 5.5 f8d3722143 shell: refuse a replica trim that would drop a needle no survivor holds (#12878)
* shell: refuse a replica trim that would drop a needle no survivor holds

The -doCheck pass before volume.fix.replication deletes a surplus
replica compares it with each survivor in turn without resurrecting
absent needles, so a needle live on the doomed replica and missing on
every survivor passed the check. Trimming then deleted its only copy if
it was a missed write. Count, across all survivors, the live needles
none of them holds live or deleted, and skip the trim when there are any.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: count a remote-tier survivor's delete as covering the needle

A remote-tier replica records its deletes with offset zero, and the
filtered index load drops those keys, so the trim check saw the needle as
held by no survivor and refused the trim on every run. Walk survivor
indexes unfiltered: any entry for the key covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: keep the trim's final survivor check under test

The coverage check reads each survivor's index a second time, so the
survivor that disappeared after its first index read now failed that
read and the final VolumeStatus check was never reached. Make it
disappear after the second read and require the status check to run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:12:33 -08:00
Chris LuandClaude Opus 5.5 95a4113c1e volume(rs): append an EC delete outside the store lock (#12874)
* volume(rs): give the EC deletion journal its own lock

The .ecj append handle and its size move behind a per-volume mutex, Go's
ecjFileAccessLock, shared through an EcJournalAppender that outlives the
store lock that found the volume. Closing or dropping the volume closes
the journal under that lock, and the decode takes it for its catch-up
passes, so an append in flight is either fully read or not at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): append an EC delete outside the store lock

VolumeEcBlobDelete and the local EC delete of the HTTP path held the
store write lock through the journal append and its fsync, on a runtime
worker. On a slow disk a stream of deletes kept the store write-locked,
and readers queued behind the waiting writer, heartbeat collection
included, until the master dropped the server.

They now resolve the volume and its needle under the store read lock,
then append and fsync on a blocking thread under the volume's journal
lock. The decode tail is checked under that lock, which the decode
takes after claiming the tail, so a delete still cannot commit behind
the rebuilt index. A volume closed in between is resolved again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): share a .ecj append lock across disks holding the file

Disks can mount runtimes of one volume that journal into the same .ecj,
each with its own handle and journal lock. With deletes appending
outside the store lock, a delete through one disk could land while
another disk's rebuild folded and replaced the file, or while a new
mount loaded it, and be lost or cached before its rollback.

The ecj registry now hands every holder of a path one append lock.
Appends take it before the disk's journal lock, a mount holds it
through its tail repair and load, and a rebuild holds it through the
fold and every sibling's adoption.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): roll a failed .ecj append back to the file's real length

The rollback point was the handle's cached size, which misses records
another disk holding the same journal appended since, so a failed sync
on one disk could truncate a sibling's committed delete. Take the
length from the file itself, under the path's append lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): an EC sync does not wait for a journal append in flight

CopyFile syncs the EC volume under the store read lock, and the .ecj
sync now took the journal lock, so it waited out a delete's fsync with
the store guard held. Every committed append already syncs its own
record, so skip the journal while one holds its lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): repoint sibling .ecj handles when the fold fails after the unlink

A rebuild fold that removed the journal and then failed to reopen it
returned before the sibling disks sharing the .ecj adopted the new file,
and one sibling's failed adoption skipped the rest. A delete parked on
the path lock could then append to the removed inode and be acknowledged,
then lost at restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: reopen sibling .ecj handles even when the folded mount's reopen fails

RebuildEcxFile unlinks the shared journal; the sibling reopen loop ran
only when the folded mount's own reopen succeeded and stopped at the
first sibling error, leaving the remaining handles on the detached inode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): order the EC delete tail test on the path lock, not sleeps

The delete holds the .ecj path lock exactly while it waits on the
journal lock the test holds, so the store probe and the tail claim wait
for it to be busy, and the commit check waits for it to be free again.
A tail check taken before the journal lock now fails the test every run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: track the fold outcome without rewriting the rebuild call

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): find a folded journal's siblings by the registry's path key

The sibling check compared raw .ecj paths, so a runtime reaching the same
journal through a differently spelled index directory shared its append
lock but was not repointed after the fold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 20:39:59 -08:00
Chris LuandClaude Opus 5.5 8be0837c20 s3api: try the next replica when a copied encrypted chunk does not decrypt (#12872)
A copy stores a per-chunk-encrypted chunk's ciphertext as-is, so a replica
whose needle is cut short or diverged became the copied chunk unnoticed.
Open the GCM tag of a whole-needle read and fail that replica when it does
not authenticate; a compressed ciphertext has no expected length to check.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:44:57 -08:00
github-actions[bot] 279d2d2c03 docs: regenerate star history chart 2026-11-22 00:34:57 +00:00
Harrison Crosse 88aa5e9ebe s3api: validate x-amz-checksum-* headers on DeleteObjects (#12868)
* s3api: validate x-amz-checksum-* headers on DeleteObjects

* s3api: reject malformed query escapes, non-canonical signed Content-MD5, and test presigned DeleteObjects

* s3api: share canonical Content-MD5 parser and index query keys once
2026-11-21 13:23:42 -08:00
cbce146a63 s3api: keep a long CopyObject/UploadPartCopy alive with whitespace, as AWS does (#12862)
* s3api: keep a long CopyObject/UploadPartCopy alive with whitespace, as AWS does

CopyObject and UploadPartCopy copy every chunk and only then write the
response. On a slow volume disk (~10 MB/s), or when the source is a
remote-only file of a remote-mounted bucket that is fetched first, a copy of
tens of MB sends no byte for 20-30 s. Clients with a low-speed check give up
while the copy finishes: the AWS SDK for C++ (pyarrow, among others) sets
libcurl's CURLOPT_LOW_SPEED_LIMIT to 1 byte/s over a few seconds, and the
abandoned copy leaves an orphan.

AWS S3's documented behaviour for long copies: answer 200 at once, keep the
connection alive with whitespace, then send <CopyObjectResult> (or an
<Error> document) in the body. This does the same:

- Once every check that refuses with its own status has run (auth, missing
  source, preconditions, invalid arguments, ACL and lock headers, the
  remote-cache 503), a copy still running after 1 s commits to 200,
  application/xml and the XML declaration, then sends one space a second,
  flushed, until <CopyObjectResult>/<CopyPartResult> (checksum in the body)
  or an <Error> with the code the handler would have answered. A copy that
  ends sooner answers byte for byte as before.
- Armed before a remote-only source is fetched into the cluster, which is
  the slow part on a remote-mounted bucket.
- Never kept alive: the metadata-only self-copy; a destination with
  versioning Enabled (x-amz-version-id is known only after the copy); a part
  copy whose upload or request carries SSE (its response headers are known
  only after the copy).
- One goroutine owns the ResponseWriter from arming until halt() returns;
  a client that leaves ends it without touching the copy.
- s3err gains StartStreamingResponse, ErrorResponseFor and EncodeXMLBody,
  shared with WriteErrorResponse.

Accepted: a slow failure is 200 + <Error>, as on AWS, and the request is
counted as 200.

Tests: s3api_object_handlers_copy_keepalive_test.go (slow success and
failure, fast unchanged, a refusal keeps its status, part copy, versioned
destination, SSE-C part, checksum in the body, remote fill covered, client
gone under -race, slow lookup then bad tag = 400, self-copy 412 under the
lock, part range on a remote-only source). With the keep-alive forced off,
the slow-copy tests fail.

* s3api: send a block of spaces per copy keep-alive tick

libcurl rounds its measured rate down, so one byte a second sits right
at the AWS SDK for C++'s 1 byte/s low-speed limit and jitter can trip it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: audit a kept-alive copy error at the 200 it was sent with

Once the keep-alive has sent 200, the <Error> rides in that response, so
the access log records 200 and the error code, as AWS server access logs do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fill a conditional remote-only copy source before the keep-alive

A source condition read the filled entry only after the keep-alive had
committed 200, so a slow fill turned its 412 (or the 400 of a malformed
date) into an <Error> inside a 200. With any x-amz-copy-source-if-*
header the fill runs first, as it did before the keep-alive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fill a remote-only self-copy that moves data under the keep-alive

Only a self-copy that can stay metadata-only needs its source filled
before the keep-alive; one that re-encrypts takes the data path, so its
fill is the slow part the keep-alive is for. A fill changes no
encryption state, so the unfilled entry decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test that the copy keep-alive reaches a client mid-copy

A ResponseRecorder keeps every write, flushed or not; over a real
connection the declaration and the spaces must arrive while the copy is
still held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: bound the copy keep-alive streaming test with a request deadline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 13:05:04 -08:00
Chris LuandClaude Opus 5.5 40fe40556c filer.meta.backup: list large etcd directories without the 3s request deadline, skip excluded subtrees (#12870)
* filer/etcd: list a directory without the request deadline

etcd counts every key left in a range even when the request is limited,
so one page of a directory costs time that grows with the entries after
it: about 0.3 s at the start of a 4 million entry directory on an idle
local etcd, against 1.6 ms near its end. The 3 s request_timeout therefore
fails listings of large directories, which a long walk such as
filer.meta.backup reaches page after page, with "list <dir> : context
deadline exceeded". Listings keep the caller's context like
DeleteFolderChildren; keepalive still ends a call to a member that stops
answering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer_pb: let a TraverseDfs callback skip a directory's subtree

fn returning fs.SkipDir for a directory leaves its subtree unlisted; the
directory is still reported as walked, so a resumed walk passes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.meta.backup: do not walk directories the path filter leaves out

The walk listed every directory and dropped excluded entries one by one,
so -excludePrefixes could not keep it out of a directory: a huge or
failing excluded directory was still listed page by page. A directory
that is not included and has no include prefix under it is now skipped
whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.meta.backup: resume outside a directory the path filter leaves out

A walk saved before the filter skipped directories, or before the filter
changed, can hold a position inside a directory the walk now leaves out.
Resuming there entered the directory without asking the filter and listed
it. The resume position moves to the topmost such directory, which a
resumed walk treats as done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.meta.backup: skip the walk when the path filter leaves out its root

The root of the walk is never handed to the callback, so a -filerDir the
filter leaves out was still listed. Nothing under it would be backed up,
so the walk now ends before it starts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:23:36 -08:00
Chris LuandClaude Opus 5.5 f6d2a42265 s3api: authenticate unsigned requests by a verified client certificate (#12871)
* iam: let an identity name the client certificates it authenticates with

An Identity gets a list of CertificateMatch entries: a URI SAN, a DNS SAN
and a subject CN, every field set having to equal the certificate's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: authenticate an unsigned request by its verified client certificate

With -tlsVerifyClientCert the gateway verifies every client certificate,
but the certificate took no part in naming the identity. A request that
carries no signature or token now authenticates as the identity whose
certificates match the leaf of the chain the gateway verified, and goes
through the same authorization as a signed request from that identity.
Only a verified chain counts. A signature or token still decides the
identity on its own, a certificate matching a disabled identity or more
than one identity is refused, and a certificate matching none leaves the
request anonymous as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep certificate identities off the anonymous read paths

AuthWithPublicRead and the deferred anonymous object read classified a
request by its headers alone, so an unsigned request authenticated by its
client certificate would have been authorized as the anonymous principal:
a GET in a private bucket was refused. They now treat a request whose
certificate names an identity like a signed one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep a user's certificate mappings when the dashboard edits it

UpdateObjectStoreUser and UpdateUserPolicies save a rebuilt identity, which
left out the certificates, so editing a user's email or policies ended
their certificate authentication.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* credential/postgres: store a user's certificate mappings

The PostgreSQL credential store keeps each identity field it knows in its
own column, so certificates were dropped on save and a user configured
there could not authenticate by certificate. Users get a certificates
JSONB column, added to existing tables like policy_names, and every user
query reads or writes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:07:24 -08:00
48f9a1f891 s3api: read a copy's source chunk from another replica when one cannot serve it (#12865)
* s3api: read a copy's source chunk from another replica when one cannot serve it

CopyObject and UploadPartCopy looked up the source volume and always read
from the first location the lookup returned. When that replica could not
serve the chunk (it was down, or it was missing a needle the other replicas
hold), the copy failed with 500 even though the object was fully readable:
GET falls back to the other replicas, copy did not.

Keep every location from the lookup and try them in order:

- the streaming path opens the source on the first replica that answers
  with the chunk. It only moves to the next replica before any byte has
  been forwarded to the destination.
- the buffered path (encrypted or rewritten chunks) retries the whole
  download on the next replica and discards a partial read.

When no replica can serve the chunk the error lists what each one answered.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* s3api: try the next replica when a buffered copy read comes back short

A replica holding a shorter needle answers the range clamped, with a
clean end, so the download looked complete and the copy kept the short
data instead of reading the healthy replica. Plaintext reads now need the
full requested length; cipher chunks are still checked by decryption.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: skip a replica whose streamed copy source is shorter than the chunk

The streaming path checked only the status, so a replica holding a shorter
needle had its clamped range forwarded and the destination stored a short
chunk. An uncompressed response that declares fewer bytes than requested
now moves on to the next replica before anything is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-21 11:05:18 -08:00
Chris LuandClaude Opus 5.5 0aca7d1d6c ci: install Caddy from the pinned GitHub release (#12864)
caddyserver.com/api/download now answers 401 without a login or API
key, so the awscli-over-https job failed in Setup Caddy on every run.
Download the v2.11.9 release tarball instead and verify it against the
release's SHA-512 checksums.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:02:34 -08:00
cf00eae537 filer: end retried deletions of chunks on volumes the master no longer knows (#12860)
* filer: end retried deletions of chunks on volumes the master no longer knows

The deletion lookup read volume locations from the client's cache only. A
chunk on a volume the cluster no longer has (a dropped collection, a removed
bucket) found no location, so no volume server was asked, no deletion result
came back, and the retry queue re-queued it "to avoid loss". The durable
deletion ledger keeps such ids and reloads them with a fresh retry count on
every restart, so MaxRetryAttempts never ends them: on one deployment 2,337 chunks
on 159 deleted volumes were retried 2-4 times an hour for days, ~7,000
warnings an hour.

The retry loop's lookup now asks the master about the volumes the cache does
not know. A location found is used. A "volume id N not found" answer is not
proof on its own (a live volume whose server is away answers the same, and so
does a follower's cold cache), so it only starts a streak on the retry item:
once the master has answered it for VolumeGoneGrace (30 min) over at least
VolumeGoneMinAnswers (3) retries in a row, the chunk counts as deleted with
its volume and leaves the queue and the ledger. Any other outcome, a failure
to ask included, resets the streak and keeps the id retried as before. The
hot deletion loop and the remote-cache flush keep the cache-only lookup.

* filer: hold a volume-gone deletion for MaxRetryDelay before dropping it

A volume server that is down for longer than half an hour gets the same
"not found" answer from the master as a deleted volume, so the 30 minute
grace dropped pending deletions of chunks that come back with the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test the answer count once the volume-gone grace has passed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:00:51 -08:00
Harrison Crosse c9fb00a5d2 s3api: return NoSuchBucket for conditional requests on a missing bucket (#12861)
* s3api: return NoSuchBucket for conditional requests on a missing bucket

* s3api: preserve bucket-name validation for non-If-Match conditional PUTs
2026-11-21 10:48:36 -08:00
Chris LuandClaude Opus 5.5 e3946a35ee filer: keep a directory created while a nested create fills in its parent (#12858)
* filer: fill in a missing parent only where no directory appeared meanwhile

A nested create fills in a missing parent directory by looking it up and
then inserting a plain directory row. A directory created at that path in
between, such as an S3 directory marker carrying its content type and
ETag, was overwritten by the upsert and lost its marker. The parent's
insert and a directory create now re-check the path under a per-path lock
before inserting, so neither replaces the other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test a directory created while its parent is filled in

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep writes inside a store transaction out of the directory lock

A transaction holds its store connection until it commits, and SQLite has
only one. A rename creating its destination directory inside one would
wait for the directory lock while a nested create holding that lock waits
for the connection, so transactional writes no longer take it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test a directory create that waits for its parent's insert

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:44:57 -08:00
70ed252dd6 shell: mask every remote secret in remote.configure's listing (#12856)
* shell: mask every remote secret in remote.configure's listing

remote.configure without arguments lists the configured remotes and replaces
their secrets with stars, but the list was incomplete: the Azure account key,
the Backblaze application key, the Baidu secret key (the access key was masked
in its place) and the Contabo secret key were printed in clear, and so were
inline gcs service account credentials (the field holds a file path or the
JSON itself, private key included).

Move the masking into maskRemoteConfSecrets, which covers every secret field
of RemoteConf, and test it. An unset secret stays empty, so an Azure remote
that authenticates with Entra ID still lists an empty key; a gcs credentials
file path stays listed.

* shell: compare each masked remote secret with its full-length mask

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:41:05 -08:00
Chris LuandClaude Opus 5.5 14631d530b filer: refuse a forwarded conditional write on a filer that is not its owner (#12857)
* filer: refuse a forwarded conditional write on a non-owner

A filer applied any routed write a ring peer forwarded, even when its
own ring named another filer as the write owner. While two filers'
rings disagree (a cooling-off window closing at different times, or a
filer that installed the ring without the prior snapshot), each could
apply a conditional write of the same entry under its own path lock,
and both callers saw success.

The receiver now refuses such a forward with Unavailable carrying a
NOT_WRITE_OWNER reason, so the sender can tell nothing was applied.
Refusing rather than re-forwarding keeps the one-hop bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: re-route a forward the owner refused as not its own

A refused forward applied nothing, and the two rings converge once a
ring update reaches the lagging filer or a cooling-off window closes.
The sender now routes the write again by its own ring, with backoff,
until shortly after its latest window ends, and surfaces the refusal
only after that. A write whose owner turns out to be this filer is
applied locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test forwarded conditional updates between two filers

Two filers on one store, each serving gRPC with its own ring: while
the receiver's ring names the sender as the owner, the forward is
refused and the entry is untouched; once the receiver's cooling-off
window closes, the sender's retried forward applies once and a second
update with the same expectation fails its condition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep retrying a refused forward through a new ring change

The retry deadline was taken from the cooling-off window seen at the
first refusal. A ring change arriving during the retries opens a new
window, in which the two rings can still disagree, so the deadline is
now recomputed after every refusal, capped at 15 s from the first one
so a ring that keeps changing cannot hold a request indefinitely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: surface a refused forward rather than apply it locally

A caller can check the entry before routing: an HTTP append verifies
its snapshot under its locks and then commits locally without a
condition. Once a forward is refused, the retries wait, and if this
filer's ring then names itself, a local apply would act on that stale
check and could overwrite an entry replaced meanwhile. The refusal now
surfaces in that case, and the caller retries the whole request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:40:22 -08:00
Chris LuandClaude Opus 5.5 ebd90c3a45 fips140=only: SHA-256 in place of MD5 and SHA-1 so the server starts and serves S3 (#12855)
* util: SHA-256 stands in for MD5 and SHA-1 under fips140=only

GODEBUG=fips140=only panics on MD5 and SHA-1. NewMd5 and NewSha1 return
those hashes as before, and under fips140=only SHA-256 cut to the same
size, so digests keep their length. Md5, HashStringToLong and HashToInt32
use NewMd5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer stores: hash directory keys with NewMd5 and NewSha1

leveldb2, leveldb3, rocksdb and arangodb hash directory keys with MD5,
tikv with SHA-1, which GODEBUG=fips140=only refuses, so the filer
panicked at startup. They now use util.NewMd5 and util.NewSha1.

Keys made under fips140=only differ from MD5 keys, so leveldb2 and
leveldb3 mark an empty database opened under fips140=only and refuse a
database whose keys are of the other kind instead of showing it empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* operation, volume: no Content-MD5 checks under fips140=only

Under GODEBUG=fips140=only the uploader's digest is not an MD5, so it is
no longer sent as Content-MD5, which volume servers outside that mode
would reject; the digest still becomes the chunk ETag. A Go volume
server in that mode keeps a client's Content-MD5 unchecked instead of
panicking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api, filer: ETags and content digests with util.NewMd5

ETags, entry Md5 attributes and chunk digests now use util.Md5 and
util.NewMd5, so under GODEBUG=fips140=only they are SHA-256 cut to 16
bytes instead of panicking. That digest cannot check a client's
Content-MD5, so in that mode Content-MD5 is accepted unchecked, and the
filer stops returning Content-MD5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api, iam, master: SHA-1 names with util.NewSha1

Multipart upload ids, IAM policy ids, the OIDC provider, audit and
session revocation file names, and the master's read-only copy dir hash
names with SHA-1. They now use util.NewSha1, which GODEBUG=fips140=only
turns into truncated SHA-256.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* postgres, oidc, update: refuse MD5 and SHA-1 checks under fips140=only

PostgreSQL md5 authentication, OIDC TLS thumbprints (SHA-1 by
definition) and weed update's MD5 check of the download cannot run
under GODEBUG=fips140=only. They now fail with an error saying so
instead of panicking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: no empty-body MD5 when Content-MD5 is not checked

Under fips140=only a bodyless signed request still reached md5.Sum(nil)
before the nil check and panicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: empty copy part ETag from the digest it stores

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: skip the native MD5 test under fips140=only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3sink: no Content-MD5 under fips140=only

The entry's Md5 attribute is truncated SHA-256 there, which an S3
destination checking Content-MD5 would reject.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iam: move OIDC provider and revocation records to this mode's name

The record names hash the ARN or JTI with util.NewSha1, which differs
under GODEBUG=fips140=only. On the first use of a filer, each store
renames records whose name does not match the one derived from their
content, so lookups, revocation checks and deletes find records written
in the other mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iam: test the rename with the names each fips140 mode derives

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iam: rename a record only if it is unchanged, under its new name's lock

Two processes renaming after a mode switch could both list a record; if
one renamed it and the provider was then deleted, the other wrote it
back. The rename is now one filer transaction locked on the new name,
like the stores' conditional writes, that requires the old entry to be
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:38:38 -08:00
949952f2b6 filer: take a hard link off only after the store dropped the name (#12853)
* filer: take a hard link off only after the store dropped the name

Deleting one name of a hard-linked file took the name off the file's link
count (DeleteHardLink: the shared record read, its count less one written
back, in writes of their own) before the store deleted the name. When the
store then refused the delete (a TiKV write conflict, a database timeout),
or the filer stopped in between, the name stayed with the count already one
short. Each time the delete was sent again it took one more off: a client
retrying, or rm run again after the error. At zero the record went, and that
delete, having read a count of one, deleted the chunks. The file's other
names were left with no record and with their chunks deleted. Without a
retry, the next delete of another name of the file did the same.

A name now comes off the count once the store no longer holds it
(FilerStoreWrapper.dropLink). A refused delete leaves the name and the count
as they were, and the delete sent again takes it off once.

- DeleteEntry and DeleteOneEntry delete the name, then drop its link.
- InsertEntry and UpdateEntry over a name of another hard-linked file write
  the new entry, then drop the replaced name's link (handleUpdateToHardLinks
  now returns it instead of dropping it).
- A recursive delete drops its hard-linked children's links after
  DeleteFolderChildren deleted them, not while listing them.
- A link that cannot be dropped after the delete or the write is logged and
  fails neither (a write failed before): the count stays one too high, and
  the record and the chunks outlive the file's last name instead of going
  before it.

Inside a store transaction (a rename) the order changes nothing.

Tests: filer_hardlink_delete_test.go, and through the DeleteEntry handler
filer_grpc_server_hardlink_delete_test.go. With the old order the refused
delete, write and recursive delete each take a link off, and the delete sent
again queues chunk 3,0c03 for deletion while /dir/other.txt reads it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: delete a hard-linked name's chunks only once its file's record is gone

DeleteEntryMetaAndData deleted the chunks of a hard-linked name when the
link count it read before the delete was one or less. Another filer can
link the file under a new name in between: the count misses that name, the
record, which counts it, outlives the delete, and the chunks went while the
new name read them.

Now the count read before must leave no other name and the file's record
must be gone after the delete (lastLinkDropped); a recursive delete already
asks for the record. The count stays in: one name deleted at once through
two filers is taken off twice, and the record goes while another name still
holds the file. When both deletes read the count before either took a link
off, the count still shows that name and the chunks stay. Where the two
disagree the chunks leak rather than go.

Tests: TestDeleteEntryKeepsChunksOfLinkAddedMeanwhile fails with the count
alone, TestDeleteEntryTwiceAtOnceKeepsChunks with the record alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: delete a recursive delete's hard-linked names one by one, as a single delete does

A recursive delete listed a folder's hard-linked names, had
DeleteFolderChildren delete them with the other children, and then took
their links off and asked whether each record was gone. Found in review:

- A store that deletes a folder's children in batches (TiKV) can fail after
  some of them. The names it deleted are gone, their links were never taken
  off, and the delete run again no longer lists them, so their counts stay
  high and the file's chunks are never freed.
- Two filers deleting the same folder at once both take the link of each
  hard-linked name off. The second finds the record gone and deletes the
  chunks while a name outside the folder still reads them (as on master).
- The listed entries, chunk lists included, were kept until the folder's
  children were deleted.

A hard-linked child now goes as it is listed, the way a single delete takes
a name (deleteLinkedName): its entry read again for the current count, the
name deleted by the store, then its link taken off (dropLink), and its
chunks queued only when it was the last link (lastLinkDropped: the count
read left no other name and the record is gone). DeleteFolderChildren takes
the other children. Names of one file in two folders of the tree still free
the chunks once, with the last of them.

The link of a hard-linked child now comes off whether or not the delete
removes data, as it already did for a single delete. OnHardLinkIdsFunc and
maybeDeleteHardLinks, which took links off only with the data, are gone.

Tests: TestRecursiveDeleteFailingAfterItsLinkedChildTookItsLinkOff and
TestRecursiveDeletesAtOnceKeepChunksOfANameOutside fail with the previous
commit; the latter also fails when deleteLinkedName asks for the record
alone. TestRecursiveDeleteOfEveryNameDeletesChunksOnce covers the names of
one file in two folders of the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: delete a recursive delete's last-link chunks as the link goes

deleteLinkedName queued the chunks of a file whose last link it took off
with the folder's other chunks, which are deleted only once the whole folder
delete has succeeded. When a later child, a listing or DeleteFolderChildren
failed, the delete returned first and those chunks stayed for good: their
name and record were gone, so no retry could find them. Found in review.

They are now deleted when the link goes, through DeleteChunks with the
child's path, as a single delete deletes them.

Test: TestRecursiveDeleteFailingAfterALastLinkWentDeletesItsChunks fails
with the previous commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: free a swept hard-linked child's chunks only when its last link went

The replay sweep freed a hard-linked child's chunks once the shared record
was gone. One name deleted at the same time through another filer takes the
link off twice, so the record goes while another name still reads the file.
Use lastLinkDropped with the count read under the child's lock, as the
single and recursive deletes do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test store hands out a copy of an entry, as a real store does

Returning the stored entry let a later lookup overwrite the link count an
earlier lookup handed to its caller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: look a hard-linked name up again before taking its link off

A delete read the name, and another filer deleted the same name and took
its link off before this delete read the count. The count then already
lacked the name, the second delete took the link off again, the record
went with another name left, and the chunks were deleted. A hard-linked
name is now deleted through DeleteEntry, which looks the name up after
the count was read and skips the link when the name is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: report a failed lookup from a store delete instead of success

DeleteEntry took any lookup error for a name already gone, so the delete
reported success, the name stayed, and the caller sent a delete event.
Only a missing name is a no-op now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-20 21:21:00 -08:00
Chris LuandClaude Opus 5.5 f7bd0ad802 storage: measure the search lock-hold budget in rounds (#12854)
A stall of a loaded host (a goroutine not scheduled for most of a
second) made one search and one foreground write go over the 250 ms
budget, failing the test though every search held the lock for about
20 ms. Measure in five 500 ms rounds and pass once a round stays within
the budget: every search scans the tombstone run, so a slow search still
fails every round.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:37:19 -08:00
Chris LuandClaude Opus 5.5 3bc6161401 helm: opt-in HTTPS for the volume servers' data port (#12843)
* helm: render volume server HTTPS in security.toml

global.seaweedfs.volumeHttps.enabled sets [https.volume] to the volume
certificate and turns on [https.client] with the client certificate and the
chart CA, so the volume data port is no longer plaintext under
enableSecurity. The option fails without enableSecurity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: add the volume service names to the volume certificate for HTTPS

Volume servers register as <pod>.<volume service>.<namespace>, and HTTPS
clients verify that name, which none of the certificate's wildcards cover.
With volume HTTPS on, the certificate also lists every volume group's
service.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: probe volume servers over HTTPS when they serve it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: reject volume HTTPS for the all-in-one deployment

Its volume server registers by pod IP, so HTTPS clients could not verify
the volume certificate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm CI: check the volume server HTTPS rendering and its guards

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: document volume server HTTPS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: copy chunks for cp.from through the shared HTTP client

The copy built a bare client and plain http:// chunk URLs, so with
[https.client] on it could not read from or write to HTTPS volume servers
("source returned status 400"). Use the global client's transport and
redirect policy, and normalize the source and destination URLs to its
scheme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: restart every security.toml reader when volume HTTPS is toggled

security.toml is mounted with subPath and read once at startup, so on an
upgrade that turns volume HTTPS on, the volume servers restarted with TLS
while filer, S3 and the other clients kept speaking plain HTTP. A
checksum/volume-https pod annotation, rendered only while the option is
on, rolls them all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm CI: check the volume HTTPS rollout annotation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: forward to the leader with the masters' own HTTP scheme

A follower took the scheme from [https.client], so with HTTPS clients
toward volume servers and plain-HTTP masters every forwarded request
(/dir/assign, /dir/status, the UI) failed with 502 "first record does not
look like a TLS handshake". Masters share one [https.master] setting, so
use HTTPS exactly when this master serves it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: update the volume HTTPS caveats now that masters forward correctly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: send a read token on the cp.from source chunk GET

With jwt.signing.read set, volume servers refuse unsigned reads, so
cp.from of a chunked file failed with "source returned status 401".
Mint a read token for the chunk on each source attempt, the same way the
filer's own reads do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume (rust): look up volume locations over the master's gRPC port

The lookup used the master's HTTP /dir/lookup with the [https.client]
scheme, so with HTTPS volume servers and plain-HTTP masters every
replicated write, proxied read, remote chunk read and batch delete failed.
Go asks the master's LookupVolume over gRPC; do the same, over one reused
channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume (rust): bound the whole master dial in lookup_volume

connect_channel's connect timeout covers only the TCP connect, so a master
that accepted the connection and stalled in the TLS handshake held every
replicated write, proxied read and remote chunk read that needed a lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:20:23 -08:00
github-actions[bot] afdb32d228 docs: regenerate star history chart 2026-11-21 00:51:16 +00:00
Martijn HoekstraandClaude Opus 5.5 1c04179953 s3api: refuse SigV2, SSE-C and SHA-1 checksums under fips140=only (#12845)
With GODEBUG=fips140=only, MD5, SHA-1 and HMAC-SHA1 panic, so a request
that uses SigV2 (header, presigned or POST policy), SSE-C (whose customer
key check is MD5) or the SHA-1 flexible checksum panics in the handler and
the client sees a dropped connection. Refuse them before any hashing:

- SigV2: InvalidRequest "The authorization mechanism you have provided is
  not supported. Please use AWS4-HMAC-SHA256." (ErrSignatureVersionNotSupported)
- SSE-C, including copy-source SSE-C headers: NotImplemented
- x-amz-checksum-sha1 (value header, algorithm headers or query, and
  x-amz-trailer): NotImplemented

fips140Enforced is a package variable so tests can turn the refusals on
without running the test binary under fips140=only. Without enforcement
nothing changes.

Refs #12839

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:39:12 -08:00
Chris LuandClaude Opus 5.5 0de9a82dd9 filer: make the stub-backed remote storage tests re-runnable (#12852)
filer: drop cached remote clients when a test registers a stub maker

The remote client cache is keyed by the configuration, so rerunning a
stub-backed test (go test -count>1) got the previous run's stub from the
cache and its counters never moved. Nineteen tests failed on a rerun.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:09:36 -08:00
Chris LuandClaude Opus 5.5 228ccd9eb6 admin: bulk table delete and force namespace delete for S3 Tables (#12851)
* admin: force-delete an S3 Tables namespace with its tables

DELETE /api/s3tables/namespaces?force=true deletes every table in the
namespace, paging through ListTables, before deleting the namespace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: offer deleting a namespace's tables in the S3 Tables namespace delete dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: select several S3 Tables tables and delete them at once

The tables list gets a checkbox column with select-all and a Delete
Selected button that deletes each selected table after one confirmation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: clear restored table selections and keep the bulk delete result on screen

Browsers restore checkbox state on reload, which left rows that took the
deleted tables' places selected. The admin alert() is a non-blocking modal,
so reload only after it is closed instead of discarding the failure list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: re-enable the bulk delete confirm button on page load

Firefox restores a button's disabled state across reloads, which left the
confirm button of the next bulk delete disabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: stop a bulk table delete when its dialog is cancelled

Cancel closed the dialog while the remaining deletes kept running. The
loop now stops before the next table and reports how many were deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: say when the S3 Tables list is cut at the list limit

The tables page shows at most the admin list limit, so select-all covers
only the displayed rows; mark a truncated list and name select-all's scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:08:16 -08:00
Chris LuandClaude Opus 5.5 865a7bd988 filer: commit an HTTP append on a non-owner through the entry's owner (#12849)
* filer: commit an HTTP append on a non-owner through the entry's owner

An HTTP append or offset write re-read the entry under its path lock and
cluster lock and then committed with an unconditional upsert. The path
lock is per process and the cluster lock is a lease, so with several
filers on one store a write landing between the re-read and the upsert
was overwritten although both requests were acknowledged.

A filer that is not the entry's write owner now sends the commit to the
owner as a CreateEntry conditioned on the entry it read (IF_ENTRY_EQUAL,
absent when there was none), evaluated under the owner's path lock. The
owner keeps committing locally under that same lock. A failed condition
refuses the append as a changed entry; any other routed error keeps the
uploaded chunks the stored entry references.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test an HTTP append racing another filer's append

Two filers on one store share a two-member ring. An append on the
non-owner gets another filer's append injected at the store after each
of its reads of the entry in turn; it must either keep both appends or
be refused. Without the routed conditional commit, injections after the
re-read are overwritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the chunks of a forwarded append whose outcome is unknown

The owner may have committed before its reply was lost, and with
separate per-filer stores the local lookup may not see that commit yet,
so deleting the chunks it does not find can strip a committed append.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep fsync appends on the local commit

A per-request fsync is a local context mark that a forwarded CreateEntry
cannot carry, so the owner would store the append without flushing.
Storage-rule fsync is still applied on the owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: normalize the stored entry too when matching IF_ENTRY_EQUAL

A store that keeps the entry as given (the JSON-backed ones) returns
FileSize zero beside chunks, while the expected entry was normalized to
the chunk extent, so an unchanged entry failed the match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: carry a create's fsync request in CreateEntryRequest

The per-request fsync is a context mark on the receiving filer, so a
create forwarded to another filer lost it. CreateEntry now applies the
request's fsync flag to its store write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: route fsync appends to the owner with the fsync flag

A fsync append on a non-owner committed locally without a condition, so
it could still overwrite a write the owner committed after its re-read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test an offset write on a store that keeps FileSize as given

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: start an append at the entry's full size

A store that keeps the entry as given can return FileSize zero beside
chunks, so the append chunks were placed at offset zero over the
existing bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test an append on a store that keeps FileSize as given

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:07:18 -08:00
Chris LuandClaude Opus 5.5 137e4aeede s3api: keep the write condition on the lock fallback create (#12846)
* s3api: keep the write condition on the lock fallback create

Without a ring the PUT checks its conditional headers at the gateway and
then sends the create unconditionally under the object write lock. That
lock is a short lease, so a paused or slow holder lets a second
conditional writer in, and both writes succeed. Send the reduced
condition with the create so the filer re-checks it under its path lock.
Suspended-versioning writes keep the gateway check, since their condition
names the latest version rather than the create's path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test two If-None-Match PUTs racing on the lock fallback

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep the chunks of a fallback create whose outcome is unknown

A conditional create is forwarded by the filer to its ring owner, which
a gateway without a ring may not know, so its landed-check can miss a
commit the owner made before the response was lost. Reclaim the chunks
of such a create only when the filer refused it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test exact fallback race results and a lost conditional create

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: reclaim the chunks of a fallback create the filer refused

A precondition refusal proves the create never committed, but the
landed-check finds the winning writer's entry and reports the key as
present, so the refused writer's chunks were left orphaned. The
ambiguous-route recovery keeps its own rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test that the refused fallback writer's chunk is reclaimed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep the chunks of a recovery create whose outcome is unknown

The owner can forward the conditional recovery create of an ambiguous
routed PUT to a filer the gateway cannot look up, so the cleanup gate
now follows the condition each create actually sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test that the fallback race deletes only the refused writer's chunk

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:06:24 -08:00
Chris Lu 0c705ec9f2 pb: client interceptors on every dialed connection (#12834)
AddClientUnaryInterceptor registers an interceptor that runs around every
unary call on a connection opened by GrpcDial. GrpcDial installs one
fixed interceptor that consults the registered list at call time, so one
added later also applies to connections already open and cached. With
none registered it only calls through.

Claude-Session: https://claude.ai/code/session_011Upvag1tiz2pnSB8mS2qtK
2026-11-20 13:05:23 -08:00
037c27582f redis2: let Redis hash the Lua scripts (no SHA-1 at package init) (#12848)
* redis2: let Redis hash the Lua scripts (no SHA-1 at package init)

redis.NewScript computes the script's SHA-1 in Go when the package-level
vars are initialized. redis2 is linked into every weed binary, so under
GODEBUG=fips140=only every subcommand, including `weed version`, panics
before main. NewScriptServerSHA leaves the digest to Redis (SCRIPT LOAD
on first use) and keeps Run's EVALSHA-then-EVAL behaviour.

weed/fips140_only_test.go runs the weed main package's test binary with
fips140=only, so any package init that uses an unapproved algorithm
fails `go test ./weed/...`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis2: run the Lua scripts by a pinned digest (no SCRIPT LOAD, no lock)

NewScriptServerSHA gets the digest with SCRIPT LOAD inside ensureHash, which
holds the Script's write lock across the round trip and does not remember a
failed load. Where an ACL denies SCRIPT but allows EVAL, every call retried
SCRIPT LOAD under that lock before falling back to EVAL.

The two scripts are now constants next to their SHA-1 digests, and runScript
sends EVALSHA and falls back to EVAL on NOSCRIPT, the same commands
Script.Run sent on master. No SHA-1 is computed in Go, at init or at run
time. TestScriptDigests checks each pinned digest against its source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* redis2: hash the script digests in the test without FIPS enforcement

TestScriptDigests panicked under GODEBUG=fips140=only, the mode this
change is for, because sha1.Sum is not approved there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-20 13:03:47 -08:00
1b209f7717 util, s3api: AES-GCM via NewGCMWithRandomNonce for fips140=only (#12847)
* util: AES-GCM via NewGCMWithRandomNonce in Encrypt/Decrypt

cipher.NewGCM returns an error under GODEBUG=fips140=only ("use of GCM
with arbitrary IVs is not allowed"), so filer -encryptVolumeData cannot
encrypt or decrypt chunks in that mode. NewGCMWithRandomNonce produces the
same nonce(12) || ciphertext || tag layout, so chunks written by earlier
versions still decrypt and older versions can read new chunks; the tests
check both directions against a copy of the previous code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: SSE-S3 DEK and KEK wrapping via NewGCMWithRandomNonce

cipher.NewGCM returns an error under GODEBUG=fips140=only, so SSE-S3
PutObject fails in that mode. NewGCMWithRandomNonce yields the same nonce
and ciphertext+tag bytes: the wrapped KEK keeps its magic || salt || nonce
|| ciphertext+tag layout, and the DEK's nonce and ciphertext are still stored
as separate metadata fields. sealGCMSplit and openGCMSplit split and join
them, with the nonce length as gcmNonceSize, because the random-nonce AEAD's
NonceSize() reports 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util, s3api: keep AES-GCM working for AES blocks NewGCMWithRandomNonce refuses

cipher.NewGCMWithRandomNonce accepts only the standard library's own
*aes.Block. In a GOEXPERIMENT=boringcrypto build aes.NewCipher returns
BoringCrypto's block instead, so Encrypt, Decrypt and SSE-S3 key wrapping
would fail there. util's newGCMWithRandomNonce falls back to cipher.NewGCM
with a nonce from crypto/rand for such blocks, with the same
nonce || ciphertext || tag output. SSE-S3's KEK wrap and DEK wrapping use no
additional data, so they now go through util.Encrypt and util.Decrypt and
build no AES-GCM of their own; the stored bytes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: keep the GCM fallback test working in boringcrypto builds

cipher.NewGCMWithRandomNonce refuses aes.NewCipher's block in a
GOEXPERIMENT=boringcrypto build, so the test failed there before it
reached the fallback. Compare with cipher.NewGCM and the nonce in front
when the native constructor is unavailable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: build the SSE-S3 sealed buffers with slices.Concat

Summing the input lengths for make() trips CodeQL's
go/allocation-size-overflow on the DEK path, whose inputs come from
stored metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: draw SSE-S3 key IDs from crypto/rand

The math/rand key ID is serialized next to the wrapped DEK, so CodeQL's
go/insecure-randomness follows it from the metadata JSON into the
AES-GCM open of the DEK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-20 13:03:22 -08:00
Chris LuandClaude Opus 5.5 f69cb98042 admin/plugin: extension points for scheduling policy (#12833)
* admin/plugin: extension points for scheduling policy

The lane scheduler decides four things in line: how a lane's job types
are run, whether a proposal becomes a queued job, whether a queued job
starts on the slot reserved for it, and whether a job holds the cluster
admin lock for its whole run. Each now goes through a schedulerExtension
whose default answers exactly as before, so policy can be added without
editing the dispatch loop. The extension can also serve its own gRPC
service beside the worker stream.

Claude-Session: https://claude.ai/code/session_011Upvag1tiz2pnSB8mS2qtK

* admin/plugin: state when runLane may return and when done runs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:02:14 -08:00
Chris LuandClaude Opus 5.5 22df63ad22 security: accept a previous JWT signing key during rotation (#12844)
* security: verify JWTs against an optional previous signing key

DecodeJwt, the admin token checks and the volume expiry classifier take
previous keys to try after the current one, and Guard keeps a previous
write and read key next to the current ones. Signing still uses only the
current key. Callers pass no previous key yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume, filer, s3, admin: accept tokens signed with jwt.*.previous_key

jwt.signing.previous_key, jwt.signing.read.previous_key,
jwt.filer_signing.previous_key and jwt.filer_signing.read.previous_key
(WEED_JWT_*_PREVIOUS_KEY from the environment) name a key the verifiers
still accept next to the current one, and SIGHUP reloads them. Keys can
then rotate without an error window: add the new key as previous
everywhere, swap current and previous, then remove previous.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: document jwt previous_key for key rotation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): accept tokens signed with jwt.signing previous_key

Mirrors the Go volume server: [jwt.signing] and [jwt.signing.read] take
previous_key (WEED_JWT_SIGNING_PREVIOUS_KEY,
WEED_JWT_SIGNING_READ_PREVIOUS_KEY), the guard verifies against it after
the current key, and SIGHUP reloads it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume, filer, s3: drop a removed previous_key on SIGHUP

LoadConfiguration merges, so a previous_key line deleted from
security.toml kept verifying until a restart. Read the previous keys
without the merge on reload, as the Rust volume server already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume, filer, s3: keep previous keys when a reload cannot read the file

A SIGHUP that found security.toml unreadable or malformed cleared the
previous keys while the merged current keys stayed. Fall back to the
merged configuration then, so the keys in effect stay in effect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: IAM and metadata subscription admin checks follow the filer guard

The IAM gRPC service checked the jwt.filer_signing keys read at startup,
and the metadata subscription read them from the merged configuration,
so adding or removing previous_key with SIGHUP did not reach them. Both
now read the filer guard that Reload updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: reload jwt keys in one place, keeping the guard's previous keys

When security.toml could not be read, the reloads fell back to the merged
configuration, which still holds a previous_key an earlier reload removed.
Guard.ReloadSigningKeys keeps the previous keys the guard already has
instead, and the volume, filer and S3 reloads share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: take reloaded current keys from the same read as previous keys

The current keys came from the merged configuration and the previous keys
from a second read of the file, so a file swapped between the two reads
could publish the same key as both. Take every key the fresh read sets
from it; a current key the file no longer sets keeps its merged value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: worker streams read the filer admin keys as security.toml sets them

Both worker stream handlers read jwt.filer_signing keys from the merged
configuration. Under weed mini a reload merges the file, which keeps a
previous_key the operator removed, so new streams still accepted it; a
standalone admin never picked up a rotation at all. Read the keys the file
sets now, falling back to the merged values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: wait for old-key tokens to expire before clearing previous_key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep the keys in effect when SIGHUP cannot read security.toml

parse_security_config falls back to defaults when the file is missing or
unreadable, so a SIGHUP then cleared every key and turned JWT checks off.
Skip the key and whitelist update in that case, as the Go reload keeps
its merged configuration and the guard's previous keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: keep every key in effect when a reload cannot read security.toml

A failed read took the current keys from the merged configuration while
keeping the active previous keys, so after a swapped pair the guard could
publish the old key twice and reject tokens signed with the new one. The
reload now leaves the keys untouched, as the Rust volume server does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: filer admin keys fall back to the last pair read, not merged values

When security.toml stopped being readable, FilerAdminKeys returned the
merged configuration, which still holds a previous_key the file had
already dropped, so tokens signed with the retired key verified again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: STS store gates check the admin token against one key snapshot

The OIDC provider and role RPCs read the reloadable admin key twice, in
checkAdminAuth and in the store gate. A reload that set the key between
the two reads let a call without a token pass both. The gate now takes
one snapshot for the empty-key refusal and the token check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: read and cache filer admin keys under one lock

Concurrent callers could store their reads out of order, so an older
pair that still had previous_key could overwrite a newer one and come
back when a later read of security.toml failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: unlock the filer admin key mutex on every exit of its test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:01:27 -08:00
Chris LuandClaude Opus 5.5 4fefe7863c scaffold: list every component that needs each JWT signing key (#12838)
* scaffold: list every component that needs each JWT signing key

jwt.signing.read.key is not a master and volume only key: the filer, the
S3 gateway, mount, webdav, sftp, filer.sync/backup, workers, admin and
weed shell all sign their own volume read tokens with it. Giving the S3
gateway only the filer keys made every GET fail with 401 wrong jwt. Drop
the stale note that the filer does not support read JWTs, and name the
filer and weed shell as signers of the volume write key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: name admin and workers as filer signing key users

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:59:59 -08:00
Chris LuandClaude Opus 5.5 234886d801 admin/plugin: apply the completion of a job whose progress carried no state (#12828)
* admin/plugin: keep a job running when its progress has no state

A progress update without a state stored job_state_unspecified on the
tracked job. That state is not active, so attemptEnded took the attempt
for closed and dropped the worker's JobCompleted: the job stayed at its
first progress stage, with no run record and no completion activity.
seaweed-worker sends its progress without a state.

Treat an unspecified progress state as running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* seaweed-worker: report progress as running when the handler sets no state

The Lance handlers send their progress without a state, so admin saw
JOB_STATE_UNSPECIFIED where the Go handlers send JOB_STATE_RUNNING, and
dropped the job's completion. Default the state in the stream sender so
every handler reports like the Go ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:59:27 -08:00
Chris LuandClaude Opus 5.5 425216714c helm: stronger JWT signing keys, keep security config in a Secret (#12836)
* helm: generate 64-character JWT signing keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: keep security.toml in a Secret

The JWT signing keys were readable by anyone allowed to read ConfigMaps
in the namespace. Existing keys are carried over from the ConfigMap on
upgrade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: document where the security config is kept

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: test upgrading a release of the ConfigMap chart

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: refuse a partitioned upgrade that removes the security ConfigMap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: check for the security ConfigMap even when the Secret exists

A failed migration leaves the new Secret next to the old ConfigMap, so a
partitioned retry must still be refused before Helm removes the ConfigMap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: test a partitioned retry after a failed migration

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: guard partitioned upgrades only for this release's ConfigMap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: test a partitioned upgrade next to another release's legacy ConfigMap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:58:30 -08:00
Chris LuandClaude Opus 5.5 d68cde4cfc s3api: sign the virtual-hosted bucket in signature V2 (#12835)
* s3api: sign the virtual-hosted bucket in signature V2

Signature V2 signed only the request path, so a path-style signed or
presigned request replayed with a virtual-host Host header reached
another bucket. Prefix the bucket taken from the Host to the canonical
resource, as AWS does, and refuse a request routed to a different bucket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test signature V2 against virtual-host retargeting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: match port-qualified virtual-host domains like the router

With -s3.domainName=s3.test:8333 the router matches the full host:port,
but bucketFromVirtualHost compared the port-stripped host and never found
the bucket, so the virtual-host checks did not apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:55:03 -08:00
Chris LuandClaude Opus 5.5 7d52383ccf admin: show tooltips on the S3 Tables namespaces and tables buttons (#12837)
* admin: title the S3 Tables namespaces and tables buttons

The icon-only links that open a bucket's namespaces and a namespace's
tables had no title, so hovering them showed no tooltip while the other
row actions did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: title the topic details button

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: switch the topic details button title with its state

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:53:20 -08:00
3aadc0fc46 s3api: bound route-by-key lookups at an unreachable owner filer (#12827)
* s3api: bound route-by-key lookups at an unreachable owner filer

A route-by-key read (getObjectEntryRoutedByKey and the scoped .versions
listing) asks the key's owner filer first, on context.Background(). When
that owner sits behind a network partition that drops packets instead of
refusing them, the lookup waits out gRPC's 20 s connect timeout before the
failover walk asks the next filer. The owner is then skipped for only 2 s,
so the next read of any key it owns dials it again and waits another 20 s.
With the ring spread over two data centers, about half the keys stall
every ~22 s for as long as the partition lasts (#12826).

- The owner's attempt in the walk now gets a deadline,
  -s3.routedLookupTimeout (default 1s), when the owner is not the
  gateway's current filer. Past it the walk moves on to the next filer, as
  for any transport error, and flags the owner unreachable. The current
  filer and every later attempt stay unbounded, so a slow but reachable
  local filer still answers; 0 restores the unbounded lookup. The prior-
  owner probe during a ring rebalance gets the same bound.
- The skip time of a failed owner is now -s3.unreachableOwnerTTL
  (default 2s, unchanged). Deployments that can see dropped-packet
  partitions can raise it so each owner is retried less often.
- The S3 gateway's volume location lookups take -s3.volumeLookupTimeout
  per filer (default 5s, the FilerClient default, unchanged), so a vidMap
  miss need not wait 5 s per unreachable filer.

The flags exist on weed s3 (without the s3. prefix), weed filer, weed
server and weed mini.

Tests (s3api_object_routed_read_deadline_test.go): an owner that never
answers costs a read the deadline and is skipped by the next read (hangs
without the change); with the deadline 0 a slow owner is still waited
for; an owner that is the current filer is not timed out; a slow filer
later in the walk is waited for; the scoped listing fails over at the
deadline; the skip TTL honours the option and the default.

* s3api: bound a routed listing only until the owner's first message

The routed-lookup deadline covered the whole .versions stream at a remote
owner. A reachable owner whose listing keeps streaming past it (a store
scan trailing its first rows) was cut off mid-stream, and the failover
walk refuses to replay a stream that already delivered entries, while
listRetry does not retry DeadlineExceeded, so the listing failed outright
where it used to succeed. Lift the deadline once the stream delivers its
first message; an owner that never answers still fails over at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:52:30 -08:00
小马一只andClaude Opus 5.5 aa95f631f2 http: keep the body pieces that arrive after a read is cancelled (#12822)
RetriedFetchChunkData's callback for ReadUrlAsStream skipped every piece
once ctx was cancelled. ReadUrlAsStream checks ctx only before each body
read, so when ctx is cancelled while the last read is under way, that
read returns the last piece with io.EOF, the callback drops it, and the
fetch returns fewer bytes than asked with a nil error. Nothing above it
checks the length: weed mount answers the FUSE read with the short
buffer, and the kernel takes a short buffered read as the end of the
file, so the reader sees EOF in the middle of it.

The callback now keeps every piece. A read cancelled before its last
piece still ends with ctx.Err() from ReadUrlAsStream's own check, so the
download still stops; one cancelled during the last piece returns the
whole range. An encrypted chunk reaches the callback in one piece, so
there the old check lost the whole chunk: 0 bytes and no error.

TestRetriedFetchChunkDataCancelledWhileTheLastPieceArrives cancels ctx
inside the body read that returns the last piece, for a range read and
an encrypted chunk; both fail on master with fewer bytes and no error.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:50:44 -08:00
Yip LeoandClaude Opus 5.5 5adfc23e85 s3api: serve a 0-byte file on HEAD when its child probe fails (#12824)
HEAD of a 0-byte file lists one child to tell an implicit directory from
an empty file, and hasChildren answers true when that listing fails. The
listing callers want that, since keeping an entry is their safe side, but
HEAD then answers 404 NoSuchKey for a file it has just found. A copy tool
that HEADs the key it just wrote reports the copy as failed; rclone logs
"Failed to copy: object not found" for every empty __init__.py or lock
file whose probe failed, although the object is in place.

The probe fails like this whenever the request context is already
canceled while the client still waits. net/http cancels a connection's
context when its background read fails, and the read deadline the
activity-timeout listener sets can expire during a long request that
neither reads nor writes, such as a large server-side copy. The
connection stays open and keeps serving keep-alive requests, each with a
context canceled from the start, so every 0-byte HEAD on it answered 404.

HEAD now asks zeroByteFileHasChildren, which answers false when the probe
fails, and the file is served. hasChildren keeps answering true for the
listings. A probe on an already-ended context returns at once instead of
failing every filer of the failover walk and counting each as a failure.

TestZeroByteFileHasChildrenServesTheFileWhenTheProbeFails covers a real
child, no child, a canceled context and a filer error.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:49:44 -08:00
f28d101a82 filer, mount: fail writes to a read-only path at once, as EDQUOT (#12823)
* filer: report a read-only create in the response, not as a gRPC error

CreateEntry returned a storage rule's read-only verdict (a bucket over
quota) as a status-less error, which reaches clients as codes.Unknown.
Clients retry Unknown like a filer outage. A mount retried the create of
every new file four times (1/2/4 s) before returning EIO, so each close()
on an over-quota bucket hung 7 s, git on its index.lock included.

Report it the way AssignVolume already does: a successful RPC whose
response carries the text and FilerError_READ_ONLY. CreateEntryWithResponse
and the mount's stream path already map that code to filer_pb.ErrReadOnly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fail a write to a read-only path at once, as EDQUOT

On a read-only path (a bucket over quota), close() of a new file retried
its create for 7 s and then returned EIO, and a failed chunk upload
returned EIO as well. The verdict holds until the bucket is back under
quota, so a retry gains nothing, and EIO names no cause.

- isRetryableFilerError does not retry filer_pb.ErrReadOnly.
- grpcErrorToFuseStatus, writeErrorToFuseStatus, and mkdir, symlink and
  link return EDQUOT for it. ENOSPC still means the cluster is out of space.
- ShouldReassignUpload never reassigns on it, even when the path in the
  message contains "transport".
- CreateEntryWithResponse and the stream path recognize the text an older
  filer sends ("read only: <prefix> ...", as codes.Unknown or as a bare
  message). The mount stops retrying even before its filer is upgraded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin, iam, shell: check a create's response, not only the RPC error

A filer reports a refused create in CreateEntryResponse with a nil RPC
error: an existing directory, a parent that is a file, a store error,
and now a read-only path. Ten callers sent CreateEntry directly and
looked only at the RPC error, so they took every refusal for success. An
admin upload into a bucket that went read-only mid-upload reported
success and skipped its chunk cleanup, and a session revocation that the
filer refused left the session usable.

They now go through filer_pb.CreateEntry, which returns the response's
error as the call's error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb, mount, operation: read a filer verdict as an answer, not a failure

A filer verdict, such as a read-only path, names the path in its
message. Classifiers that fall back to matching that text for words like
"transport" still read a refusal of /buckets/b/transport/f as a broken
network:

- shouldInvalidateConnection closed the shared filer channel, failing
  every other RPC in flight on it.
- The mount's withFilerClient retried the call for about 13 s.

filer_pb.IsFilerVerdict reports whether an error carries a sentinel that
a filer response code maps to. shouldInvalidateConnection keeps the
channel for such an error, and also for an older filer's read-only
refusal that arrives as codes.Unknown. withFilerClient no longer retries
it, and an upload with RetryForever no longer loops on a read-only
assignment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep the first filer's verdict when another filer is down

withFilerClient walks the filer addresses and keeps the last error. When
the first filer refuses a write to a read-only path and the next one is
unreachable, the walk returned the Unavailable from the second, so the
call was retried for 13 s and then failed without the verdict.

Stop the walk at a verdict and keep that filer as the one to try first:
it answered, and every filer gives the same verdict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: fail a metadata write the filer refuses in its response

The filer now reports a create on a read-only path in CreateEntryResponse
instead of as a gRPC error. writeMeta ignored the response, so closing a
zero-byte file under a read-only rule reported success without creating it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-20 12:49:05 -08:00
Chris LuandClaude Opus 5.5 89457b1387 vector: indexed metadata keys, worker job, table state and shell (#12820)
* vector: derive the indexed metadata key columns

An indexed metadata key is a hidden `_mk_<n>` column of List<Utf8>: the
strings an S3 `$eq` on a string matches, that is the value when it is a
string or the string elements of an array, and nothing for any other type
or a missing key. The field metadata names the key and its state
(`building` or `ready`).

The module derives the column from metadata given as JSON (the write
path) or as stored (jsonb or JSON text, for a backfill), and reads the
indexed keys from a schema. It lives in the worker crate so the engine and
the worker share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: fill the indexed metadata key columns on PutVectors

PutVectors builds its batch against the table's current schema. Once a
table has indexed metadata key columns, the three-column batch no longer
matches that schema and the write fails. Fill each `_mk_*` column the
schema has from the row's metadata, whatever the key's state; a column
the engine does not know still fails the request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: answer string $eq and $in on a ready indexed key from its column

The gateway renders a string `$eq` or `$in` on a key as an OR of
`json_extract(metadata, P) = '"v"'` (or IN) and
`json_array_contains(metadata, P, '"v"')` over the same values. On the
parsed filter, a top-level conjunct of that shape on a key whose column is
`ready` becomes `array_has` / `array_has_any` on the column, which its
LABEL_LIST index answers. The two halves must name the same key and the
same strings, the scalar half in the text json_extract returns for them;
anything else, including `$ne`, `$nin`, `$exists`, numbers and booleans,
stays on the JSON path, and the other conjuncts still apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: score few indexed matches exactly, per scope

With a ready indexed key in the filter, `ann` first counts the rows of its
scope that the key's conjuncts match, through the scalar index. When they
are at most the limit it scores them exactly over that scope, the way
the short-result fallback does; above it, the vector index searches with
the indexed prefilter, and the fallback still applies. The scope is the
one `exact_in_scope` scores, so per-scope exact answers merge into the
global exact top-k.

The limit is `Query::exact_match_limit` (None takes 256; 0 never counts),
set by the engine's --exact-match-limit (WEED_VECTOR_EXACT_MATCH_LIMIT).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: count filtered queries by metadata key

For each index, the engine counts its QueryVectors calls by the metadata
keys of the parsed filter, with their total latency and the operand types
each key was compared with, over the last hour in 5-minute buckets. At most
512 indexes and 32 keys per index are kept (an idle key makes room;
otherwise the index is marked truncated), and the stats are not exported
as metrics labels.

The new FilterStats RPC returns an index's stats; the gateway's discovery
client forwards it like the other calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: report the metadata columns capability in gRPC health

An engine whose writes fill the indexed metadata key columns reports the
gRPC health service `weed.vector.capability.metadata_columns` as serving,
so an operator action can refuse to index a key while an older engine
could still write the table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: expire filter stats' operand kinds and truncation with the window

The operand kinds a key was compared with, and the mark that a key went
uncounted, outlived the queries that set them. Keep the kinds per
5-minute bucket and the truncation as the bucket it last happened in, so
both leave the hour window with the counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: fill indexed key columns a write left empty racing their add

A PutVectors that opened the table before an indexed key's column was
added, and commits after the add, is rebased by Lance onto the wider
schema: it commits, and the rows it wrote hold NULL in the new column, so
the column's index misses them (reproduced in the test: 100 of 150 rows).

After its commit, PutVectors now looks for indexed-key columns the batch
did not carry, reads those of its keys whose column is still NULL, derives
the values from their stored metadata and patches just those columns with
a partial-schema merge that updates only rows still NULL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: keep filter stats' truncation mark at the later bucket

record() reads the clock before it takes the lock, so a call that waited
on the lock across a bucket boundary could move the truncation mark (and
the index's last-used bucket) back to its earlier bucket, and the mark
then left the window one bucket early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: derive a raced write's indexed key columns from current metadata

A PutVectors that opened the table before an indexed key's column was
added is retried by Lance against the wider schema: rows it inserts hold
NULL there, and rows it updates keep the value derived from their old
metadata, which the NULL-only heal never looked at. The heal now derives
the columns for all of the write's keys.

Its merge also ran with Lance's retry, which joins the values derived
before the conflict onto the rows a later write of the same keys left.
It now fails on a conflict and is redone from the latest version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: check the raced write's keys keep the later write's rows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector worker: the indexed metadata key lifecycle on the Lance table

A key's whole state lives in the table: a request is schema metadata
(`weed:metadata_key_request:<key>`), the key's `_mk_<n>` column carries
`building`, `ready` or `off`, and its LABEL_LIST index is named
`_mk_<n>_idx`.

- request / request_removal: the cheap metadata-only steps an operator
  action takes. Removal of a column sets it off at once.
- add_column computes the column for every row with add_columns.
- finish fills rows still NULL (a write that raced the add and died
  before filling them), builds the first segments, fills again, marks the
  key ready and clears the request.
- index_fragments keeps the index as time-ordered segments: the first
  build splits the table into segments of up to `segment_rows` rows in
  fragment order (uncommitted builds committed in one CreateIndex);
  later, once unindexed rows reach a threshold, they fold into the head
  (num_indices_to_merge = 1) or start a new head once the head is full
  (num_indices_to_merge = 0).
- maintain fills NULL rows, then folds; remove_column sets off, drops the
  index, then the column.

Filling uses a partial-schema merge that only updates rows still NULL; it
moves the rows it updates to a new fragment, so it serves the few rows a
racing write leaves, not the backfill, which add_columns does in place.

The test runs the whole lifecycle, including a write that opened the
table before the add and committed after it without filling its rows, and
a compaction: Lance keeps each segment's fragments apart and remaps every
segment, and indexed answers match the JSON filter throughout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: list and request indexed metadata keys through the engine

MetadataKeys reports an index's keys as its Lance table records them:
requested (schema metadata), building, ready or off (the column's field),
with the rows, segments and bytes of each key's scalar index.
UpdateMetadataKey records a request to index a key, or to stop: a request
is withdrawn, a column is set off at once. Both are refused with
FailedPrecondition for a key indexed or requested already, past eight
keys, or not indexed. The gateway's discovery and describe clients
forward both, so the shell and admin reach them like the other calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: lance_metadata_index job adds, maintains and removes keys

Detection reads each S3 Vectors table's keys: a requested or `building`
key is to add, an `off` one to remove, and a `ready` one whose unindexed
rows reached `min_unindexed_rows` (default 50,000) to maintain. A job
names the table, key and action, as the admin builds it when it
dispatches one for an operator, and does only what the table still asks
for when it runs. `segment_rows` (default 1,000,000) caps a segment.
The job runs in the Lance scheduler lane.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3vectors: list and request indexed metadata keys for trusted callers

Server.MetadataKeys and Server.UpdateMetadataKey reach the engine's new
RPCs for the shell and the admin server. Adding a key refuses a
non-filterable key of the index, and refuses unless every vector engine
the masters list reports the gRPC health service
weed.vector.capability.metadata_columns as serving, so no older engine can
write the table without filling the key's column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* shell: s3vectors.index.metadata lists, adds and removes indexed keys

s3vectors.index.metadata -bucket b -index i [-add key | -remove key]
prints each indexed metadata key with its state, the share of rows its
scalar index covers, its segments and size. The shell's in-process S3
Vectors server setup moves into shellVectorsServer for both commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: derive raced rows again, not only the NULL ones

A write that raced a key's column add leaves NULL in the rows it
inserted and, in the rows it updated, the value derived from their old
metadata. Filling only NULL rows missed the second kind.

rederive compares each row's column with the value its stored metadata
gives and rewrites the rows that differ, starting over from the latest
version when a write commits meanwhile. finish runs it over the table
before the first build and over the fragments written during the build;
maintain runs it over the fragments the index does not cover yet, before
folding them. The lifecycle test's raced write now moves 500 rows to
another author as well as inserting 500, and all are right once the key
is ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: count indexed matches segment by segment, newest first

The planner counted a filter's indexed matches with a Lance scan of the
query's scope. A fragment-scoped scan makes Lance read the column
instead of answering from the index, and it counted every match.

The count now opens each segment of the key's index that overlaps the
scope, newest first, searches up to eight of them at once in order,
keeps the rows of the scope's fragments, and stops as soon as the total
passes the limit. Rows in fragments no segment covers yet are counted by
a read of the column. An AND is bounded by its most selective indexed
conjunct. Rows a segment still lists after a delete count too: the total
is an upper bound, which can only send a query to the vector index
instead of an exact scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: test jobs on a table dropped under them (fails)

DeleteIndex purges the table directory, and a colocated index created
again under the same name reuses it. The test runs a vector index
build and the metadata key add, maintenance and remove jobs against a
table dropped right after the job opened it, and at the job's first
write. It expects the job to fail, no manifest in the dropped path (no
file at all when dropped before the first write), and a table created
there again to start empty.

It fails today: the remove job's metadata-only commits succeed and write
two manifests into the dropped path, after which creating the table
again fails with "Dataset already exists". The next commit fixes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: a job does not write into a table dropped under it

Jobs open tables through dataset::open, which now wraps the store in a
DropGuard: once the manifest of the version the job opened is gone,
every write fails ("the table was dropped while this job wrote it"),
so the job fails instead of committing a manifest of the old table into
the dropped path. A drop can land between the check and a write, so a
manifest write is checked again afterwards and removed if the table is
gone. Data or index files written in that window stay in the path
unreferenced; no manifest does.

With the guard, the vector index build and the metadata key add,
maintenance and remove jobs fail on a table dropped after their open or
at their first write, leave no manifest (nor any file when dropped
before they wrote), and a table created there again starts empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: test an index dropped and created again on one engine (fails)

DeleteIndex purges the table's directory through the catalog and an
index created again under the same name reuses it. On the same running
engine, after a ready indexed key, a query and its filter stats, the
test drops and re-creates the index, writes new rows and queries again:
no old row, indexed key or filter stat may come back.

Rows and keys come back clean; the filter stats of the old table are
still served for the new one. The next commit fixes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: filter stats follow the table behind an index name

An index dropped and created again under its name is another table, but
its filter stats were kept by name, so the new index showed the old
one's filtered queries. The engine now forgets an index's stats when it
creates or drops the index, and, since DeleteIndex purges through the
catalog without telling the engines, a query of an index whose table id
differs from the one its stats were counted on starts them over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3vectors: refuse indexed key calls when no engine is configured

A Server built without a vector engine client (as the admin's tests
build it) panicked on MetadataKeys instead of answering with an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: a key removed during its build stays removed

Removing a key whose build had not finished set its column off but left
its add request, which reappeared once the column was dropped and asked
for the key again. A build that finished after the removal also set the
key back to ready.

Removal now withdraws the request too, both when the operator asks and
when the job drops the column, and finish marks the key ready only if
the latest version still has it building.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: maintain a key at once when a write left NULL rows

A write that raced a key's add and stopped before fixing its rows leaves
NULL in the key's column, so queries through the key miss those rows.
They land in fragments the index does not cover yet, which maintenance
derives again, but only once the unindexed rows reached the threshold.
Detection now also proposes maintenance when those fragments hold a NULL
row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: test a purge through the drop guard (fails)

A purge removes the versions before its rebuild, including the one it
opened, which the drop guard watches; recording the purge's completion
then fails as if the table had been dropped. The next commit fixes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: the drop guard follows the job's own commits

The guard watched the manifest of the version a job opened, and a job
that removes old versions itself, as a purge does, removed it and then
failed its next write as if the table had been dropped.

The guard now watches the newest manifest the job committed, and when
the job deletes the watched manifest itself, the newest manifest left
beside it. A table dropped under the job still fails its writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector worker: a column add keeps requests and states committed meanwhile

add_columns commits the schema it read, and Lance lets that Merge go in
over the schema and field metadata updates committed while it ran. A key
requested, withdrawn or removed while another key's column was added was
silently undone: the removed key went back to ready and the request
vanished. The add now sets those again, and a key whose own request was
withdrawn meanwhile gets its new column off instead of being built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: keep FilterStats::record's doc on record

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector worker: test the guard against the job's own cleanup directly

The purge test asserted the purge was served, which depends on the
cleanup's retention policy rather than on the guard. It now has the
job remove every version before its own commit, the opened one with
them, through the guarded store, and write again; a purge after that
still completes. Without the previous commit's fix the write after the
cleanup fails with the DropGuard error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: indexed-key tests compare keys, not only distances

assert_same accepted a different key at a rank whenever its distance
matched, so a lost row replaced by a duplicate passed. It now requires
the same keys, and lets two keys trade ranks only when they tie.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: filter stats record their table with each query

A query recorded its stats and its table in two steps, so the first
query of an index left the stats without a table, and a later table
under the name then took them over. A query of the old table finishing
after the index was created again also cleared or added to the new
table's stats.

record now takes the table and, under one lock, starts the stats over
for a new table, keeps the tables the name held before, and drops a
query of one of those.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: asking again for a key change is done, not an error

UpdateMetadataKey commits the request and then lists the keys. When the
listing failed after the commit, the caller saw an error, and its retry
was refused as already indexed, so the change it made could not be
confirmed.

A request for a key requested or indexed already, and a removal of a key
not indexed or already off, now succeed without another commit. A request
for a key still being removed is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: a resumed add sets again what its commit overwrote

add_columns commits the schema it read, so add_column sets again the
requests and key states committed while it ran. A job that stopped
between the add's commit and that step left them overwritten, and the
build that resumed the key, seeing it building, finished it: a removal
asked for meanwhile was lost and the key went ready.

The added column records the version its add read. A resumed build
compares that version's schema with the add's and sets again what the
add overwrote before going on, and stops when that leaves the key off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: a key goes ready only after writes that raced its add are done

A PutVectors that opened the table before a key's column add and
committed after it wrote its rows' key column as of the version it read:
NULL for new rows, the old value for updated ones. It derives them again
itself, but when that failed, or the write was still running when the
build finished, the key went ready with those rows wrong, and maintenance
only filled NULLs.

PutVectors now commits within WRITE_DEADLINE (120s) of opening the table
or fails. finish waits until RACE_GRACE (180s) after the add, then derives
again the fragments written since it first looked, comparing values, not
only NULLs, before it marks the key ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: drop guard tests for a table created again and flaky probes

A job on a table dropped and created again under the name, a probe that
fails after a manifest is written, a multipart upload completing after
the drop, and a cleanup whose paths now hold the new table's files. Each
fails against the guard as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: drop guard tells a table created again from the one opened

The guard only checked that the watched manifest path existed. A table
created again under the name reuses version paths, so a job on the old
table wrote into the new one. A failed HEAD after a manifest write was
taken as a drop and deleted the published manifest. A multipart upload
was checked only when it started, and a cleanup deleted paths it picked
before the drop.

The guard now records the manifest's e-tag and treats another e-tag, or
the manifest gone with others beside it, as a table created again. A
failed probe after a manifest write keeps the manifest. A multipart
upload checks again before it completes, and a cleanup checks once
before it deletes, refusing when another table is there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: order the zero-grace control of the racing-write test

The control ran the stale write 1.5s into finish, so on a slow runner it
could commit before finish's last pass and be repaired, failing the
assertion that it lands after ready. It now commits after finish returns.
With a grace the write still overlaps the wait: it commits 1.5s after the
add, and finish looks again only once the grace from the add has passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: set again what an add overwrote once, over later changes

recover_add replayed the add's historical delta on every resumed build,
so a request withdrawn after it was set again came back. It wrote over
values changed since the add, failed on a column dropped since, and
failed on every attempt once a cleanup removed the version it read.

The added column now carries a restore mark. The restoration is one
UpdateConfig commit that sets the schema entries and key states the add
overwrote and clears the mark, so it runs once. An entry or state
changed again since the add keeps its later value, and a column gone or
holding another key is skipped. The schema the add read comes from the
add's own version; without the version before it, the mark is cleared
and the build goes on. finish waits the whole grace from now when the
add's version is gone.

a_restored_add_is_not_replayed, a_resumed_add_skips_a_column_dropped_since
and a_resumed_add_goes_on_after_a_cleanup failed before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: a removal sets again what the key's add overwrote first

Recovery ran only when an add resumed. A key withdrawn after its add
stopped went to the remove job, which dropped the column and its restore
mark, losing for good the requests and key states the add overwrote.
The remove job now recovers the add before it drops the column; the key
stays off.

a_removal_keeps_what_the_add_overwrote failed before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: drop guard aborts on a failed probe, keeps another's manifest

An upload whose check before completing failed returned the error without
aborting, leaving its parts behind on S3. A manifest write found dropped
or replaced was deleted at its path even when a table created again had
since written its own manifest there.

complete now aborts on a failed probe too. The rollback deletes the
manifest only while its e-tag is the one this write got. Object stores
offer no conditional delete, so a table created again between that HEAD
and the delete is still not covered.

a_failed_probe_aborts_an_upload and
a_rollback_keeps_the_manifest_of_a_table_created_again failed before this
change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* lance worker: test a failed rollback probe over a table created again

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: keep a replacement's manifest when the rollback cannot tell it apart

After a write's manifest, a drop guard that found the table replaced
deleted the manifest whenever its HEAD failed or the PUT returned no
e-tag. It now deletes a replaced table's manifest only when the e-tags
match; a table merely dropped still takes its manifest back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: MetadataKeys leases the version it lists

Like the other reads, it pins the opened version so a purge cannot
reclaim that manifest's index files while the segments are loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: test a key that went ready on an empty table

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: build the first segment of a ready key below the threshold

A key that went ready on an empty table has no segment. Detection held
its unindexed rows to min_unindexed_rows, so a small table stayed
unindexed. A ready key without a segment is now maintained once it has
rows, as index_fragments builds a first segment at any size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: test a repair retried over a compaction of its fragments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: a repair retried after contention derives the moved rows too

rederive started over from the latest version with the fragment ids it
was given. When a compaction caused the contention, those fragments were
gone and the retry repaired nothing, so maintain folded the compacted
rows with their columns still NULL. A retry now also derives the
fragments the newer version added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: test withdrawals that race a key's add

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: a withdrawal that races the key's add sets its column off

A removal that read only the request cleared it, and Lance rebases that
metadata update over the add's Merge, so the column it made stayed
building and finish made it ready. After withdrawing the request, the
removal looks again and sets a column it finds for the key off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: a withdrawal recovers interrupted adds first

An add whose commit overwrote another key's request and stopped before
setting it again hides that request. A withdrawal of it then found
nothing to do, and the add's later recovery brought the request back.
request_removal now recovers such adds before it decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: test a request committed while a column is dropped

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: a drop sets again what it overwrote while it ran

drop_columns commits a Project of the schema it read, and Lance rebases
it over metadata updates, so a request or key state committed while the
column was dropped was lost. remove_column now sets those again as a
column add does, through the overwritten diff split out of
reapply_metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance worker: drop test counts HEADs with try_update

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: test a late query of a dropped table after the next table's first one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: test PutVectors at a version from before a key's column add

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: keep a dropped table retired when its index's stats are forgotten

Dropping or creating an index removed its stats entry, and the retired tables with it, so a late query of the dropped table that came after the new table's first one reset the new table's stats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: refuse PutVectors at a table version

Table.version pins reads. A write opened at a version from before a key's column add would commit rows without the column after the key went ready, past the write deadline and the grace pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: indexed metadata keys panel for S3 Vectors indexes (#12821)

* vector: report an index's rows and vector index type with its keys

MetadataKeys also answers with the table's rows and its vector index type
(IVF_FLAT, or empty without one), which the admin's index panel shows
next to the keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* admin: indexed metadata keys panel on the S3 Vectors bucket page

Each index of a vector bucket gets a card: dimension, metric, vectors and
vector index type; its indexed metadata keys with state, coverage of the
table's rows, filtered queries per hour and index size, with Remove for a
ready key and Cancel for a requested or building one; and the keys its
queries filtered on most in the last hour that are not indexed, with
their average latency. A key filtered only with numbers is marked
"(numeric: phase 2)" and has no Index button.

"+ Index a key" and a listed key's Index button open a dialog for the key,
which refuses the index's non-filterable keys. Adding or removing goes
through the engine; the admin then dispatches the lance_metadata_index
job for that key when a worker can run it, and detection finds it
otherwise. Filter stats are read from every registered engine and summed
per hour over each engine's window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* admin: keep a metadata key's spaces when indexing it

The dialog trimmed the key before sending it, but metadata key names are
exact strings: a key with surrounding spaces would have indexed another
field. Only an empty or all-space name is refused now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* admin: bound the index panel's key lookup

An engine that accepted the panel's MetadataKeys call and stopped
answering held the whole bucket page; the lookup now gives up after five
seconds and the panel shows the error, as the filter-stat calls do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* admin: dispatch a metadata key job without the cluster admin lock

ExecutePluginJob holds the cluster admin lock for the whole run, so a
key build dispatched from the bucket page kept weed shell and the
default lane locked out for up to an hour. The Lance lane runs without
that lock in the scheduler; run the dispatched job the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: pass an index without non-filterable keys as an empty list

An index whose record holds a metadata configuration with no key list
was rendered as `null`, and the dialog's non-filterable check then threw
before it could submit or show an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* admin: ask in a modal before removing or cancelling a key's index

Remove and Cancel on a metadata key asked with the browser's confirm(),
unlike the rest of the page. They now open a Bootstrap modal laid out as
Delete Index's, naming the key and the index, and show a failure in the
modal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* admin: show when an engine's filter stats leave keys out

sumFilterStats dropped each engine's truncated flag, so a panel whose
engine stopped counting new keys listed its frequent keys as complete.
The panel now carries the flag and says the list is partial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:45:37 -08:00
Chris Lu 4c92a00357 admin/plugin: detect again soon after a capacity give-up (#12825)
A scheduled run whose jobs no executor can take gives them up at once,
leaving them to the next detection. For a job type with a long detection
interval that is a whole interval later: a daily job whose only worker
was briefly full lost a day.

Bring the job type's next detection forward to within 10 minutes when
its jobs are given up for capacity, never pushing back an earlier one.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi
2026-11-20 00:31:18 -08:00
Chris LuandClaude Opus 5.5 1d7125abf2 filer: keep AppendToEntry's cluster lock for the whole append (#12819)
* filer: renew AppendToEntry's cluster lock while the append runs

AppendToEntry took a 5 s short-lived lock and never renewed it, so an
append slower than that (slow store, slow volume, GC pause) lost the
lock while still running, and another filer could take it and append
to the same entry concurrently, dropping one append's chunks. Use the
auto-renewing lock the HTTP append path already uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse an AppendToEntry commit once its cluster lock was lost

A renewal can still fail, or the lock can be lost and granted again
under a new generation, while the append runs; another filer may have
appended in between. Check the lock and its generation right before
the entry is written, fail the append so the caller retries, and drop
the manifest chunks this attempt created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* cluster: IsLocked reports a lock whose lease ran out as not held

isLocked only flipped when a renewal came back rejected, a second after
the reply, so a holder whose renewal stalled past the lease (a long GC
pause) still read as locked while the server could hand the key to
someone else. Track the lease from each grant's send time and require
it in IsLocked, which the filer append paths check before committing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: hold the slow-append test past the renewing lock's first lease

The renewing lock grants a 7 s lease, so a 6 s hold passed even with
renewal off; wait past LiveLockTTL so only a renewal keeps the lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: say the AppendToEntry lock check is best effort

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 00:01:24 -08:00
Chris LuandClaude Opus 5.5 6018f87c25 test(s3vectors): add an author-filter workload to the perf suite (#12818)
* test(s3vectors): let a perf test restart the engine with extra environment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3vectors): serve the volume server's metrics in the test cluster

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3vectors): build a named index in the perf suite through one helper

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3vectors): add an author-filter workload to the perf suite

Plants authors at 10%, 1%, 0.01%, fewer than topK and no rows (seed 5),
scattered over the index or written as consecutive keys, and reports the
eligible rows, p50/p95, filtered recall@k against an exact numpy search
over the eligible rows, results per query, hits without a finite
distance, and the engine and volume server read counters, warm or with
the engine's caches at 0 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3vectors): reject duplicate hits and clean up a failed filter workload setup

The workload skips the distributed cluster, since only one engine is
restarted, and accepts only the warm and cold modes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:48:58 -08:00
Chris LuandClaude Opus 5.5 4bbc03747f s3vectors: match json_extract's escaping of control characters in filter strings (#12817)
* s3vectors: render filter string control characters as serde_json does

json_extract serializes the stored value with serde_json: \b, \f, \n,
\r, \t, \u00XX for the rest of U+0000-U+001F, and U+007F-U+009F raw.
The scalar comparison text used Rust debug escapes (\0, \u{1}, \u{7f}),
so $eq/$in on such strings missed scalar values and $ne/$nin kept them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3vectors): filter on every control character, quote and backslash

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:48:27 -08:00
Chris LuandClaude Opus 5.5 e109f91c6f vector: indexed metadata keys, engine side (derive, rewrite, exact planner, filter counter) (#12813)
* vector: derive the indexed metadata key columns

An indexed metadata key is a hidden `_mk_<n>` column of List<Utf8>: the
strings an S3 `$eq` on a string matches, that is the value when it is a
string or the string elements of an array, and nothing for any other type
or a missing key. The field metadata names the key and its state
(`building` or `ready`).

The module derives the column from metadata given as JSON (the write
path) or as stored (jsonb or JSON text, for a backfill), and reads the
indexed keys from a schema. It lives in the worker crate so the engine and
the worker share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: fill the indexed metadata key columns on PutVectors

PutVectors builds its batch against the table's current schema. Once a
table has indexed metadata key columns, the three-column batch no longer
matches that schema and the write fails. Fill each `_mk_*` column the
schema has from the row's metadata, whatever the key's state; a column
the engine does not know still fails the request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: answer string $eq and $in on a ready indexed key from its column

The gateway renders a string `$eq` or `$in` on a key as an OR of
`json_extract(metadata, P) = '"v"'` (or IN) and
`json_array_contains(metadata, P, '"v"')` over the same values. On the
parsed filter, a top-level conjunct of that shape on a key whose column is
`ready` becomes `array_has` / `array_has_any` on the column, which its
LABEL_LIST index answers. The two halves must name the same key and the
same strings, the scalar half in the text json_extract returns for them;
anything else, including `$ne`, `$nin`, `$exists`, numbers and booleans,
stays on the JSON path, and the other conjuncts still apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: score few indexed matches exactly, per scope

With a ready indexed key in the filter, `ann` first counts the rows of its
scope that the key's conjuncts match, through the scalar index. When they
are at most the limit it scores them exactly over that scope, the way
the short-result fallback does; above it, the vector index searches with
the indexed prefilter, and the fallback still applies. The scope is the
one `exact_in_scope` scores, so per-scope exact answers merge into the
global exact top-k.

The limit is `Query::exact_match_limit` (None takes 256; 0 never counts),
set by the engine's --exact-match-limit (WEED_VECTOR_EXACT_MATCH_LIMIT).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: count filtered queries by metadata key

For each index, the engine counts its QueryVectors calls by the metadata
keys of the parsed filter, with their total latency and the operand types
each key was compared with, over the last hour in 5-minute buckets. At most
512 indexes and 32 keys per index are kept (an idle key makes room;
otherwise the index is marked truncated), and the stats are not exported
as metrics labels.

The new FilterStats RPC returns an index's stats; the gateway's discovery
client forwards it like the other calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: report the metadata columns capability in gRPC health

An engine whose writes fill the indexed metadata key columns reports the
gRPC health service `weed.vector.capability.metadata_columns` as serving,
so an operator action can refuse to index a key while an older engine
could still write the table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: expire filter stats' operand kinds and truncation with the window

The operand kinds a key was compared with, and the mark that a key went
uncounted, outlived the queries that set them. Keep the kinds per
5-minute bucket and the truncation as the bucket it last happened in, so
both leave the hour window with the counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: fill indexed key columns a write left empty racing their add

A PutVectors that opened the table before an indexed key's column was
added, and commits after the add, is rebased by Lance onto the wider
schema: it commits, and the rows it wrote hold NULL in the new column, so
the column's index misses them (reproduced in the test: 100 of 150 rows).

After its commit, PutVectors now looks for indexed-key columns the batch
did not carry, reads those of its keys whose column is still NULL, derives
the values from their stored metadata and patches just those columns with
a partial-schema merge that updates only rows still NULL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: keep filter stats' truncation mark at the later bucket

record() reads the clock before it takes the lock, so a call that waited
on the lock across a bucket boundary could move the truncation mark (and
the index's last-used bucket) back to its earlier bucket, and the mark
then left the window one bucket early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: derive a raced write's indexed key columns from current metadata

A PutVectors that opened the table before an indexed key's column was
added is retried by Lance against the wider schema: rows it inserts hold
NULL there, and rows it updates keep the value derived from their old
metadata, which the NULL-only heal never looked at. The heal now derives
the columns for all of the write's keys.

Its merge also ran with Lance's retry, which joins the values derived
before the conflict onto the rows a later write of the same keys left.
It now fails on a conflict and is redone from the latest version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: check the raced write's keys keep the later write's rows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:45:30 -08:00
Chris LuandClaude Opus 5.5 817338c911 volume.merge, volume tail receiver: apply size-0 records for existing keys as deletes (#12816)
* volume: apply a tailed size-0 record as a delete when the key exists

A delete and an empty write both reach the tail receiver as a size-0
.dat record. Writing every one as a live needle turned each delete
caught by volume.move's tail into a 200-empty object. Treat the record
as a delete when the key already has a record on the receiver, and as
an empty write otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rust volume: apply a tailed size-0 record as a delete when the key exists

Mirrors the Go tail receiver: a size-0 record for a key that already
has a record here is a delete, otherwise an empty write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.merge applies a size-0 record as a delete when the key exists

The tail stream carries deletes as size-0 records, and volume.merge
wrote each one to the merged copy as a live empty needle, so every
delete in the volume came back as a 200-empty object on all replicas.
A size-0 record for a key already written in the merged stream is now
a delete on the target; for a new key it stays an empty write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.merge reads a size-0 record as a delete only after its own replica's record

Replicas append the same write at their own times, so a fresh empty write
can reach the merge twice when the copies are further apart than the
dedup window. Tracking keys across all replicas made the second copy a
delete. Track, per source replica, the keys it has returned (duplicates
the merge skips included): a size-0 record is a delete only when its own
replica wrote the key before, which is the only way a replica appends a
delete. A delete for a key the merged copy already deleted sends nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.merge verification counts the deletes the merge applied

Applying deletes lets a correct merge hold fewer live needles than a
replica that missed a delete, and the live-count check then refused it
and kept the divergent replicas. Every key live on a replica is either
live or deleted in the merged copy, so compare that replica's live count
with the merged live count plus the keys the merge deleted. An empty
merged copy is still refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: tail receiver looks a size-0 record's key up in the needle map

The receiver read the needle to decide whether a size-0 record deletes
an existing key. A read reports a needle past its TTL as not found, so
a delete for it was written as a live empty needle, which reads ignore
TTL for. Look the key up in the needle map instead (Volume.LookupNeedle).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rust volume: tail receiver looks a size-0 record's key up in the needle map

Mirror Go: write_tailed_needle read the needle to decide whether a size-0
record deletes an existing key, and a read reports a needle past its TTL
as not found, so the delete became a live empty needle. Look the key up
in the needle map instead (Volume::lookup_needle).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.merge keeps a merged delete when a late empty copy follows

A replica that missed a delete can hold its copy of the empty write
stamped after the other replica's delete. As that replica's first record
for the key it was written, reviving the deleted key. A size-0 record now
never revives a key the merged copy already deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.merge refuses more replicas than its key history has bits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:36:44 -08:00
0a1e337302 wdclient: keep a volume's live replicas readable while another volume cannot be found (#12814)
* wdclient: keep a volume's live replicas readable while another volume cannot be found

A filer's "volume not found" answer counted as a filer failure, so three
of them opened the circuit breaker on a healthy filer. With its only filer
in the cool-down, every lookup then failed without asking, as "all 1
filer(s) failed with non-retryable error: %!w(<nil>)". And a refresh whose
lookup failed left the cache without the volume's live replicas, since
InvalidateCache had already dropped them with the dead one.

The breaker now counts only failures to reach the filer, and asks the
filers anyway when all of them are in their cool-down. InvalidateCache keeps
what it removed; a lookup that errors puts it back unless the volume was
learned again, the epoch moved, or a reset would have expired it, and
leaves out locations fenced by a pushed removal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: set invalidated locations aside in the map instead of copying them out

The first commit kept what InvalidateCache removed in a side map and put it
back when the lookup failed. The copy left the map's lock, so a removal the
master pushed between the take and the put-back was undone: the removed
server came back into the cache.

The entry now stays in the map with a state. entryStale hides it from readers
and releases its server references, as a delete did. A pushed removal edits
it like any other entry. When the lookup after the invalidation returns an
error, the entry becomes entryRevived and is served again.

A stale or revived entry holds only what was known before the read failed,
so the next thing learned replaces it: a lookup answer drops it before the
answer is cached, including an answer with no locations and an answer to a
lookup that was in flight when another one failed, and a pushed add replaces
it instead of merging.

LookupVolumeIdsWithFallback returns no error when every volume it was asked
for has locations after the revive, so the filer's LookupVolume handler sends
its response instead of an error status.

The not-found breaker test now checks the failure count itself. Without
that, a regression of the classification passed, because a lone filer in its
cool-down is asked anyway.

On the first commit, TestPushedRemovalRacingFailedRefreshes failed in 8 of 8
runs under -race: four with "got [live:8080 old:8080], want [live:8080]",
four with "got [], want [live:8080]".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* wdclient: retry a filer lookup pass that asked no filer

The pass decides once whether to skip unhealthy filers. A filer whose
breaker trips after that decision, as when a concurrent lookup records
its failure, is still skipped. With every filer skipped the pass ended
with no error and failed the lookup as non-retryable with
"%!w(<nil>)". Such a pass now counts as Unavailable, so the lookup
retries and the next pass asks the filers anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: believe a provider answer that reports errors for some volumes

The master provider answers a batch with a map of the volumes it knows
and an error naming the ones it does not. The failed-lookup branch took
that as no answer and revived what InvalidateCache had set aside, so a
volume the master reported as absent came back with its old locations,
and the batch could return them with a nil error. Only a nil map now
means no answer. Otherwise the answer replaces what was set aside, and
the provider's error is still returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: keep set-aside locations learned after a lookup was asked

A successful lookup dropped every stale or revived entry of the volumes
it asked for, however old the answer was. A lookup asked before the
master confirmed new locations could, on finishing, delete those
locations after a read had set them aside and a failed refresh had
revived them, and its own answer was not cached because the epoch had
moved. Entries now record when their locations were learned, and an
answer drops only what was learned before it was asked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: keep an older answer from replacing locations set aside after it was asked

fdcde25 keeps dropSetAside from deleting set-aside locations that were
learned after a lookup was asked. The answer's insertion still replaced
them: fillLocations adds each location with vidMap.addLocation, and
addLocationToMap replaces a stale or revived entry whatever its learnedAt.
The epoch does not stop this when the newer locations came from another
lookup's answer or, on the master client, from a pushed add, since neither
moves it. The master client's provider also caches its answer itself,
before LookupVolumeIdsWithFallback reaches dropSetAside.

vidMap.addAnswer adds an answer's locations under one lock, and adds none
of them while vid has a stale or revived entry learned after the lookup was
asked. fillLocations uses it, and the master client's provider passes the
learned mark it takes next to its epoch. An answer with nothing newer in the
way still replaces what was set aside, with every location it reports.

On fdcde25, TestOlderAnswerDoesNotReplaceNewerRevivedLocations and the
"newer location revived during the lookup" case of
TestMasterAnswerAgainstSetAsideLocations fail with
"got [old:8080], want [new:8080]".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: move addAnswer next to dropSetAside

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 22:34:35 -08:00
Chris LuandClaude Opus 5.5 374c77bcbe admin/plugin: fail a restored job its worker no longer lists (#12815)
* admin/plugin: fail a restored job its worker no longer lists

An admin restart reloads the jobs that were running from the persisted
state, but the workers drop those jobs when the old admin stream closes.
No pending execution covers a restored job, so only the 24h stale sweep
ended it, and until then it blocked dedupe and scheduling of its job type.

Track the active jobs loaded at startup by worker and fail one after two
itemized heartbeats from its worker leave it out, as is already done for
a dispatch whose worker restarted. A listed job is left to adoption.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: keep tracking a listed restored job; skip queued ones

- A restored job its worker lists only resets its miss count, so one it
  drops later is still failed.
- Track only jobs that were sent to a worker (request id set, not pending).
- Match restored ids against the trimmed heartbeat ids.
- Fail the restored attempt under the jobs lock that applies the expiry
  (handleJobCompletedIf / expireActiveJobIf), so a newer attempt of the
  same job is neither failed nor canceled.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: keep a newer attempt's detail from a restored-job expiry

- The conditional completion writes the job detail through
  persistJobDetailSnapshotIf and skips it when the stored detail already
  names another request; the check runs under jobDetailsMu with the write.
- mergeTerminalDetailIntoTracked ignores a terminal detail of another
  request, so a restart does not end the loaded attempt with it.
- Tests wait for the restored-job expiries instead of sleeping.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: restore a finished retry from its detail

The job detail is saved as each attempt changes and the job list only
periodically, so a terminal detail naming another request is the newer
attempt. Apply it with its request id instead of ignoring it; the
expiry's own detail write already refuses to overwrite another request.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: restore whichever attempt is newer

The job list and a job's detail can name different attempts either way
round: the list is saved periodically, and a detail write can fail. When
their request ids differ, apply the terminal detail only if it is the
newer attempt (higher attempt number, else later update).

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: fill a restored job's empty request id from its detail

A job the list saved while still queued has no request id; take the
finished detail's, as the merge did before the newer-attempt check.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: take the worker and attempt of a newer restored detail

When the restore takes a finished retry's detail over the job list's
attempt, the record kept the older attempt's worker and attempt number
next to the retry's request id and state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/plugin: fold the conditional completion into the existing functions

handleJobCompleted, expireActiveJob, trackExecutionCompletion and
persistJobDetailSnapshot take the accept check themselves instead of
gaining *If twins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/plugin: ignore a late earlier-attempt completion; replace an older detail

- A completion whose request id differs from the tracked attempt's is a
  late report of an earlier attempt and no longer ends a retry.
- A conditional completion skips the detail write only when the stored
  detail is a newer attempt (detailIsNewerAttempt), so an older finished
  attempt's detail left behind by a failed write is replaced.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: take only the dispatched attempt's reports

A late progress report of a timed-out attempt replaced the retry's request
id, after which the retry's own completion was rejected as foreign. One
rule now gates both: a record the admin dispatched (attempt > 0) takes
progress and completion only for its own request (reportFromOtherAttempt).

When an expiry replaces an older attempt's detail it also takes the
closing attempt's worker, attempt number and times.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: restore a newer running attempt's identity from its detail

The job list can name attempt A while the detail shows retry B running
when the admin stopped. The restore now takes B's request id, worker and
attempt number from such a newer running detail, so B's own reports are
accepted. Test helper keeps a given attempt number.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: keep attemptEnded's doc comment on attemptEnded

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/plugin: dispatch an attempt-less job as attempt 1

The late-report guard only covers records with a positive attempt, and
ExecuteJob passed a zero attempt through, so a direct caller's dispatch
could be closed by another request's completion. The HTTP API already
raised zero to one; the dispatch path now does the same for every caller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:30:52 -08:00
2382f07788 filer: keep a hard-linked file's chunks when one of its names is replaced (#12812)
* filer: keep a hard-linked file's chunks when one of its names is replaced

Replacing one name of a hard-linked file deleted the file's chunks while
its other names still pointed at them. Reads through those names then
return EIO once the volumes are vacuumed; until then they only work
through readDeleted.

Two everyday ways to get there through a mount:
- conda links an environment's files to its package cache with hard
  links. Python saves a __pycache__/*.pyc by writing a temporary file and
  renaming it over the old name, so the cache's copy loses its data.
- A training script saves model.pt, hard-links it into an epoch directory
  and saves the next epoch by renaming a new file over model.pt. Each
  archived epoch loses its data.

Three write paths deleted the chunks of the entry they replaced without
asking whether that entry was one of several hard links:
- a rename over a file: moveSelfEntry drops the target's link, then
  queues all of the target's chunks for deletion;
- CreateEntry over an existing path (an S3 PUT, for one): the update
  drops the old entry's link, then deleteChunksIfNotNew deletes its chunks,
  and the CreateEntry handler deletes chunks its own list covers;
- UpdateEntry with an entry that no longer carries the old one's link.

A plain delete already keeps the chunks while HardLinkCounter > 1, and a
folder delete asks hardLinkIsOrphaned. The three paths now go through
Filer.KeepHardLinkedChunks, which asks after the write, once the replaced
name's link is gone: the chunks stay unless the file's shared record went
with it, that is, unless the replaced name was the last link. Writing the
file through one of its names (an entry with the same hard link id) still
deletes the chunks the write replaced, since every name reads the new
content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep hard-linked chunks from the shared record, not the replaced row

A lookup that cannot read the hard link record returns the name's own row,
which can lag the file. Read the record when filtering the garbage, and keep
everything when it cannot be read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test the manifest reads behind KeepHardLinkedChunks

The manifest resolution moves into withoutChunksOf, which takes the lookup
function, so tests can serve manifests. Chunks behind nested manifests and
the manifests themselves stay, unrelated garbage is still deleted, and an
unreadable manifest returns an error, on which KeepHardLinkedChunks deletes
nothing. Behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 22:14:01 -08:00
Chris LuandClaude Opus 5.5 a91def90c0 volume: count and log needles vacuum drops as unreadable (#12811)
* volume: count needles vacuum drops as unreadable and log each at error level

Vacuum drops a live needle whose record fails to read back intact (CRC
mismatch, malformed fields, short or dangling record). The key leaves the
compacted index with no tombstone, so repair tools later treat it as a
vacuumed delete. Log every dropped key at error level and count the drops
in SeaweedFS_volumeServer_vacuuming_dropped_needles per collection, once
the compacted index is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: add a panel for needles dropped by vacuum

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: count needles vacuum drops as unreadable and log each at error level

Mirror the Go volume server: log every dropped key at error level and add
SeaweedFS_volumeServer_vacuuming_dropped_needles per collection once the
compacted index is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: count dropped needles only after the compacted dat is flushed

The final .cpd fsync runs in the deferred close and loadTmpNeedleMap can
still fail after the index is saved; a copy failing there is retried and
would count the same needles again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:02:31 -08:00
Chris LuandClaude Opus 5.5 2ac8db5cb4 filer: lock the path for plain HTTP overwrites so replaced chunks get deleted (#12801)
* filer: lock the path for plain HTTP overwrites

CreateEntry looks up the entry it replaces and queues that entry's chunks
for deletion. Two plain PUT/POST writes of one path could both read the
same old entry, so the chunks of whichever write lost were never queued.
Take the exclusive path lock around CreateEntry, as the gRPC CreateEntry
already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test concurrent HTTP overwrites queue every replaced chunk

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:01:08 -08:00
Chris LuandClaude Opus 5.5 ac7d949c61 filer: keep a manifest needle until its data chunks are queued for deletion (#12810)
* filer: resolve deleted manifests through the master on a volume cache miss

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a manifest needle until its sub-chunks are queued for deletion

When a manifest could not be read during chunk deletion, the manifest
needle was deleted anyway and the data chunks it listed were orphaned.
Retry the resolve with the deletion retry backoff and delete the
manifest alone only after MaxRetryAttempts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a durable delete that joins a pending manifest retry

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: bound each manifest retry read with a deadline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: requeue resolved manifest ids on an fsync upgrade instead of rereading

A durable delete that joins a manifest retry in flight used to resolve
the manifest a second time, but the first pass had already queued the
manifest needle, so the reread could fail and the sub-chunks never got
the durable mark. Resolve nested manifests up front and queue the same
ids again with fsync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: bound each manifest retry pass and stop it on shutdown

A pass takes ready manifests one at a time and stops after
manifestRetryTimeout, leaving the rest queued for the next tick, so a run
of stalled reads cannot keep the shared retry loop from ordinary deletion
retries or from noticing shutdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:50:40 -08:00
Chris LuandClaude Opus 5.5 8df716b728 volume: make a delete retry after a failed replica fan-out reach the replicas (#12797)
* http: report the status of a failed delete that has no body

A replica that answers a DELETE with a bare 500 left the forwarding
server reporting "[<replica>]: " with an empty reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: forward a delete retry that finds nothing here to the replicas

A delete is applied locally before it is sent to the other replicas, so
when the fan-out fails the client is told to retry while this replica
already dropped the needle. The retry then read nothing here and answered
404 without asking the replicas, so the replica that missed the delete
kept the needle for good.

On a replicated volume, a plain delete that finds the needle missing or
deleted now cancels a write still queued for it, as a replica delete
does, and sends the delete on to the other replicas. A failed fan-out is
reported as before, so the client retries until every replica agrees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): take a replica's 404 to a forwarded delete as done

A replica that no longer holds the needle answers a forwarded delete with
404. The Go server folds that into success, but the Rust server reported
it as a replication failure, so a delete that only had to catch up one
replica failed on the replica that was already in step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): forward a delete retry that finds nothing here to the replicas

Mirrors the Go server: on a replicated volume, a plain delete that finds
the needle missing or deleted cancels a write still queued for it and
sends the delete on to the other replicas, so a retry after a failed
fan-out reaches the replica that kept the needle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: answer a delete whose needle read fails with 500, not 404

A replica's 404 to a forwarded delete is taken as the needle being gone
there. DeleteHandler answered 404 for any failed pre-read, so a replica
whose disk could not read the needle let the primary acknowledge a delete
that replica never applied. Only a missing or deleted needle (or a volume
this server does not hold) answers 404 now; other read errors are a 500,
so the client retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): answer a delete whose needle read fails with 500, not 404

Mirrors the Go server: a replica's 404 to a forwarded delete is taken as
the needle being gone there, so only a missing or deleted needle answers
404; other read errors are a 500 and the client retries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): corrupt the needle with portable file writes in the delete read test

FileExt::write_all_at is Unix-only, so the test did not build on Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:47:02 -08:00
Carlos Leyva 2e4be5e25e mount: report a read-only mount root that does not exist as not found, not as the create error (#12799) 2026-11-19 19:45:41 -08:00
Chris LuandClaude Opus 5.5 f2acfb7be4 volume: serve decoded bytes for a range over a compressed needle (Go and Rust) (#12805)
* volume: serve decoded bytes for a range over a compressed needle

A Range with Accept-Encoding: gzip got Content-Encoding: gzip and a slice
of the compressed bytes, which a decoding client cannot read. The range
is over the stored file's decoded bytes, so pass gzip through only for a
whole read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* seaweed-volume: serve decoded bytes for a range over a compressed needle

Mirrors the Go volume server: a Range with Accept-Encoding: gzip got
Content-Encoding: gzip and a slice of the compressed bytes. Pass gzip
through only for a whole read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* seaweed-volume: HEAD of a compressed needle reports the served length

HEAD answered a compressed needle from its meta: the stored gzip length
with no Content-Encoding, whatever the request accepted. Go reads the
payload and reports what the GET would send: the decoded length, or the
gzip length with Content-Encoding: gzip for a whole read that accepts
gzip. Read a compressed needle in full on HEAD too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/volume_server: range and HEAD over a compressed needle

Both volume servers serve a gzip-accepted range decoded, and HEAD reports
the length the matching GET would send.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* seaweed-volume: decode every gzip member of a compressed needle

Go's gzip reader reads concatenated members; GzDecoder stopped after the
first, so a range over such a needle saw a shorter body and length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:43:02 -08:00
Chris LuandClaude Opus 5.5 b5f23b7dbf vector: answer a short filtered ANN query by an exact scan (#12802)
* vector: answer a short filtered ANN query by an exact scan

A prefiltered query through the IVF index sees only the partitions it
probes. When those hold fewer than k eligible rows the answer is short
(400 matches, topK 500, 63 partitions: about 208 returned), and when at
most k rows match Lance appends the ones its probes missed with an
infinite distance. Either case is now answered again by an exact scan of
the same scope: the listed fragments plus the live coverage of the listed
index segments, or the whole table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* vector: count an explicit probe count as indexed only with an index

With nprobes set on a table that has no vector index, the scan was marked
indexed, so a filtered query matching fewer than k rows ran the same exact
scan a second time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:42:02 -08:00
261c534c19 filer: retry TiKV store writes on a write conflict (#12798)
* filer: retry TiKV store writes on a write conflict

TiKV transactions are optimistic. A commit fails with a write conflict
when another transaction committed one of its keys after it began, even
for a blind Set or Delete. Outside a filer transaction the TiKV store
runs each save and delete in a transaction of its own and returned that
error to the caller, so of two requests writing the same entry at the
same moment one failed, and a mount reported EIO.

A write the store commits itself (InsertEntry, UpdateEntry, DeleteEntry,
one batch of DeleteFolderChildren, KvPut, KvDelete) now runs again in a
new transaction after a write conflict, up to 5 times, waiting 1-2ms,
2-4ms, ... 16-32ms in between. The failed transaction stored nothing,
and the retry lands after the other writer, as if the two had not
overlapped. The retries stop when the context is done.

A write inside a transaction from BeginTransaction is not retried: the
conflict is reported when the caller commits, as before.

deleteBatch now goes through RunInTxn like the other writes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: stop TiKV write retries once the context is done

When the context was cancelled while the retry wait was running, the
timer case could still win the select and start one more transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a TiKV entry that is no longer expired when listing deletes it

The listing decides an entry has expired from its own read, and the
delete ran later as a blind delete. Once the delete retries after a
write conflict, a live replacement committed in between was removed.
Read the entry again in the deleting transaction and delete it only if
it is still expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 19:17:26 -08:00
github-actions[bot] 5e003bae7d docs: regenerate star history chart 2026-11-20 01:22:33 +00:00
Chris LuandClaude Opus 5.5 4ac3633f1c volume: check the needle id in the streamed-read probe and on blob writes (#12794)
* storage: reject a streamed read whose record id or size differs

The header probe before a streamed read returned not-found only when both
the record's id and its size differed from the index entry, so a record of
another needle with the same size passed and its data was streamed under
the requested key until the final checksum check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: refuse a needle blob whose header names another needle

WriteNeedleBlob compared only the blob header's size with the size it was
asked to index. A blob read from an offset that has since moved to another
record of the same size was appended and indexed under the wrong key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): refuse a needle blob whose header names another needle

Mirror of the Go check: write_needle_blob_and_index compared only the blob
header's size, so a blob of another needle with the same size was appended
and indexed under the requested key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): report not-found when a streamed read's record is another needle

The meta read ahead of a streamed reply took the id from the record header
without comparing it with the requested key. Return not-found when the
index entry resolves to another needle, as the Go header probe does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: check the requested id after a meta-only read

ReadNeedleMeta overwrites n.Id with the record's header id, so a meta-only
read through an index entry that resolves to another needle returned that
needle's metadata, and the streamed-read probe that follows compared the
record with itself. Return not-found when the header names another needle,
as the Rust meta read does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: copy a needle blob to another volume, not under another key

WriteNeedleBlob now refuses a blob whose header names another needle,
so the round trip writes the blob under its own id into a second volume
and checks that storing it under another key is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: compare the streamed header with a deleted entry's record size

A deleted index entry stores the negated size, so a read-deleted stream
compared the positive header size with a negative one and missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:27:15 -08:00
Chris LuandClaude Opus 5.5 4a5dbe4c6f storage: copy an empty needle written during compaction in makeupDiff (#12796)
* storage: copy an empty needle written during compaction in makeupDiff

A size-0 index row is a live empty needle, not a delete. makeupDiff
grouped it with tombstones and appended a made-up delete marker, so
the compacted .dat lost the record's cookie and held a delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): copy an empty needle written during compaction in makeup_diff

A size-0 index row is a live empty needle. makeup_diff wrote a made-up
delete marker and a tombstone row for it, so the needle read as not
found after the commit. Copy the record like any other live row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: fail makeupDiff when the replayed needle write fails

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): check the compacted empty needle's id and cookie in the test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:20 -08:00
Chris LuandClaude Opus 5.5 ba1bfa816c admin: show a pruned job's detail from its run record (#12795)
* admin: show a pruned job's detail from its run record

Tracking keeps the newest 1000 jobs across all job types and deletes
the details of older finished ones, while each job type's run history
keeps its last 10 successful and 10 failed runs. A job listed in the
run history could therefore open as "job detail not found". Fall back
to the run record when the job is no longer tracked.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin: show 100% progress for a pruned successful run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: use the newest run record for a job across both outcomes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep the run record a pruned job's detail was built from

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep looking for a run record past an unreadable history

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: pick a pruned job's newest run record across job types

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:23:46 -08:00
Ping QiuandClaude Opus 5.5 be8ebc2e04 storage: build the temporary needle map in CompactByVolumeData (#12788)
* storage: red test for CommitCompact after CompactByVolumeData with a concurrent write or delete

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: build the temporary needle map in CompactByVolumeData

Fixes #12783

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: require a successful commit in the CompactByVolumeData commit test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:06:05 -08:00
Chris LuandClaude Opus 5.5 bfbeed61a7 storage: read only the header and trailer in the append-time search (#12791)
BinarySearchByAppendAtNs, its left/right probes and ResumeByLastEntry read
every probed record through readNeedleAt, which parsed the whole body and
verified the data checksum, although they use only the id, cookie, size and
append time. One record with damaged data on the search path, even a needle
deleted long ago, failed the search and with it the tail sender, a
timestamp-based incremental copy and the volume.move catch-up.

readNeedleAt now reads the header and the trailer and skips the data. The
data checksum is still verified where the data is read, including the tail
receiver for every record it gets. The Rust volume server already parses
only the metadata on this path and does not verify the data checksum.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:02:25 -08:00
05427e8108 storage: hold the data-file read lock across the append-time search (#12789)
* storage: red test for the append-time search racing a vacuum commit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: hold the data-file read lock across the append-time search

Fixes #12785

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: Version() writes the superblock version only when it changes

Version() stored the .vif version into SuperBlock.Version on every call, so
each call was a write that raced with readers of the superblock that do not
take superBlockAccessLock, such as the append-time search and the
compaction setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: harden the append-time search race test; add a lock-hold budget test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: Linux-only lock budget; stop before reading search failures

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 15:01:47 -08:00
Chris LuandClaude Opus 5.5 f7323f2b63 filer: optional HTTP Basic Auth on the filer HTTP ports (#12778)
* security: add a constant-time HTTP Basic Auth check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: require HTTP Basic Auth on the HTTP ports when configured

With filer.basic_auth.password set in security.toml (or
WEED_FILER_BASIC_AUTH_PASSWORD), a request on the filer HTTP ports, TUS
included, must carry those credentials or a valid filer JWT, and an
access level with no JWT signing key is no longer open. Valid Basic
credentials grant read and write. 401 responses then carry a Basic
challenge so browsers prompt. The credentials reload on SIGHUP with the
signing keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: document filer.basic_auth in security.toml

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: enable reloaded Basic Auth before swapping the JWT keys

Reload cleared the old signing keys before storing the new Basic
credentials, so a switch from JWT to Basic Auth briefly left both off
and admitted anonymous requests. Store new credentials first and clear
old ones last.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse Basic credentials on cross-origin browser requests

Browsers resend cached Basic credentials on requests other websites
trigger, such as a form POST with mv.from, and the default
cors.allowed_origins "*" lets them through. Accept Basic credentials
only on requests without an Origin, from the filer's own host, or from
an origin explicitly listed in cors.allowed_origins. A JWT is still
accepted from any origin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: recheck Basic Auth after reading an empty signing key

A request that loaded Basic Auth as off, then read the signing key after
a JWT-to-Basic Reload had cleared it, was let through anonymously. Open
access now also needs Basic Auth to be off after the key read; with
Reload enabling the new credential before disabling the old one, the
two loads cannot both miss a credential that was on throughout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: compare Basic Auth credentials as MACs under a per-process key

A plain SHA-256 of the password is what password-hash scanners flag;
keying the digests with a random per-process HMAC key keeps the
length-independent constant-time compare without holding one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: read a configuration file without merging into the shared viper

LoadConfiguration merges each read into the shared viper, so a key
removed from the file keeps its old value after a reload.
ReadConfiguration reads the file into a fresh viper with the same search
path and WEED_ environment overrides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: turn Basic Auth off when security.toml no longer sets it

The shared viper merges each SIGHUP reload into what it held, so
removing [filer.basic_auth] kept the old password valid. Read the
credentials from security.toml alone at startup and on reload; an
unreadable file keeps the current setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep Basic Auth when security.toml cannot be read

A malformed file at startup dropped a WEED_FILER_BASIC_AUTH_PASSWORD
from the environment, and viper reports an unsearchable config
directory as a missing file, which turned Basic Auth off on reload.
ReadConfiguration now always returns the environment overrides and
reports whether the file was read; a reload that could not read it
keeps the current credentials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep reloading Basic Auth from the security.toml first read

A search directory that turned unsearchable made viper fall through to a
lower-priority security.toml, and a reload from a file without
[filer.basic_auth] turned Basic Auth off. ReadConfiguration now takes the
file to read, and the filer reads the file it first found on every reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:19:46 -08:00
f5e091cf91 wdclient, s3: return an embedded S3 gateway to its local filer after failover (#12772)
* wdclient: sort newly discovered filers and log every current-filer switch

Discovery appended new filers in map iteration order, so after the current
filer left, the fallback at index 0 was a random filer. Append them sorted.
Route every change of the current filer through one helper that logs it at
V(0) with its reason (failover, return_home, discovery), so an operator can
see which filer a gateway uses without new metrics.

* wdclient: prefer a home filer and return to it after failover with backoff

A FilerClient with FilerClientOption.HomeFiler set goes back to that filer
once its circuit breaker allows a re-check, instead of staying on whichever
peer it failed over to. Leaving home again soon after a return doubles the
wait before the next return, up to 5 minutes; a return that holds for 10
minutes resets it. Volume lookups and discovery follow the same preference.

* s3: embedded gateway uses its local filer as home filer

weed filer -s3, weed server -s3 and weed mini now build the gateway's filer
address in the form the filer registers in the master (ip:port.grpcPort),
with the gRPC port default applied, and pass it to the gateway as its home
filer, so the gateway returns to its local filer after any failover.
Standalone weed s3 has no home filer and behaves as before.

Refs #12768, follow-up to #12771

* wdclient: switch the current filer only from the filer a request started on

A volume lookup that started on a peer and finished after the client had
returned home moved it back to the peer and counted that as leaving home,
doubling the return backoff although home never failed. Concurrent
failovers could also each count as a separate departure.

Failovers now name the filer they started on and take effect only while it
is still current, via compare-and-swap, so only the winning switch logs and
feeds the backoff. S3's failover walk uses the same rule.

* wdclient: switch the current filer and record the return backoff in one step

The index moved by compare-and-swap before the switch was recorded, and
both ran under the shared read lock. A request reading the current filer
in that gap saw the peer with the old eligibility time and, with home's
breaker still closed after one failure, switched straight back home.
The eligibility check, the move and the bookkeeping now all run under
homeMu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: discovery falls back past a home that is still backing off

When discovery removed the current filer and home was not yet eligible,
the client took index 0, which is home whenever it is listed first. With
home's breaker still closed after a single failure, requests went back to
the filer they had just left. Take the next filer instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: start return timing on every switch back to the home filer

Only a return_home switch stamped lastReturnHome. Discovery or a peer's
failover could also put the client back on home, and a failure soon
after such a return kept the backoff at its base value instead of
doubling it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Konstantin Lebedev <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:18:57 -08:00
Chris LuandClaude Opus 5.5 c9f3a02b94 filer: recover a leveldb store whose table a power loss damaged (#12780)
* filer: recover leveldb without rebuilding broken tables

leveldb.Recover rebuilds a table with damaged blocks using the user
comparer and filter on internal keys. The shortened index keys it writes
are not valid internal keys, so a Get on the rebuilt table panics, and
the bloom filter it writes misses every lookup. Recover with a comparer
that keeps full index keys (same name, so the manifest still matches)
and no filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: recover a leveldb store when a compaction finds a corrupted table

When a compaction reads a damaged table block, as a power loss can
leave one, goleveldb latches the corruption error and returns it for
every later write until the database is reopened. A plain reopen loads
the same table and the next compaction fails again, so the store kept
rejecting inserts even across restarts.

Treat a corruption error from a write like a storage error, and reopen
through leveldb.Recover, which rebuilds the table without the damaged
blocks, then retry the write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: rebuild damaged leveldb tables before Recover

leveldb.Recover's own table rebuild orders internal keys with the user
comparer, so a damaged table holding several versions of one key fails
with "keys are not in increasing order" and the recovery gives up.
Overriding the comparer cannot fix that, because the same comparer
also serves the recovered database's user keys.

Rebuild every table that has corrupted blocks first, using an internal
key comparer and full index keys, then let Recover rebuild the manifest
from tables it no longer needs to rewrite. Seed the test tables from a
journal flush so they keep several versions of a key, and check keys
the write test does not rewrite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: leave unreadable leveldb tables for Recover to drop

table.NewReader reports a truncated table or a damaged footer through
the reader, not its error, so rebuildDamagedTables never stopped on one,
but it rewrote it as an empty table first. Skip tables with nothing
readable and let Recover drop them, and test an unreadable table next
to a healthy one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: let StrictRecovery drop damaged leveldb tables

With StrictRecovery set, leveldb.Recover drops a table that has corrupted
blocks. Salvaging the readable blocks first would hide the damage from it,
so skip the rebuild under that option.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: hold the leveldb storage lock while rebuilding tables

The table rebuild ran after the failed open released the storage lock
and before Recover took it, so it could rewrite the tables of a database
another caller had open on the same storage. Take the lock for the
rebuild; Recover takes it again afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:13:30 -08:00
6bdcd17ed4 master: reject an assign on a follower as Unavailable (#12779)
* master: reject an assign on a follower as Unavailable

Assign on a master that is not the raft leader returned
raft.NotLeaderError as a plain error, which reaches gRPC clients as
codes.Unknown. operation.Assign retries only Unavailable,
ResourceExhausted, Canceled and DeadlineExceeded, so every assign made
during a leader election failed at once instead of waiting for the new
leader.

Return it as codes.Unavailable, like the warming-up status in the same
file, so clients retry within their 30 s assign budget. The message is
unchanged, so callers that match "Not current leader" still work.
StreamAssign now answers such a request in-band with the error message
instead of ending the stream, as it already does for warm-up.

TestAssignOnFollowerIsUnavailable covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: keep the cached channel when the peer answers Unavailable with details

gRPC's own Unavailable (dial failure, closing transport) never carries
details, so one that does came from the peer over a working channel.
Closing the shared ClientConn for it cancels every other in-flight RPC
on it with "the client connection is closing".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: tag the follower's assign rejection with a NOT_LEADER ErrorInfo

The detail marks it as the master's answer, so clients retry it
without tearing down their cached channel to that master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 13:11:40 -08:00
Chris LuandClaude Opus 5.5 729b872f01 test: let the merge-read FUSE test wait out the master's vacuum drain (#12777)
* test: let the merge-read vacuum outlast the master's write drain

Before compacting a volume the master waits up to 30 s for writes it
assigned to that volume to drain. The test cut each /vol/vacuum call at
30 s and gave the vacuum 60 s, so one or two slow drains failed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: retry the merge-read vacuum until the master runs one

A 409 means another vacuum holds the master's lock; check the chunks
only after a vacuum this test asked for has finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:44:48 -08:00
Chris LuandClaude Opus 5.5 972f85159e util/http: probe dead replicas in the background and key no-answer dials by machine (#12776)
* util/http: probe an unanswering server in the background, not on a read

Once the retry interval passed, the first read put the dead server first
and waited out the full dial timeout before trying a live replica. Keep it
last and dial it from a background probe with a short timeout instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: try every server of a machine that does not answer last

Unreachability was kept per host:port, so a powered-off node running one
volume server per disk cost one stalled read per server before each was
known dead. A dial that times out or finds no route now marks the whole
machine; a refused connection still marks only that port and shows the
machine is up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: probe an unanswering server with an HTTP request

A bare TCP connect cleared servers that accept connections but never send
response headers, and could not dial an address without an explicit port.
Probe with a HEAD request through the global client instead, and have the
tests wait for the probe to settle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: keep a timed-out port last after a sibling port answers

A dial timeout stored only the machine verdict, so a success on another
port of that machine cleared it and the port that timed out went back to
the front. Record the port as well as the machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: classify refused and unroutable dials with Winsock errnos on Windows

Windows reports these as WSAECONNREFUSED, WSAEHOSTUNREACH and friends,
which errors.Is does not match against the syscall constants. Test the
refusal with a real dial to a closed port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: wait for background probes through a WaitGroup in tests

A refused probe can finish before the test reads the claimed record, so
inferring completion from the record's timestamp could wait out the
deadline on a probe that already settled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: key machine verdicts apart from hosts without a port

A host without an explicit port is also its machine name, so a sibling
port answering cleared the timed-out host along with the machine verdict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: group a bracketed port-less IPv6 host with its machine

net.SplitHostPort rejects "[2001:db8::9]", so the machine key kept the
brackets and missed the verdict stored for "[2001:db8::9]:9501".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:44:10 -08:00
ed7324611c filer: metrics for metadata subscription delivery (lag, holds, ring fall-offs, claim and watermark ages) (#12773)
* filer: metrics for metadata subscription delivery (lag, holds, ring fall-offs, claim and watermark ages)

* filer: measure subscribe delivery lag after the real send using the mutation stamp, and record a watermark hold once per hold

* filer: skip empty progress markers when sampling subscribe delivery lag

* filer: assert subscribe delivery lag is sampled only after the stream send succeeds

* grafana: panels for the metadata subscription delivery metrics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: record a watermark hold when the read passes the held entry, not when the next hold starts

* filer: use a monotonic clock for the subscribe hold duration

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:43:34 -08:00
Chris LuandClaude Opus 5.5 05a1463855 wdclient: keep the embedded S3 gateway on its local filer across discovery (#12771)
* filer: keep an explicit gRPC port in the embedded gateways' filer address

runFiler handed the embedded S3/WebDAV/IAM/SFTP gateways
NewServerAddress(...).String(), and String() drops the .grpcPort part.
With a non-default -port.grpc the gateways then dialed port+10000 and
did not recognize their own filer in the master's list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: match discovered filers by gRPC address

A filer listed as host:port and the same filer discovered as
host:port.grpcPort were compared as raw strings, so a refresh pruned the
configured filer, added every discovered filer as new in map order, and
reset the current filer to whichever came first; a pushed join added it
a second time. Key filers by their gRPC address: a survivor keeps its
health and current position and takes the discovered address form, and
pushed joins and leaves match the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:42:31 -08:00
c1c95e127f filer: scoped read-only tokens for metadata subscriptions (#12767)
* security: scoped read-only token for filer metadata subscriptions

A token signed with jwt.filer_signing.subscribe.key names the subscribe
methods and the path prefixes its holder may see. mTLS peers and admin
tokens stay unrestricted. Internal subscribers attach an admin token
when both keys are configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: enforce subscription token scope on metadata streams

With jwt.filer_signing.subscribe.key set, SubscribeMetadata and
SubscribeLocalMetadata authorize the caller first. A scoped caller gets
a stream that sends only events whose paths are all under its prefixes,
filters batches, and never carries log file refs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: send an admin token on internal metadata subscriptions

Peer filers, metadata followers and the lifecycle reader attach an
admin token when the subscribe key is configured, so they keep the full
stream without mTLS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: add fs.meta.token to mint metadata subscription tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: end scoped metadata subscriptions at token expiry

The scope now carries the token's exp. The scoped stream's context ends
at that time and the call returns Unauthenticated, so an open stream no
longer outlives its token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.sync: sign metadata subscriptions with the source cluster's key

MetadataFollowOption takes a FilerJwtProvider; filer.sync passes the
one loaded from -a.security or -b.security, so clusters with different
admin keys both accept the subscription.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: report fs.meta.token flag errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: give scoped metadata subscribers their own client id

A scoped caller could reuse another subscriber's ClientId with a higher
epoch and replace that registration, disconnecting it. Scoped streams now
register under a server-chosen id that no other subscriber holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: accept only HS256 metadata subscription tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: test HS384 metadata subscription token rejection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: never let a scoped subscriber replace another registration

The server-chosen id can be taken by another subscriber between choosing
and registering it. Registering scoped streams with the lowest epoch makes
addClient refuse them rather than replace the other registration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: send position markers for events a scoped token withholds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test a scoped stream withholding a whole event batch

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: filter SendMsg on scoped metadata streams

The scoped wrappers only overrode Send, so a SendMsg on the embedded
stream would reach the client unfiltered. Route it through the same
filter and refuse any other message type. Ported from #12790.

Co-authored-by: mindaeon <30555587+mindaeon@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test a scoped subscription through the real subscribe loop

Run SubscribeLocalMetadata with a scoped token over a flushed backlog,
the in-memory tail and live events: only in-scope events arrive, sibling,
"..", encoded and cross-boundary rename paths are dropped, and no log
file references are sent although the client asks for them. Without the
subscribe key every event still arrives. Ported from #12790.

Co-authored-by: mindaeon <30555587+mindaeon@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test that the HTTP API refuses metadata subscription tokens

GET, HEAD, PUT, POST and DELETE all refuse a subscription token, also
when the subscribe key equals the read or write key. Ported from #12790.

Co-authored-by: mindaeon <30555587+mindaeon@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: mindaeon <30555587+mindaeon@users.noreply.github.com>
2026-11-19 12:41:16 -08:00
Chris LuandClaude Opus 5.5 668ca45029 s3: ListParts returns each part number once, its latest attempt (#12770)
* s3: list each part number once, its latest attempt

Every UploadPart writes its own NNNN_<uuid>.part entry, so a part number
uploaded twice listed twice, superseded ETag included, and a max-parts page
could hold only the stale attempt. ListParts now groups the entries by part
number, reports the attempt sortEntriesByLatestChunk ranks first (the same
order completion uses), and pages over distinct part numbers, reading past a
page boundary that splits one part number's attempts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: test ListParts over repeated part attempts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: rank an empty part attempt by commit stamp or mtime

An empty UploadPart body stores no chunks, so sortEntriesByLatestChunk gave
it time zero and an empty re-upload always lost to the attempt it replaced.
Attempts now rank by the filer's commit stamp when both carry one, else by
the later of the first chunk's write time and the entry mtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep only the newest attempt per part while listing parts

listPartAttempts held every attempt of a part number until the page was
built, so a heavily retried part grew one ListParts request's memory past
what max-parts bounds. It now compares each entry against the newest seen
for its part number with compareLatestPartAttempt, the comparator
sortEntriesByLatestChunk sorts with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: order part attempts by commit stamp, then attempt time

Comparing commit stamps only when both attempts carried one made the order
non-transitive across stamped and unstamped attempts, so listing and
completion could pick different attempts depending on input order. The
commit stamp now leads (unstamped entries predate the field) and the
attempt time breaks ties.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: list part 10000 after the four-digit part numbers

Part names sort as text, so 10000_<uuid>.part lands between 1000.part and
1000_<uuid>.part. A page could end on part 10000 and the next marker then
skipped parts 1000-9999, and a legacy 1000.part could be reported before
the newer attempt of part 1000 was read. List the four-digit part numbers
first and part 10000 in its own prefix listing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: test ListParts paging across part 10000

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:36:27 -08:00
Chris LuandClaude Opus 5.5 dcbea0626f test/s3: patch s3-fast-list's data map race in the listing study build (#12766)
test/s3: build s3-fast-list with its data map draining the last page

The data map task reads the channel and then the list-task state. When
the list task sends its last page and completes between the two reads,
the map is dumped without that page and the tool exits 0, so a one-page
prefix comes back empty. Read the state before the channel.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:21:32 -08:00
Chris LuandClaude Opus 5.5 de4075660f telemetry: refresh the server module's go.mod so the integration test builds (#12765)
* telemetry: refresh the server module to the root module's dependency versions

The server module replaces seaweedfs with ../.., so root dependency
bumps raised prometheus/common, prometheus/procfs and x/sys past the
versions its go.mod listed, and go build refused to run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the telemetry integration test on root go.mod changes

The telemetry server module builds against the root module through a
replace directive, so a root dependency bump can leave its go.mod stale
without touching telemetry/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:55:09 -08:00
Chris LuandClaude Opus 5.5 652133a28a telemetry: keep the newest release in the versions chart (#12764)
The versions chart keeps the 8 versions with the most clusters on the last
day and folds the rest into "other". A new release starts small, so 4.54
(282 clusters) was folded in while 4.53 shrank as clusters upgraded,
which showed as a dip across the named versions. The newest plain release
now always keeps its own band.


Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:08:19 -08:00
e012fca9a2 mount: keep lookups from stalling behind directory cache rebuilds (#12754)
* mount: release the meta cache lock between batches of a rebuild wipe

deleteFolderChildrenForRebuild held mc's write lock while it listed every
cached child of the directory and deleted them. Every metadata read in the
mount (FindEntry, IsNameFresh, isOversized) takes the read lock, and a
waiting writer blocks new readers, so while a large directory was wiped,
lookups and getattrs in unrelated directories queued behind the scan. The
scan gets slower as leveldb accumulates the deletion markers of earlier
wipes of the same directory, which happens quickly once lookups rebuild
expired directories.

Wipe rebuildWipeBatchSize (1024) children per lock hold and drop the lock
between batches. A child is judged pinned under the same lock that deletes
it, so a local-only create is kept whether it was pinned before the wipe
started or between batches. The listing that refills the directory already
ran outside the lock, so batching adds no interleaving the build did not
allow.

Add LevelDBStore.BatchDeleteEntries, the counterpart of BatchInsertEntries.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: bound how long a lookup waits on the directory rebuild it starts

Since #11268 a lookup whose parent's cache expired rebuilds the parent and
every expired ancestor up to the mount root before it answers, and every
lookup beneath them joins the same builds. With a slow listing (a large
directory, a busy filer, or the meta cache lock held by another rebuild) a
plain stat, an ls -l, or the parent touch after mkdir waited for all of it.

Wait at most lookupRebuildTimeout (2s), then fall back to one LookupEntry
RPC. Since #12206 the shared build does not run on the requester's context,
so it keeps going after the waiter gives up and later lookups find the
directory cached. A timed-out wait records a rebuild attempt, so lookups
during the cooldown do not queue on a build that is already known to be
slow.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: wait for the rebuild's listing in TestLookupDoesNotWaitOutSlowRebuild

The build runs on its own goroutine, so the lookup that stopped waiting
for it can return before the build's ListEntries reaches the filer. The
test read `started` without waiting right after the lookup returned, which
relied on an ordering nothing guarantees, and the ListEntries count taken
afterwards assumed the same. Wait for the listing to arrive, bounded by
the test's deadline.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: keep children inserted while a rebuild wipe runs

A deferred create inserts its placeholder before Create registers the
handle that pins it. The single-lock wipe made such an insert wait until
it finished, so the placeholder survived; a batch that runs in that gap
judged it unpinned and dropped it, and the rebuilt listing then omitted
the file until its flush.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop a cached path that an event vacates during a rebuild wipe

A build replays only the events later than its listing's snapshot and
leaves the earlier ones to the listing, which starts after the wipe. With
the wipe in batches a file's whole life fits inside it: created, flushed,
then unlinked or renamed away. Both events are earlier than the snapshot
and are skipped, the listing has no such file, and the placeholder the
wipe kept stays in the published directory until the next rebuild.

While a directory's wipe runs, an event buffered for it now takes the
path it vacates out of the store at once, fenced by versions like any
other event. After the wipe the store holds what the listing put there,
and a removal earlier than the snapshot may still arrive, so from then on
the event is left to the replay as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: check which file a removal took away during a rebuild wipe

Two things the removal applied during a rebuild wipe got wrong.

A placeholder is unversioned, so the version gate lets every removal
through. One that arrived late, for an earlier file of the same name,
took out the placeholder of a file created since. The entry the event
took away is now compared with the cached one, by inode or, with no
inode to compare, by creation time. An event that only names the file
cannot tell and is taken at its word.

The entry was deleted without OP=MV, so taking one name of a hard-linked
file out of the cache also took one off the count its other names share.
A replayed event that vacates a path already deletes with OP=MV.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: keep a removal the rebuild wipe declined out of the replay

The wipe declines a removal when what is cached there is newer than the
event or is another file than the one it took away. The event stayed
buffered anyway. An unversioned listing clears the children's version
records and replays every buffered event, so the declined removal then
deleted the entry the wipe kept and the directory was published without
it.

A declined removal now buffers only the name it puts in place, so a
rename still lands on replay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check a declined removal again when the build replays it

The previous commit dropped the removal half of an event the wipe
declined, judged by the file cached when the event arrived. Earlier
buffered events can replace that file during the replay: a listing
attempt that failed leaves its events buffered, so the retry's wipe may
see the first attempt's file while the replay puts a later one in place
first. The dropped delete then left that later file published.

The wipe now records which removals it declined, and the replay checks
each against the entry it finds at that point, replaying only the name
the event puts in place when that entry is still another file. A
removal declined by version is replayed as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a declined removal's invalidation off the placeholder's handle

After the replay the build invalidates every buffered event again,
raised to the snapshot, and it still sent the original of a removal the
replay rejected. A late delete of an earlier file then reached the
handle of the placeholder at that name: the placeholder is unversioned,
so the raised timestamp got past it and the handle was marked deleted.

The replay's decision on a declined removal now replaces the event in
the buffer, and the invalidations use what was replayed. It is made
before the snapshot check, so a removal the listing covered is judged
the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep an event's signatures on the halves a rename is split into

A declined removal replays as its rename's create half, and a rename across
a building directory is split in two. Both dropped the event's filer
signatures, so a handle stamped by that filer no longer fenced the replayed
invalidation by timestamp and could take older listed contents over newer
ones it had read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drain invalidations around the declined-removal build check

Invalidations run on a background worker, so the baseline could miss the
removal's own and the final read could run before the build's arrived.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-19 00:04:03 -08:00
Chris LuandClaude Opus 5.5 3159b8408c filer, volume: fsync chunk deletes under an fsync path rule (#12759)
* volume: fsync a batch delete that asks for it

BatchDeleteRequest gets an fsync field, and the Go and Rust volume
servers pass it to the needle delete, which already orders the
tombstone, .dat sync, publish and .idx sync for a durable delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* operation: pass an fsync flag to batch deletes

DeleteFileIdsWithLookupVolumeId and DeleteFileIdsAtOneVolumeServer take
an fsync argument and send it in the BatchDeleteRequest. Every caller
passes false for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: fsync chunk deletes under an fsync path rule

DeleteChunks passes the path rule's fsync flag to the deletion queue.
The flag is kept with the pending record until the delete is
confirmed, so retries and re-queues keep it, and the batch and retry
loops send marked ids in a durable BatchDelete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep fsync marks in the deletion ledger

Marked ids go into the trailing parts of a manifest ledger, counted by
fsyncParts. Older filers read those parts as plain ids and still delete
them; a reload or a claimed foreign ledger restores the marks. A ledger
without marks keeps the single array form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: record a queued deletion before the delete loop can see it

queueDeletions published the ids to the hot queue before taking the
ledger lock, so a concurrent flush could delete an id before its fsync
mark landed and then forget the mark with the record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: fsync a folder delete's chunks by each child's path rule

A recursive delete collected its file children's chunks and resolved
the rule once for the folder, which misses a trailing-slash rule on
the folder itself and file-prefix rules. Each file child's own rule now
decides fsync; the folder rule still decides chunk deletion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a newer fsync request when a plain delete finishes

An id re-queued with fsync while a plain delete of it was in flight
lost its mark when that delete succeeded, so the queued copy also ran
without fsync. A plain attempt now leaves a marked record for its
queued copy; a durable delete of an already-deleted needle still syncs
the tombstone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: delete a folder's plain child chunks without fsync

Children whose own rule turns fsync off were still deleted durably when
the folder's rule asked for fsync. Only the children marked by their
own rule now go out with fsync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: retry a durable chunk delete the volume server failed

A volume server rolls back a durable delete it cannot sync and answers
with a 5xx carrying the I/O error text, which the classifier took as
permanent, so the record and its fsync mark were dropped while the
needle stayed live. A 5xx answer to a durable delete is now retryable,
within the usual attempt limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:02:43 -08:00
Chris LuandClaude Opus 5.5 f88751c3ff s3api: evaluate request condition keys for STS sessions (#12762)
* s3api: build request condition keys in one helper

Split the keys ExtractConditionValuesFromRequest reads from the request
itself into RequestConditionValues, keeping aws:SourceIp and the
bucket-listing keys in the method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: evaluate request condition keys for STS sessions

The IAM integration context for STS and OIDC sessions carried only the
source IP, legacy user agent/referer keys and claims, so role and session
policy conditions on s3:x-amz-*, aws:SecureTransport, aws:CurrentTime,
s3:RequestObjectTag/* and the other request keys never matched: a Deny
on them never fired, and a negated Deny always did. Add the same request
keys the static identity path evaluates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: report SigV4 presigned requests as REST-QUERY-STRING

s3:authType recognized only SigV2 query authentication, so a policy
condition on REST-QUERY-STRING never matched a SigV4 presigned URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:01:32 -08:00
Chris LuandClaude Opus 5.5 2089abecf3 ci: cache Snowflake suite Maven deps and fall back to a Central mirror (#12763)
* ci: cache the Snowflake suite's Maven dependencies under their own key

setup-java's maven cache key hashes the repository pom.xml files, which
other Java workflows share. The Snowflake job restored that cache, which
lacks the suite's plugins and dependencies, and never saved its own because
the key already existed. Every run downloaded the whole suite dependency
tree from Maven Central and failed when Central answered 429.

Key the cache on run.sh, which pins the suite revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: fall back to Google's Maven Central mirror in the Snowflake job

A cold cache still resolves about 36 MB of plugins and dependencies, and
Maven gives up after three 429 retries within 30 s. Add the mirror as a
settings-profile repository; Maven tries it first and moves on to Central
for any artifact the mirror fails to serve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:00:41 -08:00
Carlos Leyva 6d0a6e0935 filer: mint read_auth for the data chunks behind manifest chunks (#12756)
* filer: mint read_auth for the data chunks behind manifest chunks

* filer: cover every chunk behind manifests in read_auth (data + nested), minted after resolution, and skip when read signing is off

* filer: pass the master client as manifest cache invalidator, and move the read_auth helpers below populateBatchReadAuth for the enterprise merge
2026-11-18 19:37:06 -08:00
Chris LuandClaude Opus 5.5 9b94f00325 test: mount pinned Iceberg jars into the Spark catalog tests (#12757)
* testutil: fetch pinned Maven Central jars with a mirror fallback

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: mount pinned Iceberg jars into the Spark catalog containers

Each test started a new Spark container that resolved the Iceberg runtime
and AWS bundle through Ivy from Maven Central, so a run downloaded them six
times and a single refused request left Spark retrying until the package
timed out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: cache the Iceberg jars for the Spark catalog tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* testutil: test the verified jar download

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: bound Maven jar downloads by one deadline shared across retries

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: give each Maven mirror attempt its own timeout within the download budget

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:35:54 -08:00
Chris LuandClaude Opus 5.5 d2a0002869 s3api: fix listing regressions from argument validation (empty continuation-token, V1 Prefix encoding) (#12760)
* s3api: accept an empty ListObjectsV2 continuation-token

An empty continuation-token lists from the start and is echoed back
empty, as S3 does; rejecting it broke s3-tests
test_bucket_listv2_continuationtoken_empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: leave the ListObjects V1 Prefix unencoded under encoding-type=url

S3 encodes the V1 Delimiter, markers and keys but echoes Prefix as sent,
and botocore, which always asks for url encoding, decodes the V1 Prefix
only for V2. Encoding it broke s3-tests test_bucket_list_prefix_unreadable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: use a codespell-clean key in the versions encoding test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: URL-encode a V1 Prefix that XML cannot carry

Leaving the V1 Prefix raw under encoding-type=url turned a control
character such as \x01 into U+FFFD in the response. Such a prefix is
URL-encoded again; prefixes that are valid XML text, including '\n',
stay as sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:34:57 -08:00
github-actions[bot] c01e87689e docs: regenerate star history chart 2026-11-19 02:58:55 +00:00
Chris LuandClaude Opus 5.5 7b4bdb77bb master: export writable volumes per disk and reset leader-only layout gauges on followers (#12751)
* master: export writable volumes per disk for each volume layout

The layout gauges only report how many volumes of a collection take
writes, not where they sit, so two writable volumes sharing one disk
cannot be seen or alerted on. The leader now exports
writable_volumes_per_disk with the layout labels plus data center, rack,
node and disk id, counting the replicas of the layout's writable volumes
on each disk (state=writable) and those of them that are crowded
(state=crowded). Series for disks that no longer hold a writable volume of
the layout, and for layouts that are gone, are deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: reset the leader-only layout gauges on followers

The layout writable, crowded, under-replicated and per-disk gauges are only
set by the leader, so a master that lost leadership kept exporting the
values of its last term indefinitely, and dashboards that aggregate over
masters could show numbers days old. A master that is not the leader now
clears them on each periodic pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: chart disks holding several writable volumes of a collection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: keep disks of different clusters apart in the per-disk panel

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:17:04 -08:00
Chris LuandClaude Opus 5.5 1fd5008d63 s3api: listing argument validation and encoding-type=url for versions, prefix and delimiter (#12753)
* s3api: reject an empty ListObjectsV2 continuation-token

AWS answers continuation-token= with 400 InvalidArgument ("The continuation
token provided is incorrect"); SeaweedFS listed from the start of the bucket.
No token this server issues is empty, and raw-key and base64: tokens keep
resuming as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: reject an encoding-type other than url on listings

AWS answers any encoding-type other than url with 400 InvalidArgument
("Invalid Encoding Method specified in Request") on ListObjects,
ListObjectsV2, ListObjectVersions, ListMultipartUploads and ListParts;
SeaweedFS ignored the value and listed unencoded keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: apply encoding-type=url to ListObjectVersions

The handler accepted encoding-type=url but returned raw keys. It now
URL-encodes Key in Version and DeleteMarker entries, CommonPrefixes, Prefix,
Delimiter, KeyMarker and NextKeyMarker with the urlPathEscape form ListObjects
uses, and echoes EncodingType.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: URL-encode Prefix and Delimiter in ListObjects responses

Under encoding-type=url, ListObjects and ListObjectsV2 encoded keys,
CommonPrefixes, markers and StartAfter but echoed Prefix and Delimiter raw,
so a client decoding them once corrupted a prefix holding '%' or '+'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:55:41 -08:00
646549eee1 volume growth: spread writable volumes of a layout over servers and disks (#12749)
* volume growth: spread writable volumes of a layout over servers and disks

Volume growth picked every server, and the volume server picked every disk,
independently: the server weighted by free slots, the disk by the lowest
total volume count. A grow request therefore stacks several writable volumes
of one collection on some disks while most disks get none (a Poisson spread:
with 160 replicas on 479 disks about 20 disks get two or three), and their
writes share those disks.

Data centers and racks are still picked weighted by free slots. Inside a
rack the server is now one of those holding the fewest writable volumes of
the layout per disk, weighted by free slots among them; this covers the main
server, same-rack replicas and replicas walked into other racks and data
centers. On the volume server the disk is the one with the fewest writable
volumes of the collection, then the lowest volume count as before.

A grow request registers each volume before placing the next, so a request
smaller than the number of disks lands on distinct disks.

Fixes #12746

* volume growth: scan the layout load once per grow request

Placing each volume rescanned all writable volumes of the layout under its
read lock. RecordAssign takes that lock exclusively on every assign, so with
thousands of writables (0.8 ms for 10000) every volume of a grow request
stalled assigns once more.

GrowByCountAndType now scans once and findAndGrow adds every volume it
creates to the counts. Per volume, placement costs about 130-160 us on 480
servers whatever the number of writables, against 120 us before the spread
change; the single scan is 0.17 ms for 2000 writables and 0.8 ms for 10000.

* volume growth: address review of the spread placement

- Count only disks that report volume slots in a server's load. An
  unavailable disk, or one low on space with no volumes, is still listed in
  DiskTags with no slots; counting it understated the load of a server with
  failed disks and piled volumes onto its remaining ones.
- On the volume server, judge a volume full by its .dat size, which the
  master compares with the limit, not by ContentSize.
- A server that refuses an allocation ranks last for the rest of the grow
  request, and the request retries the volume up to 3 times. The least
  loaded server is picked first deterministically, so without this one server
  that cannot fit a preallocated volume stopped the layout from growing.
- Scan the layout load after warmup, so a grow request issued right after a
  leader change sees the writable volumes the returning servers report.

* volume growth: keep the request-local placement load ahead of the request fields

The JSON request fields stay together at the end of VolumeGrowOption, and
the comment now says the load lives for the whole grow request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): place a new volume on the disk with the fewest writable volumes of its collection

Store::add_volume picked the disk with the most free slots, so the Rust
volume server ignored the collection spread rule the Go server now applies.
find_free_location ranks disks by the writable volumes of the collection
first (not read-only, .dat below the volume size limit), then by free slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume growth: leave a refusing server out of every placement tier

A server that refused an allocation only ranked last among the servers of
its rack, so the weighted data center and rack picks could still choose its
rack on every retry while other racks had room. It now offers no free slots
for the rest of the grow request, which takes its slots out of the rack and
data center weights too. If only refusing servers are left, they are tried
again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume growth: require the full same-rack count only in the main rack

The data center check asked every rack for SameRackCount+1 free servers,
but only the main rack holds the same-rack copies; each other rack takes one.
With a refused server left out of its rack, the check rejected a feasible
placement, the retry put the refused server back, and it was picked again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Konstantin Lebedev <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:51:13 -08:00
Chris LuandClaude Opus 5.5 9cd183b04f volume: fsync a needle delete that asks for it (#12736)
* volume: fsync a needle delete that asks for it

A delete now takes fsync like a write: the tombstone is synced before the
needle map drops the needle, and the .idx row before the delete is
acknowledged. A failed .dat sync takes the tombstone back off the .dat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: honor fsync=true on DELETE and forward it to replicas

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): fsync a needle delete that asks for it

Mirrors the Go volume server: DELETE with fsync=true flushes the tombstone
before the index drops the needle and the .idx before the ack, and a failed
.dat flush takes the tombstone back off the .dat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: let a durable delete through on a full volume

A queued delete hit the batch worker's volume size check, which a
tombstone append is exempt from inline, so fsync=true deletes failed once
the volume reached its hard limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: sync a durable delete of an already-deleted needle

An earlier delete without fsync may have dropped the needle with its
tombstone still unsynced, so the inline path syncs before acking anyway,
as the batch worker already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: refuse a batch request that races the worker stopping

stopWorker can close the batch channel between startWorker handing it out
and the send, which panicked. The request now falls back to the inline path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): sync a durable delete of an already-deleted needle

Mirrors the Go volume server: an earlier delete without fsync may have
dropped the needle with its tombstone still unsynced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): run a durable delete on a blocking thread

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: keep syncDelete's signature for existing callers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: refuse a write a delete cancelled before it appends

A write cancelled while still queued behind the volume locks used to
append, publish and then tombstone itself without a sync, after its
delete may already have been acknowledged as durable. A crash could
keep the row and lose the tombstone. Refuse it before the append.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): refuse a write a delete cancelled before it appends

Mirrors the Go change: a write cancelled while still queued behind the
volume locks no longer appends, publishes and tombstones itself without
a sync after its delete may already be durable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): drop the write guards for a durable delete's flushes

The durable delete held the write lease and the io write guard across
both fsyncs, so reads of the volume waited on them. Append and publish
the tombstone under the guards and flush with only the io read side, as
write_synced_run and the Go path already do. do_delete_request keeps its
signature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: stop taking writes when a durable delete fails to index

The needle map drops the needle before it appends the .idx row, so after
a failed append a durable retry found nothing to delete and acked, and a
later write could bury the unindexed tombstone so a reload brought the
needle back. Fence the volume the way a failed durable write does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): stop taking writes when a durable delete fails to index

Rust counterpart of the Go change: the needle map drops the needle
before it appends the .idx row, so a failed append left a durable retry
nothing to delete, and a later write could bury the unindexed tombstone.
publish_delete_request now fences the volume for a durable delete, as
publish_write does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: stop taking writes when any delete fails to index

A non-durable delete whose .idx append failed left the volume writable with
the needle already dropped from the map, so a later durable retry found
nothing to delete and acknowledged without the missing row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): stop taking writes when any delete fails to index

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: take the fsync flag on the existing delete functions

DeleteVolumeNeedle, deleteNeedle2 and syncDelete take fsync instead of
gaining *WithFsync variants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): take the fsync flag on the existing delete functions

delete_volume_needle and delete_needle take fsync instead of gaining
*_with_fsync variants; the durable path and the deletable checks fold
back into delete_needle, and the cancelled-write check mirrors Go's
isCancelledWrite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:18:29 -08:00
Chris LuandClaude Opus 5.5 23eef59417 test/s3: run the s3-listing-study listing tools and strategies in CI (#12750)
* test(s3): s3-listing-study integration suite (WIP)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3): run the s3-listing-study tools against SeaweedFS (WIP)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3): s3-listing-study deleted-prefix probe, fresh data dir per run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test(s3): listing study ports keep clear of every gRPC companion

free_ports.py compared only base ports, so a base port could land on
another server's base+10000 gRPC listener.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(s3): listing study ports stay below the ephemeral range

Base ports of 20000-55000 put both them and their gRPC companions inside
32768-60999, so an outgoing connection made while weed server starts could
take a port before the server that was given it binds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(s3): listing study checks the order inside each listing page

parse_page sorted Contents and CommonPrefixes together before the probes
compared them, so keys returned out of order within one page passed. Check
each list's byte order first; the versions pager does the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(s3): listing study applies --only before running a probe

The filter was applied to the probe results, so a run limited to one tool
still sent every reference listing request and the deleted-prefix check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(s3): listing study requires CommonPrefixes from shallow modes

The CommonPrefixes comparison ran only when a tool returned at least one
prefix, so a delimiter listing of the canary root that came back empty
passed. Compare them for every shallow mode except the two whose
normalizer keeps keys only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:17:25 -08:00
Chris LuandClaude Opus 5.5 04c7b12238 s3api: reject unknown notification elements; fail test-with-server on a stuck shutdown (#12752)
* s3api: reject unknown elements in PutBucketNotificationConfiguration

xml.Unmarshal skips children that match no field, so a configuration
whose only child was an unmapped element parsed as empty and returned
success while nothing was stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: fail test-with-server when the server does not stop

A passing suite returned success even when stop-server gave up with the
server still running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:15:38 -08:00
Chris LuandClaude Opus 5.5 f5418845ce test/s3: run tigrisdata-community s3-api-compat-tests in CI (#12741)
* test/s3: run tigrisdata-community s3-api-compat-tests in CI

Runs the suite, pinned to a commit, against weed mini through a small
provider patch, and fails on any test that is not in
expected_failures.txt or on a listed test that starts passing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/s3/tigris_compat: prepare the suite again when the patch changes

The checkout was reused whenever it sat at the pinned commit, so an
edited seaweedfs-provider.patch, or a checkout whose patch failed to
apply, kept being built as it was. Record the commit and the patch's
hash once the patch applies, and prepare the checkout again when either
differs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: keep the pid file of a server already running

start-server removed weed-server.pid before it found the port taken, so
a second start lost the pid of the server holding it and stop-server
could no longer stop that one. Remove the file only once the port is
free, and have test-with-server stop only a server it started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: bound the S3 port probes

A listener that accepts but never answers held curl, and with it the
readiness loop and the cleanup after it, for good. Give each probe two
seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: expect a listed test to end with its listed status

A listed test passed the check with any non-pass status, so a setup error
that skipped the call under test (RestoreObject's PutObject, say) went
unnoticed. Entries now expect fail unless they name another status; only
GetBucketAccelerateConfiguration, whose setup PUT is unsupported, expects
error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: refuse to start while the recorded server still runs

A second start-server before the first server answered on the S3 port
passed the port probe and dropped the pid file of the live server, so
stop-server could no longer stop it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: recognize the test server by its command line

start-server and stop-server took any process named weed at the recorded
pid for the test server, so a weed process that reused the pid would be
reported as running and killed by stop-server. Match the command line
start-server launches instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: recognize the test server by its start time

A weed mini started from another checkout has the same command line, so
a pid it reused still matched. Record the process start time next to the
pid at launch and require both before treating the process as the test
server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: PutObjectTagging_VersionId passes now

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: keep the server records until the server exits

stop-server waited a fixed two seconds after SIGTERM and then removed
weed-server.pid and weed-server.started even if weed was still shutting
down, so a later stop-server could not find it and clean could delete
data it still used. Wait up to 30 seconds for the recorded server to exit
and keep the records, failing, while it still runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: start the server on an empty data directory

A data directory left by an earlier run on other ports made the master
freeze volume growth (topology id mismatch), and every PutObject failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:14:52 -08:00
Chris LuandClaude Opus 5.5 53bc62c773 s3api: accept the accelerate and notification configurations the bucket already reports (#12747)
* test/s3: run tigrisdata-community s3-api-compat-tests in CI

Runs the suite, pinned to a commit, against weed mini through a small
provider patch, and fails on any test that is not in
expected_failures.txt or on a listed test that starts passing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/s3/tigris_compat: prepare the suite again when the patch changes

The checkout was reused whenever it sat at the pinned commit, so an
edited seaweedfs-provider.patch, or a checkout whose patch failed to
apply, kept being built as it was. Record the commit and the patch's
hash once the patch applies, and prepare the checkout again when either
differs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: keep the pid file of a server already running

start-server removed weed-server.pid before it found the port taken, so
a second start lost the pid of the server holding it and stop-server
could no longer stop that one. Remove the file only once the port is
free, and have test-with-server stop only a server it started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: bound the S3 port probes

A listener that accepts but never answers held curl, and with it the
readiness loop and the cleanup after it, for good. Give each probe two
seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: accept PutBucketAccelerateConfiguration with Status=Suspended

GetBucketAccelerateConfiguration always reports Suspended, but the PUT
answered 501 for every request. Suspended is now accepted, Enabled
stays NotImplemented, and the accelerate subresource resolves to
s3:GetAccelerateConfiguration / s3:PutAccelerateConfiguration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: accept an empty PutBucketNotificationConfiguration

GetBucketNotificationConfiguration always reports an empty
configuration, but the PUT answered 501, including for the empty
configuration clients send to clear notifications. An empty one is now
accepted; a topic, queue, Lambda or EventBridge destination stays
NotImplemented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: reject accelerate and notification bodies with the wrong root

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/s3/tigris_compat: expect a listed test to end with its listed status

A listed test passed the check with any non-pass status, so a setup error
that skipped the call under test (RestoreObject's PutObject, say) went
unnoticed. Entries now expect fail unless they name another status; only
GetBucketAccelerateConfiguration, whose setup PUT is unsupported, expects
error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: refuse to start while the recorded server still runs

A second start-server before the first server answered on the S3 port
passed the port probe and dropped the pid file of the live server, so
stop-server could no longer stop it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: recognize the test server by its command line

start-server and stop-server took any process named weed at the recorded
pid for the test server, so a weed process that reused the pid would be
reported as running and killed by stop-server. Match the command line
start-server launches instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: recognize the test server by its start time

A weed mini started from another checkout has the same command line, so
a pid it reused still matched. Record the process start time next to the
pid at launch and require both before treating the process as the test
server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: PutObjectTagging_VersionId passes now

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: keep the server records until the server exits

stop-server waited a fixed two seconds after SIGTERM and then removed
weed-server.pid and weed-server.started even if weed was still shutting
down, so a later stop-server could not find it and clean could delete
data it still used. Wait up to 30 seconds for the recorded server to exit
and keep the records, failing, while it still runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test/s3/tigris_compat: start the server on an empty data directory

A data directory left by an earlier run on other ports made the master
freeze volume growth (topology id mismatch), and every PutObject failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:55:18 -08:00
Chris LuandClaude Opus 5.5 1f5cfc7552 s3api: return x-amz-version-id from object tagging on versioned buckets (#12745)
* s3api: return x-amz-version-id from object tagging on versioned buckets

PutObjectTagging, GetObjectTagging and DeleteObjectTagging now report
the version they acted on, "null" for an object written before
versioning was enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: set the tagging x-amz-version-id only on success

The header was set before the tag-conditioned policy recheck, so a
denied request carried the version id on its AccessDenied response.
Also test the "null" version and require distinct version ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:30:55 -08:00
Chris LuandClaude Opus 5.5 b1c315b837 s3api: report no ownership controls after DeleteBucketOwnershipControls (#12748)
* test/s3: run tigrisdata-community s3-api-compat-tests in CI

Runs the suite, pinned to a commit, against weed mini through a small
provider patch, and fails on any test that is not in
expected_failures.txt or on a listed test that starts passing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: report no ownership controls after DeleteBucketOwnershipControls

GetBucketOwnershipControls reports BucketOwnerEnforced for a bucket that
never stored a setting, so it kept reporting it after the setting was
deleted. The delete now records that it happened, and GET answers
OwnershipControlsNotFoundError until ownership is put again. How
objects are written after the delete is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3api: answer DeleteBucketOwnershipControls with 204 No Content

AWS answers a successful DeleteBucketOwnershipControls with 204 and no
body; this answered 200 with an empty OwnershipControls document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:25:15 -08:00
aceb089bc8 lance: per-table cleanup retention and on-demand purge of deleted rows (#12739)
* lance: per-table cleanup retention and on-demand purge of deleted rows

A vector deleted from an index stayed in storage until compaction
rewrote its fragment (only above 10% deletions) and the cleanup job's
168 h retention, set once per worker, aged out every version that
referenced it.

Let a table override retain_hours and min_versions in its Lance config
(seaweedfs.cleanup.retain_hours, seaweedfs.cleanup.min_versions), and
let it request a purge (seaweedfs.purge.requested). The cleanup job
proposes a table with a pending purge regardless of the version floor
and then rewrites every fragment with deletions, retrains the indices
(a remapped IVF_FLAT index still holds the deleted vector), keeps only
the latest version, and records the request as served. A version pinned
by a tag fails the purge and leaves the request pending.

The test scans every file of a local table for a deleted vector's key,
metadata and values, and finds none after the purge.

* lance: refuse to purge a sharded vector index

A retrain builds every index name over the whole table, so the purge
turned shards of one vector index (one name per fragment set) into
names that each covered every fragment, indexing every row once per
shard. Check before compacting and fail with the request left pending,
and retrain only the vector indices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance: rebuild scalar indices in a purge

Compaction only remaps scalar indices, and a retrain leaves them alone,
so a purge reported success while a bitmap index still listed the
deleted row's value, and under stable row ids a BTree index still held
the deleted key. Build each scalar index again from the remaining rows
with the parameters it was built with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance: purge through the cleanup job's retention policy

The purge built its own cleanup policy, so a deployment that has the
cleanup job keep more than the floor and the window (versions an
unleased reader may still be on) would have lost them to a purge. Clean
up through retention_policy, the one the job itself uses, with the
latest version kept.

Mark the request served only once the oldest version left is one the
rebuild wrote, and record the rebuild so a purge that has to wait for
its cleanup (a tag, or that policy) retries only the cleanup instead of
compacting and retraining the indices on every pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* vector: lease the version every list page reads

A list page read its version without a lease unless it was a segment
that read data and metadata twice. A purge removes every version but
the latest, and only a lease tag stops it, so a listing that opened the
version before the purge's compaction could lose its files mid-read.
Pin it as get_vectors and query_vectors do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lance: give the cleanup job a build's execution time

A purge compacts the table and retrains its indices inside a cleanup
job, but the job declared no runtime defaults, so the admin held it to
its 90 s default and could expire a purge mid-rebuild. Declare the same
budget the indices job uses for a retrain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:24:28 -08:00
c7d8b106d5 mount: follow a peer unlink to the surviving hard link for closed inodes (#12737)
* mount: drop a peer-unlinked name only while its inode keeps another

Move the survivor check from followSurvivingLink into InodeToPath.RemoveAlias
so the check and the removal happen under one table lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: follow a peer unlink to the surviving hard link for closed inodes

A peer deleting one name of a hard link only moved an open handle to the
surviving name. A closed inode kept the deleted name as its primary path, so
the next open by the kernel's nodeid failed with ENOENT.

Co-authored-by: skymazer <54621405+skymazer@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: share the cached-entry freshness check of peer invalidations

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a name a local rename reclaimed before the peer unlink arrived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a name a local rename or link gave the inode after an older peer delete

The cached-entry check only covers a cached parent. InodeToPath now records,
per hard-linked inode, the newest name a local rename or link gave it with
the filer stamp, and the closed-inode peer-delete path keeps that name when
the delete is older. The record lives in a side map dropped on Forget, so
InodeEntry keeps its size class.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: sign rename stream responses with the filer signature

A rename response carries the stamp of the filer that applied it, so the mount
can tell which clock the stamp belongs to, as it does for create acks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: order a peer delete against a local rename or link only on one filer clock

The stamp of a local rename or link comes from the filer that applied it, and
a delete logged by another filer runs on a different clock. Keep the name only
when both carry the same nonzero filer signature; otherwise drop it as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop the local-name stamp fence for uncached parents

Ordering a delayed peer delete against a local rename by filer stamp needs a
record per alias, a shared filer clock, and the open-handle path to follow;
that is a larger change than this fix. Back to the cached-entry check, which
covers a cached parent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: skymazer <54621405+skymazer@users.noreply.github.com>
2026-11-18 14:13:40 -08:00
a3b2fd722d mount: report opens for reading with TouchAccessTime (-accessReport) (#12721)
* mount: report opens for reading with TouchAccessTime (-accessReport)

An open answered from the metadata cache never reaches the filer, so a
filer that tracks access cannot see that a cached file is still being
read. With -accessReport, the mount sends one TouchAccessTime per open
for reading, with the open time, whether the open was answered from the
cache or not. Write-only opens are not reported.

Reports go out in the background and never hold up the open: a report
that does not fit in the queue is dropped, and drops and failures are
logged once a minute. A filer that answers Unimplemented pauses
reporting for 10 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: address review of the access report

- Drop reports still queued when reporting pauses; the filer that answered
  Unimplemented would answer them the same way.
- Bound each filer attempt to 2s, so a filer that accepts the connection
  but never answers leaves time for the next one, and keep using the filer
  that answered.
- Fail over only when a filer cannot be reached. Any answer, Unimplemented
  included, ends the walk.
- Report an O_CREAT open of an existing file with read access, which comes
  through Create instead of Open. A new file has nothing to read and is not
  reported.
- Stop the reporter on unmount: stop ends the workers and cancels the
  report in flight.
- Say in the flag help that it has no effect unless the filer implements
  TouchAccessTime.
- Tests no longer wait a fixed time to see that nothing else was sent; they
  look at the queue of a reporter that is not started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fail an access report over only when the filer did not answer

A status the filer sent ends the walk even when its message contains a
word the transient classifier matches, so an Unimplemented answer still
pauses reporting and a rejected request is not resent elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a filer selection made while an access report failed over

A report that reached a later filer moves the mount there only if the
selection it started from is still current, so a slower report cannot
undo another call's failover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: share an access report's time with the filers not yet tried

Each attempt is capped by an equal share of the report time left, so a
row of stalled filers cannot use up the report before a healthy one later
in the list is tried.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: report the path an open for reading came through

A create that opens an existing hard link reports the name it was
given rather than the inode's first known name. Open reads the inode's
path from the inode table rather than the handle's saved path, which
other handle operations may rewrite concurrently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check the access report stop and failover tests without races

The post-stop report is checked on a reporter without workers, so no
worker can take an accepted report before the check, and the failover
test asserts that the stalled filer was tried first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: keep the shared channel when the peer answers with its own status

gRPC never raises InvalidArgument, NotFound, AlreadyExists,
FailedPrecondition, OutOfRange or DataLoss itself, so such a status is
the peer's answer. It fell through to the string matching, and a message
naming a path like /transport closed the cached channel and cancelled
every other call on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: say which filer selection an access report keeps

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: bound the in-flight call in the rejected-report channel test

The call held in flight went through touchAccessTime, whose 2 s attempt
cap could expire on a slow runner and fail the test on a healthy channel.
It now uses callFiler with the test deadline. The wait for it to reach
the filer also ends if it returns early or the deadline passes, and the
blocked handler is released on every exit path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: report each file at most once per -accessReport.interval

Every read open used to send a TouchAccessTime, adding a filer metadata
call per open. A path reported within the interval (default 1h) is now
skipped; the last report times live in a bounded LRU. 0 keeps reporting
every open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: report an open again once the file was modified since its last report

Within -accessReport.interval a read open was skipped even after a write,
so the filer kept an atime older than the mtime until the interval ran
out. relatime records that first read after a write; do the same by
comparing the entry's mtime with the last report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep the report time apart from the mtime it saw

Recording max(now, mtime) as the last report let a file dated a day ahead
suppress reports for a day plus the interval. Record when the report was
sent and the mtime the entry had, and treat any change of that mtime as a
modification, so neither clock can stretch or shorten the interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-18 14:11:11 -08:00
Chris LuandClaude Opus 5.5 9f413ff2c8 shell: volume.check.disk skips replicas whose live counts match (#12743)
* shell: volume.check.disk skips replicas whose live counts match

FileCount counts every write and DeleteCount every delete or overwrite
until a vacuum drops them, so a replica vacuumed while its peer was not
keeps a different FileCount forever and was re-checked on every run
although both hold the same live needles. Only treat counts as differing
when the live counts (FileCount - DeleteCount) differ too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.check.disk skips equal live counts only across compaction revisions

Equal live counts at the same compaction revision mean a missed write
and a missed delete, not a vacuum-state difference, so keep checking
those pairs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.check.disk real-time recheck ignores heartbeat revisions

VolumeStatus counts are newer than the heartbeat's compaction revisions,
so a vacuum in between could make a pair at the same revision look
vacuum-skewed. Apply the old count rules there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: volume.check.disk skips on live counts only when no repair could follow

Equal live counts across compaction revisions can still hide a missed
write and a missed delete. Keep checking such pairs when -syncDeleted
could propagate the delete, or when -resurrectMissingNeedles could copy
a needle into a never-vacuumed replica.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:10:47 -08:00
e037a9c1ce s3vectors: enforce AWS metadata, key and filter limits (#12738)
* s3vectors: enforce AWS metadata, key and filter limits

PutVectors accepted vector metadata of any size and key count, bounded
only by the request body limit, and keys of any length; QueryVectors
accepted filters of any size. Apply the AWS S3 Vectors limits
(https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-vectors-limitations.html),
taking the ENHANCED index values where the modes differ, since this
implementation prefilters and takes no indexMode:

- 100 KB total metadata per vector, which also bounds a single
  non-filterable field;
- 2 KB filterable metadata per vector;
- 50 metadata keys per vector;
- 1024-character vector keys;
- at most 10 nonFilterableMetadataKeys of 1 to 63 characters at
  CreateIndex;
- 100 filter constraints per QueryVectors request.

A violation is a ValidationException before the engine is called.

* s3vectors: accept metadata whose JSON is exactly at the byte limits

metadataEntrySize counts a trailing comma for every member, so starting
from both braces overcounted by one and rejected metadata that encodes to
exactly 2 KB filterable or 100 KB total.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3vectors: rewrap the metadata limits header comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:49:15 -08:00
Denis 3db54ee7e5 kms/openbao: refresh the AppRole token before it expires (#12734)
* kms/openbao: refresh the AppRole token before it expires

The provider logged in with AppRole once, when it was created, and
never renewed the token. After the token's TTL every SSE-KMS upload,
and every read of an SSE-KMS object whose data key was not cached,
failed with "permission denied" (HTTP 500 to the client) until the S3
server was restarted.

With AppRole authentication the provider now logs in again in the
background once two thirds of the token's TTL have passed, and retries
a failed login every 5 s. Each login is bounded by the client's
timeout, or by 30 s when request_timeout is not positive. Close stops
the refresh. A static token, or an AppRole token without a TTL, is left
as it is.

* kms: keep the OpenBao token refresh across configuration reloads

- AddKMSProvider and InitializeGlobalKMS create a provider instance of
  their own with the new NewProvider instead of the registry's cached
  one: a reload closed the cached instance and then got it back, which
  now stopped its token refresh. The new instance is created before the
  old one is closed, so a configuration that fails leaves the current
  provider working
- openbao: time each refresh from the start of the login that issued
  the token, since its TTL runs from then rather than from the response
- tests: a reload gives a new instance and closes the old one, a failed
  reload keeps the old one; the refresh survives a reload; a slow login
  response

* kms: create a replacement provider outside the manager lock

AddKMSProvider ran the provider factory, which for OpenBao is a login
that may wait for its timeout, while holding the manager lock, so every
lookup, also of unrelated providers, waited for it. The new provider is
now created before the lock is taken; the lock covers only the swap, and
the replaced provider is closed after it. Test: a lookup while another
provider is being created.
2026-11-18 11:07:09 -08:00
Chris LuandClaude Opus 5.5 94de65b3b5 s3api: answer a malformed Cache-Control on PutObject with InvalidRequest (#12733)
PutObject rejected a Cache-Control value it could not parse with
InvalidDigest, whose message is about Content-MD5, even when the request
sent no Content-MD5. CreateMultipartUpload already answers the same parse
error with InvalidRequest; PutObject now does too.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:03:57 -08:00
ebc77400ca operation: reassign an upload after a proven-expired volume JWT (#12729)
* operation: reassign an upload after a proven-expired volume JWT

* seaweed-volume: mark an expired write JWT refused before append

Mirror the Go volume server: a multipart POST whose write JWT is signed
with the current key, names this fid and fails only on exp gets
X-Seaweed-Write-Outcome: expired-jwt-before-append on its 401, so the
uploader reassigns instead of failing. Both checks use one guard
snapshot, so a key rotation between them cannot drop the marker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* operation: keep same-FID retry for filer-proxy expiries, snapshot the write signing key, and make the RetryForever budget test fail fast

* operation: re-mint the filer credential before a proxy same-FID expiry retry

* operation: make a proxy marked-expiry terminal in the outer retry too, not only the inner same-FID loop

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:02:52 -08:00
Chris LuandClaude Opus 5.5 ecbf7af1ca mount: compare permissions against local ids without mapping them again (#12726)
* mount: compare permissions against local ids without mapping them again

Access, open and create (without -defaultPermissions) ran FilerToLocal on
entries that maybeReadEntry and maybeLoadEntry already return in local ids.
Under a uid/gid map where a local id is also a mapped filer id, the owner
was mapped twice and the check refused the file's own owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: cache a deferred create's placeholder in filer ids

The meta cache stores filer uid/gid and maps them to local ids on every
read, but createRegularFile cached the deferred or writeback placeholder
with the caller's local ids. The second mapping in the permission checks
used to cancel that out under a swapping id map; without it the owner of
a placeholder was refused. Cache a mapped clone and keep the handle's
entry in local ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test that a deferred create returns its entry in local ids

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:01:30 -08:00
b64895ed0a filer: stop following a peer that stays unreachable (#12725)
* filer: stop following a peer that stays unreachable

* filer: re-track an answering peer only while it is still followed

A signature read that succeeds just before the master removes the peer
called initPeerWatermark after the removal, clearing its mark. The loop
then exits, so the watermark it re-tracked never advances or drops and
pins aggregated readers at the settled horizon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: forget a peer's unreachable clock when the master removes it

Only a successful connection cleared the clock, so every departed address
that once failed stayed in the map for the filer's lifetime, and a re-added
peer inherited the old outage. The removal now drops it, and the clock is
guarded by peerChansLock so the removed peer's exiting loop cannot start a
new one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: report the unreachable mark only when it is set

Once peerResumeRetention forgets the mark of a peer that stays
unreachable, markPeerWatermarkRemoved no longer marks it (its watermarks
are gone), but notePeerUnreachable still saw no mark and logged
"treating it as removed" on every retry. markPeerWatermarkRemoved now
reports whether it set a new mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: fix the unreachable-peer subscriber's start before the baseline write

The subscriber goroutine picked its start time itself, so a baseline write
that finished first fell before the subscription and the test failed after
20 seconds with correct delivery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:00:15 -08:00
72ac9e96b2 mount: answer an interrupted read with EINTR, not EIO (#12723)
* mount: answer an interrupted read with EINTR, not EIO

The kernel's FUSE contract (Documentation/filesystems/fuse/fuse.rst,
"Interrupting filesystem operations") lets a filesystem either ignore an
INTERRUPT or honor it by replying EINTR to the original request. Read did
neither: the FUSE cancel channel cancels the read's context, the chunk
fetch fails with "context canceled", and every error became EIO.

Interrupts come from any signal the reader handles. Go's runtime sends
SIGURG for goroutine preemption, so Go programs reading under load hit
this on healthy data: on a 128-thread 64 KiB random-read test about 250
of 5 million reads failed with EIO, and none with GODEBUG=asyncpreemptoff=1.

Read now returns EINTR when its own context was cancelled, the way
dirReadStatus already does for directory reads and lookups do since
#11717. Go's os.File retries EINTR, so those readers see no error. A
cancelled read also skips the entry refresh retry, and neither read log
line reports an interrupt as a warning or error. Failures without an
interrupt stay EIO.

Tests: TestReadInterruptedReturnsEINTR (fails on the old code with EIO),
TestReadFailureWithoutInterruptReturnsEIO; weed/mount/... passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: require the failed-read test to reach the filer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: skip the read retry once the request is interrupted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-18 10:58:05 -08:00
11af0e0c12 mount: move an open file's read view to the chunks a merge wrote (#12722)
* mount: move an open file's read view to the chunks a merge wrote

When a flush finds that a file's chunks take more than twice its size,
maybeMergeChunks reads the file back and writes it again as new chunks.
The commit that publishes them makes the filer delete the chunks they
replaced. The flush put the new chunks into the handle's entry but left
its read view on the old ones, so every descriptor that kept the file
open went on reading the replaced chunks. Those read back until their
volume is vacuumed. After that a read first retries the fetch of the
missing needle for about 13 s; then refreshEntryForRead installs the
filer's entry and the read is retried. The refresh skips a handle with
writes it has not flushed, and such a read returns EIO instead.

Files that are kept open and rewritten in place, such as PostgreSQL
data files and SQLite databases, are the ones whose chunks bloat, so
they are the ones that hit this.

installRewrittenChunks puts the merge's chunks into the entry and the
read view together, under the entry lock. Chunks attached while the
merge ran were not part of it and stay. Flushes without a merge are
unchanged.

TestMergeMovesReadViewOffReplacedChunks covers the handle.
TestReadOpenHandleAfterChunkMerge runs it on a real mount, with and
without an unflushed write; for it, the fuse_integration framework
starts mini on a free master port and exposes the address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drain uploads before a merge replaces the chunks

Uploads attach their chunks without the handle lock, first to the entry
and then to the read view, and writes that landed after doFlush drained
the pages may still be uploading when the flush takes its lock. An
upload that attached during the merge could keep a chunk older than
data the merge already holds, or put a chunk the merge replaced back
into the read view. Either outranks the merge's zero-timestamp chunk.

When the chunks are bloated enough to merge, the flush now drains the
pages again while its lock holds writes off, and takes the chunks again.
FlushAll returns only after every upload has attached to both the entry
and the read view, so nothing attaches during the merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: leave a pre-merge upload failure to the next flush

The drain before a merge returned an upload failure through the
metadata flush. doFlush then retried it as a filer error and answered
EIO, where the page flush answers a full disk with ENOSPC. The drain is
there only to wait for the uploads: a failure stays with the pages, and
the next flush reports it as a write error, as it would without a merge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep chunks attached while a flush installs its compacted list

A write that lands after doFlush drained the pages can still be uploading
when flushMetadataToFiler takes its chunk snapshot. Its upload attaches the
chunk without the handle lock, and the plain flush then replaced the
entry's chunks with the list compacted from the snapshot, dropping it from
the handle and from every later commit. Keep chunks attached after the
snapshot, as the merge path already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fail a merge's flush on a failed drain

A failed upload found by the drain before a merge was only logged, and
the flush went on to publish a size covering bytes that no chunk stores.
It now fails the flush as a pageUploadError before anything is
published; doFlush maps it with writeErrorToFuseStatus, as it does its
own FlushData failure, and does not retry it as a filer error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: clone a flush's request entry under the entry lock

The request snapshot cloned the live entry after GetEntry had released
its read lock. Uploads attach chunks without the handle lock, so an
AppendChunks that landed during the clone raced it on the Chunks field.
Clone inside UpdateEntry, as content flush recovery does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: leave a merge to a later flush while uploads are pending

Before a merge the flush drained the pages while it held the handle and
publication locks. A writeback upload retries a transient storage error
until it succeeds, so that drain could hold both locks for as long as
storage stayed down, stalling reads, writes and stat on the handle.
The flush now checks for pending uploads and, if any, publishes the
compacted chunks and leaves the merge to a later flush. With none
pending the lock still holds writes off, so nothing attaches during the
merge, and a failed upload still fails the flush as a write error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep room for pending uploads when a flush merges onto a moved entry

A flush that leaves the chunk merge to a later flush publishes while
uploads are still pending, and writes that landed after the drain can be
uploading on any flush. Merging a peer's inline content or a shrink into
such a publication lets the upload attach its chunk next to the inline
bytes, where reads never reach it. Tell createContentEntry when uploads
are pending so the merge keeps room for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test chunk merges through the filer's chunk proxy, also under load

The tests serve the filer's chunk proxy, and like the filer the fake
deletes the chunks each commit replaces, so a read view still naming
them fails:
- TestFlushMergeThroughChunkProxy/Quiet: the flush merges, and reads
  through the open handle return the file from the merged chunk alone.
- TestFlushMergeThroughChunkProxy/UploadInFlight: an older page is still
  uploading while a newer page of the same bytes has attached. The flush
  leaves the merge, reads return the newer page, and the next flush
  merges.
- TestFlushMergeRacesWithWritesAndReads: four writers, three flushers
  and a reader on one handle, with uploads delayed at random. The
  writers pause now and then, so 14 to 18 flushes a run merge and the
  others leave the merge to a later one. Every read must succeed within
  2 s, and at the end the handle and the filer must both hold exactly
  what was written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: let a held upload go when UploadInFlight fails

The subtest's proxy holds the older page's upload until the test
releases it, and only the passing path did. A failure in between left
the handler blocked, so the proxy's cleanup waited on it and the failure
surfaced as a suite timeout. Release it from a cleanup as well, once,
and bound the waits for the upload and the drains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-18 10:51:31 -08:00
de5b3305a7 mount: ask the filer again when a deferred create is published mid-lookup (#12720)
* mount: ask the filer again when a deferred create is published mid-lookup

A program that writes a file under a temporary name and renames it while
the file is still open (safetensors save_file does, through Rust
tempfile's persist) looks the temporary name up before the rename. When
the parent directory's listing is not cached, that lookup goes to the
filer. If a FLUSH publishes the deferred create while the lookup is in
flight (a forked child closing its inherited descriptor sends one), the
filer can answer not-found from a read taken before the create
committed. By the time the answer arrives the flush has cleared the
handle's dirty flag, so lookupEntry finds nothing local to explain the
answer, logs "possible coherence bug" and returns ENOENT, and the rename
fails although the file exists.

Note before sending the request whether the inode had unpublished
metadata (a dirty handle or an async flush in flight). On not-found, if
it had and has since been published, ask the filer once more: the filer
acknowledged the publish before the second request is sent. A second
not-found stands, so a file another mount removed is not brought back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: judge a placeholder's not-found by one look at its base

Review of the previous commit found two problems. The retry check and the
not-found fallback read the handle separately, so a flush that finished
between the two reads still turned the answer into ENOENT. And the
pre-request read of dirtyMetadata, a plain bool that Write and the flush
set under the handle lock, raced with them on every lookup that reached
the filer.

Note instead whether the handle is a local placeholder: a deferred create
has no filer base (baseEntry) until a flush publishes it. A not-found for
a placeholder is judged by one atomic look at that base. With none, the
filer cannot have the file yet and the handle answers. With a base, the
filer acknowledged the publish, so ask once more. dirtyMetadata is not
read for this, and the not-found fallback keeps the existing check, with
the placeholder decision added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: answer a placeholder from its own handle; a second miss is final

Follow-ups from review of the previous commit:

- Pick the placeholder after the async-flush wait, from the path's
  current mapping.
- A placeholder that still has no base answers from the observed handle
  itself, instead of through the not-found fallback, which re-resolved
  the path and could miss once the handle was released and the cache
  entry evicted.
- A not-found from the second request is final. The flush installs the
  base before it clears dirtyMetadata, and keeps it set when a write
  landed meanwhile, so the fallback could return a file another mount had
  removed.
- Test gates release on cleanup, so a failing test leaves no handler
  blocked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: read a placeholder's entry the way GetAttr does

The previous commit answered a not-found for a placeholder from the
handle's live entry under entryLock. Neither of the entry's writers takes
that lock: Write and the metadata flush change size, times and chunks
under the handle lock, and async upload workers append chunks under the
LockedEntry lock, so the lookup could read an entry while it changed.

Answer with the copy the create cached when it is still this file's
(same inode), as the not-found fallback already prefers. Otherwise copy
the handle's entry under both writers' locks, in GetAttr's order (handle
lock shared, then the LockedEntry lock), and convert the copy. No caller
of lookupEntry holds a handle lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: cache a deferred create's placeholder in filer ids

The meta cache stores filer uid/gid and maps them to local ids on every
read, but createRegularFile cached the placeholder with the caller's local
ids. Under a uid/gid map whose local id is also a mapped filer id, a lookup
or stat answered from the placeholder reported the wrong owner. Cache a
mapped clone and keep the handle's entry in local ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: assert the placeholder is cached before checking its owner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check the snapshot owner after evicting the cached placeholder

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-18 10:50:28 -08:00
04e135c21e fix(helm): separate volume DNS discovery from ingress traffic (#12719)
* helm: set publishNotReadyAddresses on the volume headless service

* fix(helm): separate volume DNS discovery from ingress traffic

* test(helm): cover volume DNS discovery and ingress routing

* fix(helm): rename the volume routing Service so volumes.client cannot collide

* docs(helm): name the ready-only Service for explicit volume backendRefs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(helm): fail when the volume routing Service name collides after truncation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(helm): point explicit volume backendRefs at the rendered client-volume name

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:49:35 -08:00
Chris LuandClaude Opus 5.5 862913d199 volume, ec_balance: clean up failed EC shard copies; stop re-proposing empty-index volumes (#12718)
* volume: remove files a failed VolumeEcShardsCopy wrote

The shard files were copied before the .ecx, so a source holding a
0-byte index failed the request only after its shards had landed, and
nothing removed them: every retried move stranded another unmounted
shard on a new disk.

Copy the .ecx first, staged beside its target, so a bad index fails
before any shard lands; rename it into place only after the shards and
sidecars have copied, so a failed copy never truncates or replaces an
.ecx the destination already has. On any error, remove exactly the
files this call created; files already on the disk (an existing
holder's shards, index or journal) are left alone. Go and Rust volume
servers behave the same.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* ec_balance: skip EC volumes whose every holder reports an empty .ecx

A shard copy refuses a 0-byte .ecx, so detection proposed the same
failing move of such a volume every cycle. Leave volumes with no
holder reporting a needle out of planning; their shards still count
toward disk occupancy.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* volume: serialize VolumeEcShardsCopy per volume

Overlapping copies of one vid shared the staged .ecx, and a failed copy's
cleanup removed shards that a concurrent copy had already committed and
mounted. Hold a per-vid EC lifecycle lock across the whole copy and its
cleanup, named as in the enterprise build (Store.EcLifecycleLock /
ec_lifecycle_lock).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: overwrite an existing .ecx in place when committing a copied index

A mounted EcVolume reads its index through an open handle, so renaming
the staged copy over it left the reader on the replaced inode: tombstones
the source had folded into its .ecx never reached the mounted holder.
An index already on the disk is now overwritten in place, as before the
staging change; a fresh destination still gets the rename. Go and Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: stage replacements of shards a VolumeEcShardsCopy finds on disk

The shard transfer opened an existing destination shard with O_TRUNC and
removed it on a stream or write error, so a failed retry deleted a shard
this disk already held. A shard already present is now copied to
<shard>.copying and renamed into place only after every other file has
copied; a mounted copy is reopened so it serves the new file. Fresh
shards still write in place and are removed on failure. Go and Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: stage the .vif and .ecsum a VolumeEcShardsCopy brings until commit

The sidecars landed as soon as they transferred, ahead of the deferred
.ecx commit, so a failure after them left a new .vif beside the index
the failed copy kept. They are now staged as .copying and renamed into
place with the shards and index once every transfer has succeeded; a
source without one still stages nothing. Go and Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: run a Rust VolumeEcShardsCopy to completion when its caller goes away

tonic drops a cancelled handler future at its current await, which
released the EC lifecycle lock while file operations the copy had started
(a cleanup remove_file on the blocking pool, a create or rename) could
still land; a retry taking the lock could then lose its files to them.
The copy now runs in a spawned task that owns the lock, as Go's handler
runs to completion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: fail the sidecar copy tests with an unreadable source .ecsum

A directory at the source path reads as "not found" on volume servers
that skip non-regular EC files, which turned the failure into a no-op.
A mode-000 file fails the transfer on every implementation; root and
Windows, which can read it, skip the test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: copy each shard a VolumeEcShardsCopy lists once

A shard listed twice and already held here was staged twice; the first
commit rename consumed the staged file, so the second failed the request
after the shard was replaced, and every retry failed the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: wait out an in-flight VolumeEcShardsCopy before mounting its shards

A shard the copy had already landed could be mounted while the copy was
still running; the copy's failure cleanup then removed the file but left
the shard registered and announced. MountEcShards takes the per-volume
lifecycle lock, as the enterprise build already does, and the Rust mount
handler takes the same lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: fail a VolumeEcShardsCopy whose replaced mounted shard cannot be reopened

The copy reported success while the mounted shard kept serving the
replaced file. The error lets the caller retry the copy instead of
treating the shard as delivered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check which transfer fails in the EC copy cleanup tests

An earlier failure, before any shard or sidecar landed, would leave the
destination unchanged and pass every assertion without exercising the
cleanup. The sidecar test also skips on Windows, where a mode-000 file
stays readable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: fail the sidecar transfer in the EC copy test by injection

A mode-000 file is still readable to root and on Windows, so the test
skipped there. The source now returns an error for the .ecsum request
only, and the test checks that it served .vif before that failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: take the EC lifecycle lock for a blanket full teardown

A teardown acknowledged while a detached copy of the same volume was
still waiting on its source let that copy recreate the index and shards
afterwards. Go and Rust now wait for the copy, as the enterprise build
does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: keep the request id on a Rust EC shard copy

The copy now runs in a spawned task, outside the gRPC layer's request id
scope, so its CopyFile calls to the source went out with a new id. Carry
the caller's id into the task.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: unmount a replaced EC shard whose reopen fails

The failed copy left the mount reading the replaced file's inode, so the
destination kept serving the old shard. Unmount it, which also reports
the removal to the master, so a retry copies and mounts it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: make the Rust EC copy tests fail for the right reason

The sidecar test now serves a directory as the source .ecsum, which root
cannot read either, so it no longer returns early there. The cancel test
holds the store until the handler's join reports the cancellation, so a
copy that finished before the abort can no longer pass it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: stage every shard a VolumeEcShardsCopy transfers

A shard missing here was written in place with a cleanup guard armed
before its transfer started, so a failed copy removed a shard that
ReceiveFile wrote meanwhile. Every shard is now staged, and only one
that did not exist when it is moved into place is removed on failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: take the EC lifecycle lock for VolumeEcShardsRebuild

A rebuild folds the deletion journal into .ecx. Run during a copy of the
same volume, the copy's index then replaced the folded tombstones. Go
and Rust take the lock the enterprise build already takes here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check the staged .vif bytes in the EC sidecar failure test

A source without the optional .vif also returns success, so the served
extension list could not prove the transfer. The test now reads the
staged .vif when the .ecsum request fails and compares it with the
source's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: unmount a failed reopen's shard on the copy's disk only

UnmountEcShards walks every disk, so a reopen failure on the destination
also unmounted a healthy copy of the same shard on a sibling disk. The
copy now unloads the shard from its own disk and reports that disk's
removal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: take the EC lifecycle lock for an ordinary EC shard delete

Shards a copy has staged are invisible to the delete's last-shard check,
so deleting the only canonical shard removed the index the copy was
about to commit its shards against. Go and Rust deletes now wait for an
in-flight copy of the same volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: leave a mounted shard's copied file in place on copy failure

A shard mounted on the copy's disk whose file was missing got the copied
file reopened into its mount, then that file was unlinked by a later
failure's cleanup while the mount kept serving it. Only an unmounted
shard's new file is removed now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: skip repeated shard ids with a seen set

Scanning the request prefix for each id made a request with many
repeats quadratic while the copy held the volume's lifecycle lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: make the Go EC copy and lock tests observe their effects

The fake source counts requests per extension, so the duplicate-id test
proves .ec05 is fetched once, and returns fixture errors instead of
failing the test from its handler goroutine. The staged .vif reaches
the test through a channel. The mount and teardown lock tests seed real
files and check that nothing happened while the lock was held and that
the operation took effect after it was released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: poll the handler directly in the Rust EC lifecycle lock tests

A spawned handler that had not run when the 200 ms timer fired passed
the blocking check without ever reaching the lock. The tests now poll
the pinned handler future themselves, which guarantees it is waiting on
the lock, and cover the ordinary shard delete as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: observe the lifecycle-lock waiter in EC copy lock tests

The mount, teardown, shard-delete and rebuild tests slept 200 ms while
holding the lock, so a handler scheduled only after the unlock passed
without ever taking it. Wait until the handler's goroutine is blocked on
the mutex instead; each test now fails within its timeout if the handler
skips the lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check the shard is staged before the failure-path write in a copy test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: recover a missing EC index under the volume's lifecycle lock

Missing-index recovery fetched the index and then ran a store-wide mount
of every orphan shard, without the per-volume lifecycle lock. It could
mount shards an in-flight VolumeEcShardsCopy of another volume had just
renamed in, and that copy's failure cleanup then unlinked a mounted shard.
Each recovered volume now holds its lifecycle lock across a re-check, the
fetch and a mount restricted to that volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): recover a missing EC index under the volume's lifecycle lock

Mirror of the Go change: recover_missing_ec_indexes takes the volume's
ec_lifecycle_lock, re-checks that the index is still missing, fetches it,
and mounts only that volume's shards through mount_recovered_ec_shards_only,
so an in-flight VolumeEcShardsCopy of another volume never has its
renamed-in shards mounted from under it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: mount a volume whose index a copy installed during recovery

Recovery re-checks under the lifecycle lock that the index is still
missing. When a copy installed it in the meantime, the re-check skipped
the mount too, and the volume's other shards stayed unmounted because
later scans no longer list it. Skip only the fetch and still mount the
volume's orphan shards under the lock, in Go and Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: fetch a recovered EC index into the disk the locked re-check found

The re-check under the lifecycle lock only kept a yes/no answer, so the
fetch still wrote to the destination from the first scan, which may be a
disk that has since gone away. Fetch into the record the re-check returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: mount a copy-installed EC index even when no peer is known

Recovery skipped the locked step when the master was unreachable, the
lookup failed or no peer was listed. A copy that installed the index after
discovery then left the volume's other shards unmounted, and later scans
no longer list it. Always run the locked re-check, and give up for lack of
peers only when the index is still missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: grow the stack buffer before scanning for a lock waiter

A full buffer can cut off the handler goroutine's stack, so the test would
report a handler that is waiting as one that never waited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): fetch a recovered EC index into the disk the locked re-check found

Mirror of the Go change: fetch into the record the re-check under the
lifecycle lock returned instead of the destination from the first scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): mount a copy-installed EC index even when no peer is known

Mirror of the Go change: a failed lookup or an empty peer list no longer
skips the locked re-check, so a volume whose index a copy installed after
discovery still gets its orphan shards mounted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): run missing-index recovery to completion when the mount RPC is cancelled

Dropping the mount handler mid-recovery released the volume's lifecycle
lock while the .ecj merge it had started on a blocking thread was still
landing, so a teardown could remove the volume before that late write.
Run recovery on its own task, as the copy handler does, so the lock is
held until it finishes; Go's handler already runs it to completion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: skip other volumes before stat in a single-volume EC scan

Recovery re-checks and mounts each volume with its own scans, so a
request with many orphans repeated whole-store discovery once per volume.
The index-owner and orphan-shard scans now take the same volume filter
and drop other volumes' files by name, before the per-file stat, and the
locked re-check scans only its own volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): skip other volumes before stat in a single-volume EC scan

Mirror of the Go change: the index-owner and orphan-shard scans take the
volume filter and drop other volumes' files by name before the per-file
stat, so recovery's per-volume re-check and mount no longer repeat
whole-store discovery under the store lock for every orphan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): announce shards recovered after the mount RPC was cancelled

Recovery now outlives a cancelled mount RPC, but the heartbeat nudge
stayed in the handler, so shards it mounted after the caller left waited
for the next full EC heartbeat. Nudge it from the recovery task, as Go's
loads announce each recovered shard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: match the collection as well as the volume id in the recovery re-check

Discovery keys orphans by (collection, vid), but the locked re-check
matched the vid only. Two collections with orphans of the same vid could
both resolve to the first record, so the other's index was never fetched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): match the collection as well as the volume id in the recovery re-check

Mirror of the Go change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:48:21 -08:00
Chris LuandClaude Opus 5.5 8c6d09f498 s3api: answer NoSuchBucket from GetBucketRequestPayment for a missing bucket (#12716)
* s3api: answer NoSuchBucket from GetBucketRequestPayment for a missing bucket

The handler wrote the static BucketOwner answer without resolving the
bucket, so a bucket that does not exist looked like one that does.
Check the bucket first, as PutBucketRequestPayment and the other static
configuration getters already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test GetBucketRequestPayment on existing and missing buckets

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:38:48 -08:00
eb1dca8088 filer: release the stamps of parent directories a rename creates (#12711)
* filer: release the stamps of parent directories a rename creates

* filer: test that a suppressed create keeps the moved entry's stamp in flight

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:37:56 -08:00
deacd575ea operation: prepare upload content before assigning the volume (#12714)
* operation: prepare upload content before assigning the volume

* operation: keep the existing upload function names for prepared payloads

UploadData and doUpload prepare once and hand the prepared payload to
retriedUploadData, so the retry loop, doUploadData, uploadChunk and
uploadChunkToHolders take a preparedUpload directly instead of growing
a prepared twin of each and branching on nil.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* operation: send ciphertext whenever the prepared payload carries a cipher key

doUploadData chose the cipher branch from the option, so a payload
prepared under a different option could be sent as plaintext metadata
or lose its key. Decide from the prepared payload itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* operation: build a chunk's preparation and upload options in one place

The chunk loop prepared with a hand-written option while uploadChunk and
uploadChunkToHolders built their own, so a setting that shapes the bytes
could reach one and not the other. chunkUploadOption now feeds all three.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* operation: test that a reassigned chunk reuses its prepared payload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:36:46 -08:00
Chris LuandClaude Opus 5.5 194e6ede9f seaweed-volume: reject FetchAndWriteNeedle reads that miss the requested size (#12717)
The Go volume server fails the RPC when the remote read returns a
different length than req.Size; the Rust server cached whatever came
back as a full-size chunk.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:35:38 -08:00
97f49571a1 wdclient: let master-pushed adds replace the gateway's lookup-fed locations (#12705)
* wdclient: let master-pushed adds replace the gateway's lookup-fed locations

After a master leader change the S3 gateway clears its FilerClient cache and
refills it through filer lookups. The filer's own master client may still
answer from the previous leader's generation until the new leader has heard
from the volume servers, so a volume server lost together with the old leader
is cached again. The new leader never knew that server and never pushes its
removal, and the gateway keeps trying it until reads fail on it volume by
volume, one 30 s dial timeout at a time.

The gateway's master client relearns every volume from the new leader's
adds. On each add, cache the volume where the master client now knows it to
be, in place of what a lookup cached, and keep lookups already in flight from
caching their answer over it. A provider answer for a volume is now cached
whole or not at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: take a lookup's fill epoch before its second cache check

A master add that landed between the second cache check and the read of
the fill epoch was invisible to both: the check had already missed, and
the epoch the lookup then read already included the confirmation, so a
filer answer that still named the lost server was merged back into the
confirmed entry. Taking the epoch first means such an add either shows
up in the check or stops the answer from being cached. The same order
covers a reset or clear in that gap.

TestConfirmDuringLookupIsNotUndone fires a confirmation from a test hook
at that point and fails with the old order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: gate the master lookup provider's cache writes on the map epoch

The provider wrote each answer straight into the vid map, so a lookup sent
before a master reset and answered after it landed in the new generation,
which a gateway's FilerClient now reads as the current master's view. The
answer now goes through fillLocations, which drops it once a reset passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* wdclient: keep the vidMapClient doc comment on its type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-17 19:10:20 -08:00
Konstantin Adzer 91eaabf371 s3: answer ClientDisconnected for a GET the client aborted before the first byte (#12707)
* s3: answer ClientDisconnected for a GET the client aborted before the first byte

Fixes #12706

* s3: tell a gone client on TLS and HTTP/2 too, and not on a connection the server closed
2026-11-17 17:15:00 -08:00
c91da3d1f8 filer: fail health check when absent from lock ring (#12709)
* filer: fail health check when absent from lock ring

If the master broadcasts a lock ring that does not include this filer
(e.g. the late-cleanup race in seaweedfs#11442), every lock acquisition
fails with "no lock server found" and locked writes, including S3 PUTs,
hang indefinitely while /healthz and /readyz still report OK.

Make the filer health handler return 503 once this filer has been
missing from its own lock ring for longer than a 30s grace period, so
Kubernetes liveness probes restart it and it re-registers with the
master. The grace period covers startup before the first ring update
and the master's ring-change batching delay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: hold the lock-ring health clock until the filer announces

AnnounceOnceCaughtUp can hold the master registration for up to a minute
while HTTP already serves, so the filer cannot be in the ring yet. Report
healthy until the announce gate opens and start the grace period after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a probe racing a ring rejoin from reading a reset clock

A probe that loses the CompareAndSwap to a concurrent healthy probe could
load the reset zero and report the filer absent since the epoch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: trim the lock-ring health comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: restart the lock-ring health grace when a ring update brings the filer back

The clock only reset when a probe saw the filer in the ring, so a rejoin
and a second removal between two probes reused the first absence and
failed the next probe early. Reset it from the ring snapshot callback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test the announce gate leaves the lock-ring health clock unset

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: re-read lock-ring membership after starting the health clock

A probe whose first read raced a rejoin could start the clock after the
snapshot callback reset it, leaving a stale start for the next removal.
The ring is installed before the callback runs, so a second read sees the
rejoin whenever the reset came first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: treat a health clock changed during the probe as a rejoin

A rejoin and a second removal can both land between the probe's two
membership reads. The second read then shows the filer absent again, and
the probe judged the new absence by the expired start it had read before
the rejoin's reset. The snapshot callback resets the clock before the next
ring update is installed, so a clock that no longer matches the probe's
start means a rejoin happened; report healthy and let the next probe use
the fresh clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test ring updates that land during a lock-ring health probe

Move the absence clock into lockRingAbsence, which takes the membership
read as a function, so the test can install ring updates between the
probe's reads: a rejoin after the first read, and a rejoin plus removal
between the two reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: give every lock-ring health reset a new clock value

A probe that saw the filer absent started the clock with a CAS from 0,
so a rejoin that reset the clock to 0 again before that CAS was
invisible, and the probe could install a start time from before the
rejoin. Each reset now stores a new non-positive value and the probe
swaps from the value it loaded before the membership read, so any
rejoin during the probe makes the CAS fail. This drops the second
membership read and never waits on the LockRing mutex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test lock-ring rejoins before and after the probe's membership read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the lock-ring version lookup out of the unhealthy health path

LockRing.Version takes the ring mutex, which SetSnapshot holds while
the snapshot callback transfers locks, so an expired-absence probe
could wait on those transfers and time out instead of answering 503.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test an expired-absence health probe while the ring mutex is held

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-17 17:13:45 -08:00
c76fb36416 test(fuse): two mounts staging the same files without -dlm (#12704)
* test(fuse): two mounts staging the same files without -dlm

Two jobs that extract the same archive into one shared directory, each
through its own mount and without -dlm, both create many of the same
files: a file that exists is skipped, otherwise it is created, written
and closed, then chmod'ed and given its mtime. Before #12593, #12594 and
#12596 the attribute update and the content flush sent the mount's whole
cached entry. Sent after the other mount had rewritten the file, the
update put back chunks that the rewrite had dropped and the filer had
deleted, so the entry pointed at deleted needles and the file failed to
read once its volume was vacuumed. Nothing told the writers.

TestStageSameFilesWithoutDLM runs that on the fuse_dlm cluster with the
mounts started without -dlm (startTestCluster takes a dlm flag;
startDLMTestCluster is unchanged) and checks every staged file: each
chunk is still on the volume server (HEAD on the fid, without
readDeleted) and the filer serves the bytes written. What the losing
writer is told depends on the version and is only logged.

With a 4.53 weed binary the test fails: 66, 71 and 70 of the 400 files
were broken in three runs. With master it passes in about 48 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(fuse): bound the staging test's filer and volume checks

The checks used the default HTTP client and a background context, so a
server that accepts a request and stops answering held the test until the
package timeout instead of failing the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(fuse): fail the staging test unless both mounts wrote the same files

A mount whose MkdirAll failed returned early, and a mount that started
late could skip every file, so the test passed with one writer. Start both
loops together, fail on setup errors, and require files both mounts wrote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(fuse): bound the staging test's checks with one deadline

A per-call timeout still let 400 hung lookups and reads run for hours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-17 17:08:39 -08:00
0d3f5a220c s3: keep serving for -preStopSeconds after SIGTERM (#12703)
* s3: keep serving for -preStopSeconds after SIGTERM

On SIGTERM the gateway closed its listeners at once, so requests a load
balancer or Kubernetes Service still routed to it failed until the endpoint
was removed. With -preStopSeconds set, the gateway makes /status, /healthz
and /readyz return 503, keeps serving for that many seconds, then runs the
existing graceful shutdown. 0 (the default) keeps the old behavior.

The flag is registered for weed s3 and as -s3.preStopSeconds for weed
filer, weed server and weed mini. A cancelled weed mini cluster context
ends the wait early. The Helm chart passes s3.preStopSeconds and
filer.s3.preStopSeconds through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: assert the preStopSeconds chart render under set -e, drop timing from the probe test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: wait before weed mini cancels its clients; size grace periods in the chart

weed mini's interrupt hook runs before the S3 one and cancels the S3
gateway's shutdownCtx, so the pre-stop wait never happened there. The wait
is now also registered with beforeMiniClientsShutdown, which runs before
that cancel, and a sync.OnceFunc keeps the interrupt hook from waiting a
second time. Outside weed mini the registration is a no-op.

Helm: the s3 deployment fails to render when terminationGracePeriodSeconds
is below preStopSeconds + 15. The filer statefulset and the all-in-one
deployment, whose grace period is fixed at 60s, add preStopSeconds to it.
allInOne.s3.preStopSeconds is passed through, inheriting s3.preStopSeconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep 64-bit counters aligned on 386; let allInOne.s3.preStopSeconds=0 disable the wait

draining sat ahead of inFlightDataSize and inFlightUploads in S3ApiServer
and shifted them off 8-byte alignment on 32-bit builds, so the atomic
upload-limit counters panicked there. It now follows them.

Helm: allInOne.s3.preStopSeconds inherits s3.preStopSeconds only when null;
default treated an explicit 0 as unset. The s3 values and the grace period
error now say a lifecycle preStop hook's time comes on top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grace: add OnInterruptFirst for hooks that must run before any shutdown

Interrupt hooks run in reverse registration order, so a hook cannot run
ahead of a service that registers later, such as a volume server that is
still loading its volumes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: run the -preStopSeconds wait before every other interrupt hook

Under weed server the volume server registers its hook once its volumes
are loaded, often after the S3 gateway. Its hook then ran first and shut
the volume server down, so the gateway spent the whole wait serving
requests that could not read or write objects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-17 17:06:06 -08:00
Chris LuandClaude Opus 5.5 c4e1802e3e s3: route ';' queries as authorized, and report an empty s3:prefix to policies (#12702)
* s3: escape raw semicolons before the router matches a route

registerRouter applied EscapeSemicolonsInQuery with router.Use, but mux
runs router middleware only after it has picked the route. Queries()
matchers split pairs on ';', so GET /bucket?uploads;x=1 reached the
multipart listing handler while the handler and the IAM resolver read
uploads%3Bx=1 and saw no uploads subresource. Wrap the S3 router with the
escape so routing and authorization read the same query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: report a listing without prefix as s3:prefix "" in policy conditions

The advanced IAM path already sets s3:prefix to "" when a bucket listing
names no prefix, as AWS does, but bucket policies and attached policies
read conditions from ExtractConditionValuesFromRequest, which leaves the
key out. The AWS home-directory policy that grants s3:prefix ["", "home/"]
then denied the root listing, and a Deny keyed on the empty prefix never
applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: test the served handler composition for the semicolon escape

Move the escape and the Vectors split into s3Handler so a command test can
send ';' queries through the handler the server actually serves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep the isVectorsRequest doc comment on its function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:05:34 -08:00
1d30b0de21 fix(s3api): complete bucket-listing IAM condition handling (#12699)
* fix(s3api): complete bucket-listing IAM condition handling

Populate s3:delimiter and s3:max-keys for bucket. Add regression tests for listing conditions and variants.

Assisted-by: gpt-6.1-sol, deepseek-v4.1-flash

* fix(s3api): ignore max-keys for multipart listing policies

Assisted-by: GPT-6.1 Terra

* s3api: drop max-keys from multipart-upload listing policy conditions

Bucket policies and embedded IAM policies read condition values through
ExtractConditionValuesFromRequest, which still exposed max-keys on ?uploads
listings. Those page by max-uploads, so an unused max-keys parameter could
satisfy an s3:max-keys condition. Match the advanced IAM path and leave the
key absent there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:05:00 -08:00
5681be241e topology: never report negative free volume slots (#12698)
* topology: never report negative free volume slots

Free volume slots are computed as max + remote - volume - ecSlots. When phantom or over-registered volumes push the count past the configured max, the result is negative and rolls up into the cluster total, causing volume grow and assign to fail with a negative 'volumes left' count even while healthy servers have capacity. Clamp every free-volume count at zero so an over-committed server contributes no slots instead of subtracting from the cluster.

* topology: drop the issue reference from the free-slot test comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: test free slots next to an over-committed server

A server with more volumes than slots must not hide the free slots of
the other servers in its rack, data center or topology.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: sum free slots per data node in racks, data centers and topology

Clamping the rolled-up counters only clamped their sum, so one server with
more volumes than slots still hid the free slots of every other server in
its rack, data center and topology. Interior nodes now add up their
children's free slots, so each data node counts as zero at worst. A data
node in maintenance mode no longer adds slots to its parents either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: test that disk info keeps an over-committed deficit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: keep the signed free volume count in disk info

EC encode retries and the balance planners add refunds and planned moves
to the published FreeVolumeCount. Clamping it at zero dropped an
over-committed disk's deficit, so a refund could make a full disk look
free. Volume growth already reads the clamped AvailableSpaceFor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: test placement next to an over-committed server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: accept either data center order in the placement spread check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:02:01 -08:00
8ba33fae71 rust volume: bulk-load needle maps on redb 4.6 and compact the old floor (#12695)
* seaweed-volume: expect a fresh redb file to start at 72 KiB

The assertion fails on redb 4.2.0, whose empty database is about 1 MiB.

* seaweed-volume: bulk-load redb rebuilds with the stable cursor

redb 4.6.0 has no experimental_cursor feature. Full rebuilds insert
sorted needle ids through insert_before, and a new .rdb starts at 72 KiB.

* seaweed-volume: test which redb files are still at the old floor

The gate is missing, so the test does not compile yet.

* seaweed-volume: decide when a reused redb is still at the old floor

Compact only a file above 72 KiB and at most 1 MiB plus 8 KiB, and only
when floor_compact has not been recorded.

* seaweed-volume: test one-shot compact of an old-floor redb

Reuse, shrink, and storage-error recovery are specified. The helpers
they call are not implemented, so the tests do not compile yet.

* seaweed-volume: compact a reused redb that is still at the old floor

One compact runs when the file is above 72 KiB and at most 1 MiB plus
8 KiB. A storage error drops the handle and opens the same path again
so the volume does not keep a PreviousIo latch.

* seaweed-volume: publish a redb replay before compacting the old floor

compact() is what would make a Durability::None tail durable, and a
storage error then drops that tail on reopen. An in-band file is
committed first. The floor_compact flag is read only inside the band,
so a meta error cannot rebuild a larger index.

* seaweed-volume: drop the redb experimental cursor CI step

redb 4.6 has no redb-experimental-cursor feature. The needle-map tests
that used it now run in the normal cargo test step.

* seaweed-volume: drop the experimental-api-5 notes on redb reads

redb's experimental-api-5 can no longer be enabled, so these reads always
use the inherent ReadOnlyTable::get.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: drop the always-false flag from the old-floor band check

Both callers pass false and read floor_compact on their own, so the band
check only needs the file length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:00:55 -08:00
d8a47042c5 master: unregister a volume server whose heartbeats stop (#12697)
* master: unregister a volume server whose heartbeats stop

A volume server sends a heartbeat every 5 s. When its host hangs or its
network drops packets, its SendHeartbeat stream stays open, and the
master unregisters it only once gRPC keepalive closes the connection,
60 s plus 20 s after the last frame. Until then the master keeps
assigning writes to volumes with a copy on it, and those writes hang.

SendHeartbeat now ends the stream when no heartbeat arrives for three
pulses (15 s), which unregisters the server through the existing
deferred path and tells clients its locations are gone. The server
reconnects and registers again once it can reach the master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: test that clients learn a silent server's volumes are gone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: fail the silent-stream receive test instead of hanging

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-17 16:59:40 -08:00
Chris LuandClaude Opus 5.5 dbb2fdb93b pb: recover when a local gRPC socket file is deleted (#12694)
* pb: fall back to TCP when the local gRPC socket cannot be dialed

A temp cleaner can delete a local gRPC socket file while its server keeps
running. Every later dial to that server then failed with "no such file or
directory", so the master could no longer reach its own volume server and
volume growth stopped. Dial the server's TCP address when the socket dial
fails, as the S3 gateway already does for the filer's HTTP socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: recreate a local gRPC socket whose file was removed

Once its socket file was deleted, a server kept accepting on an
unreachable listener until restart, so same-host RPCs stayed on the TCP
fallback. Check the path every minute and, when the file is gone, close
the old listener and bind the socket again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: retry a failed local socket rebind on the next check

A failed rebind ended the watcher, so the socket stayed missing after the
cause cleared. Bind the replacement before closing the old listener: a
failed bind keeps the old listener serving and is retried on the next
check, and the old Serve still reports server shutdown. The old listener
no longer unlinks the path on close, since the replacement now owns it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: set the local socket unlink policy before serving the listener

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:58:19 -08:00
b74971b6d4 server: add -grpc.localSocketDir for the local gRPC sockets (#12693)
* server: add -grpc.localSocketDir for the local gRPC sockets

`weed server` and `weed mini` hard-coded each local gRPC Unix socket
under /tmp. systemd-tmpfiles ages /tmp after 10 days and macOS after 3,
so a long-running server loses its socket, and RegisterLocalGrpcSocket
keeps routing local dials to the missing path: the master can no longer
reach its volume server.

Add -grpc.localSocketDir to both commands, defaulting to /tmp so an
existing setup is unchanged, and build every socket path from it with
filepath.Join. A folder that does not exist or is not a directory is
refused at startup rather than at the first local RPC. A folder whose
socket paths exceed the platform's sockaddr_un limit is refused too,
because every bind then fails with EINVAL while the server keeps running
and each local RPC dials a socket that does not exist.

Refs #12692

* server: refuse a -grpc.localSocketDir the server cannot bind in

An existing folder the server's user cannot write to passed the startup
check, and then every socket bind failed: ListenOnLocalSocket only logs
the error while GrpcDial keeps routing local dials to a socket that was
never created. After the path-length check, create and remove a probe
Unix socket in the folder, and refuse startup with the bind error if
that fails.

* server: give the -grpc.localSocketDir probe a random name

A probe named only by the process id could be precreated by another
user in a shared /tmp, or left by a crashed process whose pid was
reused, and the server cannot remove such a file, so startup failed
although the real socket paths were free. Name the probe with 8 random
bytes, retry a name that is taken, and rely on the listener's close to
unlink it.

* server: keep the -grpc.localSocketDir probe name within the service socket lengths

The probe was 5 bytes longer than the master and volume socket names, so a
folder whose service sockets fit the sockaddr_un limit could still be refused.
A 23-byte probe name is shorter than any service socket name, and a process
with no local sockets skips the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* server: trim the -grpc.localSocketDir comments and drop issue references

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Brent Pease <179639673+brentDSL@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:56:15 -08:00
Chris LuandClaude Opus 5.5 95f46c8fff admin: manage filer webhook targets from the UI with live reload (#12690)
* webhook: share the default target settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webhook: managed webhook targets with a drainable queue

Targets kept as JSON (name, endpoint, token, filters, retry and worker
settings) build their own queue; Close waits for queued and in-flight
deliveries before stopping it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: run webhook targets stored in /etc/seaweedfs when notification.webhook.managed is set

The targets in /etc/seaweedfs/notification_webhooks.json start with the
filer and are rebuilt from the store whenever the file changes on any
filer, alongside notification.toml. The previous queue drains before it
stops. Events for the file itself, which holds bearer tokens, are not
sent to notification queues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: manage filer webhook targets

A Webhooks page under Management lists, adds, edits and deletes the
targets kept in /etc/seaweedfs/notification_webhooks.json. Bearer
tokens are write-only: the API reports whether one is set, and an empty
token on edit keeps the stored one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the webhook queue when the stored targets did not change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a replaced webhook queue open until its senders hand over

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: read chunk-backed webhook targets before editing them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: keep the stored webhook targets out of fs.meta.notify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webhook: reject negative managed target settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webhook: no signal handler on queues that reloads replace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: swap the webhook queue without waiting behind blocked senders

The read lock held across SendMessage made a reload wait for any sender
blocked on a saturated target, and the waiting writer stalled every
other filer write with it, which is when an operator disables that
target. Close now refuses new sends and waits for the senders already
inside SendMessage, and a send that hits the closing queue retries on
its replacement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webhook: release blocked test handlers before the server shuts down

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: always run the webhook targets managed in the admin UI

Drop the notification.webhook.managed switch: every filer loads and live
reloads the stored targets. Without stored targets no queue is created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: place the admin-managed webhook note above enabled

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: separate the admin-managed webhook note

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: note that admin-managed webhooks follow the notification queue

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: retry loading webhook targets after a failed read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: retire the admin-managed webhook queue on shutdown

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:54:54 -08:00
github-actions[bot] 386385101d docs: regenerate star history chart 2026-11-18 00:33:52 +00:00
Chris LuandClaude Opus 5.5 6342876392 ci: run the Python 3.9 jobs on 3.10 (#12691)
* ci: run the Python 3.9 jobs on 3.10

ubuntu-latest now resolves to Ubuntu 26.04, which has no Python 3.9 build
for actions/setup-python, so the Ceph S3 tests and the PyArrow Parquet
3.9 job fail during setup. 3.10 is the oldest version built for 26.04.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: list the Python versions the parquet CI runs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:07:34 -08:00
Chris LuandClaude Opus 5.5 40182a68bc admin: keep the dark theme from flashing light on reload (#12689)
* admin: apply the saved theme inline at the top of the page head

The theme script was an external file, so a reload had to fetch or
revalidate it before the root got its theme, and the page could paint
with the light default in the meantime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: set color-scheme on the root together with the theme

Until the stylesheets load, the browser paints the page canvas from the
root's color-scheme, which only the stylesheets set, so a dark theme
showed a white canvas for the duration of every reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:31:00 -08:00
github-actions[bot] eed00c3737 docs: regenerate star history chart 2026-11-17 01:00:14 +00:00
Chris LuandClaude Opus 5.5 b449301a4e ec: mount shards through the encode's .vif when a source volume's .vif shares the disk (#12676)
* ec: mount shards against the index .vif when the local one has no EC config

A worker encode can send shards to a disk that still holds the source
volume's .vif while the encode's .vif lands with the index on a sibling
disk. The shard disk mounted through the source's config-free .vif, so
it reported encode time 0 and fell back to the sidecar layout, and reads
carrying the encode time were rejected as a different encode run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): mount shards against the index .vif when the local one has no EC config

Mirrors the Go mount: a data-dir .vif that records no EC config yields
to the idx dir's when that one records it, and load_vif_info_across_dirs
reports the directory the .vif actually came from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: do not mirror EC sidecars onto a disk whose .vif has no EC config

Startup mirroring copied .ecx/.ecj next to a source volume's leftover
config-free .vif and kept that .vif, so after a restart the shard disk
mounted self-contained with encode time 0. Leave such a disk on the
cross-disk mount, which reads the owner's .vif.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): do not mirror EC sidecars onto a disk whose .vif has no EC config

Mirrors the Go startup mirror: a shard disk holding a source volume's
config-free .vif stays on the cross-disk mount, which reads the owner's
.vif, instead of mounting self-contained with encode time 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: take the encode .vif from a sibling data dir when the index dir is shared

With a separate -dir.idx the .ecx is shared by every disk, but the encode's
.vif lands in the data dir of the disk that received it. A disk still holding
a source volume's config-free .vif mounted through it at generation 0.
NewEcVolume now accepts the server's data dirs and takes a sibling's EC .vif
when the index is not local and every sibling EC .vif names the same run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: give EC mounts the data dir of every disk on the server

NewStore records every data dir on each DiskLocation before loading, so the
startup scan, cross-disk reconcile and MountEcShards all pass them to
NewEcVolume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): take the encode .vif from a sibling data dir when the index dir is shared

Mirrors the Go mount: EcVolume::new_with_vif_dirs takes a sibling's EC .vif
when this disk's own records no EC config, the index is not local, and every
sibling EC .vif names the same run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): give EC mounts the data dir of every disk on the server

main sets Store.store_dirs before the first add_location, so a disk loaded
before its siblings still sees them; each DiskLocation passes them to
EcVolume::new_with_vif_dirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: size startup EC validation by the sibling encode .vif

With a shared -dir.idx, a disk that still holds the source .dat and its
config-free .vif read the default data-shard count, judged custom-ratio
shards an interrupted encode, and removed them along with the shared .ecx
before the mount could take the sibling's .vif. The startup lookup now
falls back to the same sibling .vif the mount uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): size startup EC validation by the sibling encode .vif

Mirrors the Go change: validate_ec_volume falls back to the sibling data
dir's encode .vif before judging shards beside a source .dat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: keep EC shards when sibling .vif files disagree on the encode

SiblingEcConfigVif reports when a sibling .vif cannot be read or the
siblings name different encode runs. The startup data-shard lookup then
returns 0 instead of the default ratio, and validateEcVolume keeps the
files rather than sizing custom-ratio shards by a ratio they do not use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep EC shards when sibling .vif files disagree on the encode

Mirrors the Go change: sibling_ec_config_vif returns Err for an unreadable
sibling .vif or disagreeing runs, ec_data_shards_from_vif returns 0 then,
and validate_ec_volume keeps the files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: release the opened EC shard when its volume cannot be built

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:38:17 -08:00
Chris LuandClaude Opus 5.5 9e5357782e volume: keep reads over the download limit local when readMode is local (#12679)
* volume: keep reads over the download limit local when readMode is local

With -readMode=local the server never sends a read for a volume it does
not hold elsewhere, but a read over -concurrentDownloadLimitMB on a
replicated volume was still redirected to another replica. Skip the
replica fallback in local mode, so the read waits for a download slot
and answers 429 when the wait times out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep reads over the download limit local when readMode is local

Mirror the Go volume server: with readMode local, a read over the
download limit waits for a slot instead of being redirected to a
replica. proxy_or_redirect_to_target no longer needs the local-mode
redirect switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check download capacity under the wait lock

waitForDownloadSlot read the in-flight size outside the cond lock and
the read handler broadcast without it, so a download finishing between
the check and the wait was missed and the read waited out the timeout
for a 429. Check capacity with util.WaitUntil under the lock and
broadcast under it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): register for the download notification before checking capacity

The wait loop created its Notified future only after the capacity
check, so a body dropped in between had its notify_waiters() lost and
the read waited out the deadline for a 429. Create the future first,
then check, as Go now checks under the cond lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:20:15 -08:00
f4e638fa1d Fix/admin cluster submenu (#12677)
* admin: fix cluster submenu toggle

* admin: update embedded JavaScript

* admin: drop the object store submenu handlers

The sidebar no longer renders an object store submenu, so its expand,
link and toggle handlers match nothing; the toggle handler repeated the
manual collapse that fought Bootstrap on the cluster submenu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: ivan <i.stepanov@navigine.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:13:18 -08:00
Chris LuandClaude Opus 5.5 1e31c6dbf5 test(pjdfstest): check the sudo'd mount with ps, not kill -0 (#12673)
sudo switches its real uid to root while it starts, so kill -0 from the
invoking user fails with EPERM even though the mount process is alive,
and the wait loop reported "weed mount exited early" a few milliseconds
after starting it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:12:30 -08:00
0f0f3811bf filer: serve caught-up aggregated subscribers from memory, not a held disk pass (#12674)
* filer: serve caught-up aggregated subscribers from memory, not a held disk pass

An aggregated SubscribeMetadata stream that does not take metadata chunks
(filer.sync, filer.backup, filer.meta.backup, filer.meta.tail, the
filer.remote.* syncs, the S3 gateway's subscriptions, and mounts that
predate chunk support) re-ran the persisted-log pass whenever its cursor
moved: after every memory hold at the delivery watermark and on every
2 s re-probe. The pass holds at the peers' flush low-watermark. Peers
flush on their own one-minute schedules, so on a cluster that keeps
writing some peer has always flushed past a caught-up cursor while the
slowest has not: the pass held at its first entry, the loop came back
to it, and memory was never read. The stream got each change only once
the slowest peer's flush covered it, in bursts up to a flush interval
late, and every pass listed and re-read the newest log files.

When the aggregated ring was already filling at the cursor and evicted
nothing after it, memory holds everything the persisted logs could add,
since every peer's log reaches the ring through the aggregator. Skip the
pass and read memory, held at the delivery watermark as before. The
skipped pass proves nothing past the cursor, and the next-day scan for
an empty pass does not apply. An empty ring, a ring that starts past the
cursor, and a cursor memory just refused still take the pass. Chunk
subscribers already skip it for a caught-up cursor: their ref listing
stops below the flush hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a new peer's pre-start history on the disk pass

The ring only receives a peer's events from the start of its subscription.
A peer followed for the first time after this filer started (a filer added
to the cluster, a restarted pod with a new address, or the late-arriving
peers bootstrap) starts at its notice time, so what it logged before then
is only in the persisted logs. A cursor below that start passed the ring
check and skipped the disk pass, losing those events for subscribers that
do not take metadata chunks.

Record the newest start of a peer subscription that had no resume point and
send cursors below it through the disk pass as before. Peers that rejoin with
a resume point (a restart under the same address) do not move it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-16 16:12:06 -08:00
dependabot[bot] 53b234558e build(deps): bump actions/setup-go from 6 to 7 (#12685)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 6 to 7.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/setup-go
  dependency-version: '7'
  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-11-16 15:39:24 -08:00
dependabot[bot] d9c2d99f8f build(deps): bump gocloud.dev/pubsub/natspubsub from 0.46.0 to 0.49.0 (#12680)
Bumps gocloud.dev/pubsub/natspubsub from 0.46.0 to 0.49.0.

---
updated-dependencies:
- dependency-name: gocloud.dev/pubsub/natspubsub
  dependency-version: 0.49.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-11-16 15:38:44 -08:00
dependabot[bot] e3769592a5 build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/storage/azblob from 1.8.2 to 1.8.3 (#12684)
build(deps): bump github.com/Azure/azure-sdk-for-go/sdk/storage/azblob

Bumps [github.com/Azure/azure-sdk-for-go/sdk/storage/azblob](https://github.com/Azure/azure-sdk-for-go) from 1.8.2 to 1.8.3.
- [Release notes](https://github.com/Azure/azure-sdk-for-go/releases)
- [Commits](https://github.com/Azure/azure-sdk-for-go/compare/sdk/azidentity/v1.8.2...sdk/storage/azblob/v1.8.3)

---
updated-dependencies:
- dependency-name: github.com/Azure/azure-sdk-for-go/sdk/storage/azblob
  dependency-version: 1.8.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-11-16 14:58:43 -08:00
dependabot[bot] c3f4b3e0eb build(deps): bump go.etcd.io/etcd/client/v3 from 3.7.1 to 3.7.3 (#12682)
Bumps [go.etcd.io/etcd/client/v3](https://github.com/etcd-io/etcd) from 3.7.1 to 3.7.3.
- [Release notes](https://github.com/etcd-io/etcd/releases)
- [Commits](https://github.com/etcd-io/etcd/compare/v3.7.1...v3.7.3)

---
updated-dependencies:
- dependency-name: go.etcd.io/etcd/client/v3
  dependency-version: 3.7.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-11-16 14:57:32 -08:00
dependabot[bot] 438cc8562f build(deps): bump github.com/aws/aws-sdk-go-v2/service/s3 from 1.114.1 to 1.114.10 (#12681)
build(deps): bump github.com/aws/aws-sdk-go-v2/service/s3

Bumps [github.com/aws/aws-sdk-go-v2/service/s3](https://github.com/aws/aws-sdk-go-v2) from 1.114.1 to 1.114.10.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/service/s3/v1.114.1...service/s3/v1.114.10)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go-v2/service/s3
  dependency-version: 1.114.10
  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-11-16 14:56:55 -08:00
dependabot[bot] 51ab451f37 build(deps): bump github.com/rabbitmq/amqp091-go from 1.15.0 to 1.16.0 (#12683)
Bumps [github.com/rabbitmq/amqp091-go](https://github.com/rabbitmq/amqp091-go) from 1.15.0 to 1.16.0.
- [Release notes](https://github.com/rabbitmq/amqp091-go/releases)
- [Changelog](https://github.com/rabbitmq/amqp091-go/blob/main/CHANGELOG.md)
- [Commits](https://github.com/rabbitmq/amqp091-go/compare/v1.15.0...v1.16.0)

---
updated-dependencies:
- dependency-name: github.com/rabbitmq/amqp091-go
  dependency-version: 1.16.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-11-16 14:56:35 -08:00
dependabot[bot] 34927705fa build(deps): bump actions/setup-python from 6 to 7 (#12686)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 6 to 7.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-version: '7'
  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-11-16 14:56:11 -08:00
Chris LuandClaude Opus 5.5 d5b4e1352e helm: drop the 4.53 vector metrics render guard (#12672)
* helm: pin the 4.53 tag in the vector metrics rejection test

The 4.54 release made 4.54 the chart's default image, and that image
serves weed-vector metrics, so rendering vector.metricsPort with the
default tag no longer fails. Pin image.tag=4.53 for the rejection case
and check that the default image renders the metrics port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: describe vector metrics support from 4.54 on in the chart README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: say the vector metrics render guard skips image overrides

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: drop the 4.53 vector metrics render guard

The chart now defaults to 4.54, whose weed-vector serves --metrics-port, so
the check keyed on one old tag only blocked valid installs. The test asserts
the default image renders the metrics flag and HTTP probes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: describe vector metrics without the render guard in the chart README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:49:39 -08:00
github-actions[bot] 5ef99c1d8d 4.54 2026-11-16 05:31:42 +00:00
Chris LuandClaude Opus 5.5 8e15110b4f filer: wake metadata subscribers only for directories they can match (#12669)
* log_buffer: let a subscriber skip wake-ups for unwanted partition keys

Every append woke every registered subscriber. SetSubscriberWakeFilter lets
a reader sleep through appends whose partition key it would filter out; it
still reads them on its next poll. Flushes and keyless appends wake everyone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer_pb: decide subscription matches from an event's directories

MetadataDirectoryMayMatchSubscription rules out events whose directory no
child path of can match the subscription, and ScanMetadataEventDirectories
reads an event's directory and new parent path without allocating.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: wake subscribers of a move's destination directory

Appends are keyed by the source directory, so a filtered subscriber of the
destination would otherwise only see the move on its next poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: wake metadata subscribers only for directories they can match

Every metadata event woke and was scanned by every subscriber, so filer CPU
grew with the number of subscribers watching other paths. Readers now
register a directory wake filter, and the per-entry prefilter rules entries
out from their directories before the skeleton scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: test that moves into a subscribed prefix pass the prefilter

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:53:41 -08:00
Chris LuandClaude Opus 5.5 f13b763552 docs: explain the 3-filer recommendation in the production setup notes (#12671)
* docs: explain the 3-filer recommendation in the production setup notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: note that a filer load balancer must forward the gRPC port

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:52:03 -08:00
Chris LuandClaude Opus 5.5 df30c883fe s3api: keep a multipart upload's state on the object's owner filer (#12668)
* s3api: create a multipart upload's directory on the object's owner filer

CreateMultipartUpload wrote .uploads/<id> to the gateway's own filer while
the upload's completion commits on the object's write owner. With
independent filer stores, a part or completion reaching another gateway
before peer metadata replication caught up could not see the upload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: look up a multipart upload on the object's owner filer

UploadPart, UploadPartCopy, ListParts, CompleteMultipartUpload,
AbortMultipartUpload and the bucket policy SSE lookup read .uploads/<id>
from the gateway's own filer, so a request on another gateway shortly
after CreateMultipartUpload answered NoSuchUpload until replication
caught up. Read it preferring the object's write owner, like object reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: write multipart parts to the upload's owner filer

UploadPart and UploadPartCopy stored part entries on the gateway's own
filer, so ListParts and CompleteMultipartUpload on another gateway could
miss a part that replication had not delivered yet. Store them next to the
upload directory on the object's write owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: list and clean up a multipart upload on its owner filer

ListParts, CompleteMultipartUpload and AbortMultipartUpload listed and
removed part entries on the gateway's own filer. Do it where the upload
and its parts now live, so completion sees every part and cleanup does
not miss entries replication has not delivered yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test a multipart upload against a lagging gateway filer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: check the upload's owner before freeing a failed part's chunks

A part write that the owner stored but answered with an error went to
recovery with no object, so the owner was never among the filers checked.
When the owner is outside the gateway's filer list, the others' not-found
answers freed chunks the stored part still references.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: list an upload's parts on the prior owner after a ring change

The upload record lookup already falls back to the key's prior owner while
a ring change is in its cooling-off window, but the part listing read only
the new owner. ListParts then reported no parts for an open upload. Fall
back the same way when the new owner has nothing yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: find the upload record on the prior owner past a bare directory

A part routed to a new owner that has not received the upload yet makes
that filer create .uploads/<id> without the upload's key. The post-write
check then read it as an aborted upload and removed the part. While the
ring change is in its cooling-off window, a record on the prior owner
now wins over such a directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: merge the prior owner's parts into an upload listing

During a ring change's cooling-off window the new owner may have received
only some of an upload's parts. Listing returned the new owner's parts
alone once it had any, so ListParts dropped the rest and a completion
naming them failed with InvalidPart. Both owners' pages are now merged,
the owner's entry winning a shared name, and cut to the page limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fail an upload listing the prior owner could not answer

When the new owner has none of an upload's parts yet and the prior
owner's listing fails, the parts may all be on the prior owner. That
listing read as empty, so CompleteMultipartUpload answered NoSuchUpload
for an upload that still exists; it now returns the error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fail an upload lookup the prior owner could not answer

During a ring change's cooling-off window an upload the new owner has
not received yet, or holds only as a bare directory, read as NoSuchUpload
when the prior owner's lookup failed. That failure is now returned, so
the client sees a retryable error instead of an upload that is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:03:41 -08:00
github-actions[bot] 5a1b0abc20 docs: regenerate star history chart 2026-11-16 00:37:53 +00:00
b2dd93eac8 admin: support [maintenance.s3_lifecycle] in admin.toml (#12661)
* admin: support [maintenance.s3_lifecycle] in admin.toml

The admin.toml overlay covers vacuum, volume_balance and erasure_coding but
not s3_lifecycle, so the bucket lifecycle job's settings can only be changed
from the web UI and are lost whenever the admin data directory does not
persist. That is the worst combination for this job type: its
meta_log_retention_days knob decides whether bucket rules ever apply to
objects written before the job was enabled, and silently reverting it to the
default makes the rules no-op without any error.

Wire the four admin-side knobs into the existing overlay:

  meta_log_retention_days    retention window the meta-log replay can reach
  walker_interval_minutes    minimum gap between full bucket walks
  cluster_deletes_per_second cluster-wide delete budget
  cluster_deletes_burst      token-bucket burst for that budget

All four are admin config values, not worker values: the engine partition is
computed on the admin side and the delete budget is divided across
execute-capable workers at dispatch time. enabled/retry_limit/
retry_backoff_seconds come for free from the shared section handling.

Tested with TestApplyPluginConfigFromTomlS3Lifecycle, which also pins the
retention=0 case: 0 means unbounded and must survive as an explicit 0 rather
than being treated as unset.

* admin: fix meta_log_retention_days guidance in admin.toml scaffold

Both reviewers caught a real error. `0` is not "unbounded": runShard does

    retentionWindow := cfg.RetentionWindow
    if retentionWindow <= 0 {
        retentionWindow = maxTTL
    }

so zero falls back to the longest rule TTL, which keeps every replay rule in
replay and promotes nothing to the walk set. Recommending 0 to force full
scans was wrong, and so was the claim that pre-existing objects are only
reachable through the walk set -- the cold-start recovery walk covers them
regardless of the retention value.

Describe zero as "no retention info supplied" and tell operators to set the
window the filer meta-log actually retains. The code change is unaffected:
it only wires the four keys into the existing overlay.

* admin: tie s3_lifecycle walk-set scans to walker_interval_minutes in admin.toml

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: show the s3_lifecycle retry defaults in admin.toml

The s3_lifecycle descriptor sets no retry limit or backoff, so a failed
run is not retried and the scheduler's 5 s backoff applies; the scaffold
listed the vacuum values instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: shorten the s3_lifecycle toml section comment

The retention and walker knobs are read by the worker from the admin
values, not computed on the admin side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: cover cluster_deletes_burst in the s3_lifecycle toml test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: check the s3_lifecycle retention zero is a stored int64

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:46:14 -08:00
Chris LuandClaude Opus 5.5 5f7fefadae s3 lifecycle: write the suspended expiration marker before deleting the null version (#12664)
* s3 test: evaluate mutation conditions and serve DeleteEntry in the fake filer

The fake ObjectTransaction now checks each mutation's own condition before
applying it, as the filer does, and reports the failed mutation. ETag clauses
read the stored ETag attribute first, like the filer. DeleteEntry removes the
entry so unrouted delete paths can run against the fake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: write the suspended expiration marker before deleting the null version

A suspended-versioning expiration deleted the null version first and then
wrote the delete marker. When the pointer read or the marker write failed in
between, the retry found no null version, resolved as NOT_FOUND or
VERSION_NOT_LATEST, and never wrote the marker, so an older version became
the latest.

The marker now goes first. The latest pointer outranks the null object, so
the key reads as deleted once the marker lands, and a null delete that fails
after it leaves a noncurrent null version rather than exposing an older one.

The null delete is pinned to the entry read before the marker: on the owner
it carries IF_ENTRY_EQUAL on that read, and off the ring the entry is re-read
and compared by identity first. A null object written after the read is a
newer write and is no longer deleted. When the null version is the one that
passed the expiration checks, a missing or changed entry at that read
resolves the request as STALE_IDENTITY before anything is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: retry a failed routed null delete instead of deleting on the default filer

A routed null delete that failed fell through to the unrouted path, which
reads and deletes on the default filer. That filer may not have the owner's
newer null object yet, so the fallback could delete it without the owner-side
IF_ENTRY_EQUAL guard. The failure now returns RETRY_LATER; the marker is
already written, so the key keeps reading as deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: recheck and delete an unrouted null version under the object write lock

Without a ring owner the identity recheck and the null delete were separate
calls, so a suspended PUT landing between them was deleted. Off the ring
writers take the object write lock, so the recheck and the delete now run
under it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 test: strip quotes from the stored ETag in the fake filer

The filer normalizes both sides of an ETag comparison; the fake now strips
quotes from the stored ETag attribute as well as from the candidate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: retry the null delete when the object lock lookup fails on a routed key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: check the suspended marker against the validated version

A suspended expiration that validated a named version wrote its marker
without comparing the pointer, so a null PUT landing after the checks was
hidden, and deleted too when it landed before the null read. The marker now
compares the latest the way the enabled path does and resolves the request
as VERSION_NOT_LATEST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 test: count the marker's object write lock in the unrouted null delete

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: recheck the attempt deadline after reading the null version

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:30:00 -08:00
Chris LuandClaude Opus 5.5 c09009a74f s3: accept the governance bypass header case-insensitively (#12667)
* s3: accept the governance bypass header case-insensitively

botocore and the AWS CLI send x-amz-bypass-governance-retention: True,
so the exact "true" match ignored the bypass and governance-locked
deletes and retention changes failed with AccessDenied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: test governance bypass with SDK-style header values

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:18:19 -08:00
Chris LuandClaude Opus 5.5 c0509cf499 s3api: evaluate each policy condition against its own values (#12665)
* s3api: normalize a nil policy value to no values

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: evaluate each policy condition against its own values

The process-wide normalized value cache keyed entries by fmt.Sprint of the
value, so ["a", "b"] and ["a b"] (or [] and [""]) shared one entry and a
condition in one policy could be compared against another policy's values.
Normalizing is cheaper than building that key, so drop the cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test that look-alike condition values stay distinct

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:16:27 -08:00
Chris LuandClaude Opus 5.5 63806b7073 s3 lifecycle: bound each LifecycleDelete attempt with its own deadline (#12646)
* s3 lifecycle: bound each LifecycleDelete attempt with its own deadline

Replay and walker deletes used the job context with no request
deadline, so one stalled unary RPC could hold a shard for the whole
job. Each attempt now runs under DeleteTimeout (default 1m), set after
the limiter wait. A timeout while the job is still live is retried like
a transport error and then halts the shard or walk without advancing;
parent cancellation still stops both the attempt and the backoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: admin setting for the delete RPC timeout

Adds delete_timeout_seconds to the S3 Lifecycle admin form and passes
it to both the replay drain and the walker. 0 keeps the 60s default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: describe replay and walker timeouts separately in the help text

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: fail the pass when a replay delete exhausts its attempts

A transport error or attempt timeout that outlived the retries halted
the shard with a nil error, so the job reported success. processMatches
now returns the error (the cursor still holds at the event), and
runShard treats a drain error as a clean stop only when its own context
ended, since an attempt timeout also wraps DeadlineExceeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: test that a replayed LifecycleDelete resolves after a lost reply

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: skip the expiration write once the attempt deadline passed

A worker retries a LifecycleDelete whose attempt timed out, while the
first attempt can still be running on the S3 server. An attempt that
stalled before its marker write would then stack a second delete marker
after the retry wrote one. The gRPC deadline reaches the handler context,
so check it right before the expiration writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: recheck the attempt deadline after the suspended null delete

The null-version delete can block on the owner filer past the attempt
deadline; the worker may have retried and written a marker by then.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: finish the suspended marker once the null version is deleted

Skipping the marker after a successful null delete left an older version
as the latest, and the retry then resolved as a no-op without hiding it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: let a routed delete marker commit only while its latest guard holds

createDeleteMarkerIf passes an optional condition, evaluated on the
.versions directory entry under the object's lock on the owner filer,
and reports a refused commit as errLatestVersionChanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: write the expiration marker as a compare-and-set on the latest pointer

A timed-out attempt can still be running on the S3 server while the
worker's retry writes the marker. The marker commit is now conditioned
on the .versions pointer as read just before it and skipped when the
latest is already a delete marker, so whichever attempt commits second
writes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: resolve the marker as stale when another version became latest

The marker's compare-and-set only covered changes after its own pointer
read, so a version promoted after the expiration checks passed could be
hidden by the marker. The enabled path now passes the validated version
and a conflict retry that finds a different named latest resolves the
request as VERSION_NOT_LATEST.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: resolve a null expiration as stale once a version takes the pointer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: read the marker's latest version the way getLatestObjectVersion does

A pointer names a version only with its file name; an id alone falls back
to the null object, and the null-is-latest signal makes the null version
current. An expiration that validated a named version no longer hides a
null written by a suspended PUT, and a current null under an id-only pointer
now expires instead of resolving as stale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: hold the object write lock for an unrouted expiration marker

Off the ring createDeleteMarkerIf cannot carry the pointer guard, so a PUT
committing between the pointer read and the marker write was hidden. The
read and the write now run under the object write lock that unrouted
writers take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: share transient-error retries between walker and replay deletes (#12649)

* s3 lifecycle: retry only transient LifecycleDelete failures

dispatchWithRetry retried every RPC error except parent cancellation, so
an authentication, permission or argument error spent the whole retry
budget before surfacing. Retry only attempt timeouts and the failures
util.IsTransientError recognizes (Unavailable, ResourceExhausted, network
resets); everything else returns on the first attempt. A nil response
is now an error instead of a nil dereference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: take a delete-rate token for every LifecycleDelete attempt

processMatches waited on the shared limiter once per match, so the
retries behind it ran outside the cluster-wide deletes/sec budget. The
retry loop now waits on the limiter before each attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: give walker deletes the replay retry policy

WalkerDispatcher sent each LifecycleDelete once, so one dropped
connection aborted the bucket's daily walk while the same failure on the
replay path was retried. The walker now goes through deleteWithRetry and
shares its transient-error retries, per-attempt limiter wait and nil
response handling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: retry a DeadlineExceeded the server sends back

A server or proxy can end the RPC with DeadlineExceeded while the
attempt's own deadline is still running. util.IsTransientError rejects
that status, so the delete halted with retries left. It is a timed-out
attempt like the client-side one, so retry it the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: say walker deletes get 3 attempts in the timeout help

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:09:22 -08:00
Chris LuandClaude Opus 5.5 504de9b562 security: refuse to start when per-target gRPC server allowlists are not applied (#12662)
* security: refuse to start when per-target server allowlists are not applied

A component that dials every server with one option ignored
<target>_allowed_server_* keys, so a config that only set those
accepted any CA-signed server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: say which components scope server allowlists per target

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: also catch per-target server allowlists set through WEED_ env vars

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:41:19 -08:00
Chris LuandClaude Opus 5.5 d80e905fc7 security: optional dialed-host check for gRPC server certificates (#12663)
* security: optionally check the dialed host against gRPC server certificates

verify_server_host under [grpc] or a [grpc.<component>] section switches
the client to certificate-and-host verification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: document verify_server_host

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:38:37 -08:00
Chris LuandClaude Opus 5.5 799fd10342 s3 lifecycle: fail over between S3 fronts during a pass (#12647)
* s3 lifecycle: add a LifecycleDelete client that fails over between S3 fronts

When the current front returns Unavailable, the client closes it, marks it
failed for the rest of the pass, picks the next front that passes
checkLifecycleReady and resends the same request there. Callers cut off by
that switch closing their connection resend on the new front. When no front
is left, every later call returns one error naming the fronts tried.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: serve the pass through the failover client

Execute hands the replay drain and the walker one failover client built on
the selected front, reports each switch as job progress, and closes the
current connection when the pass ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: keep failing over until a front serves the resent delete

The resend after a switch went straight to the new front, so a second
lost front ended the call even with a healthy third one, and the walker
has no retry of its own. Resend through the failover loop instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: do not recheck fronts skipped when the pass started

The failover client started with no failed fronts, so losing the selected
front checked the fronts selectS3Front had already skipped again, holding
every delete for another readiness timeout per front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:37:07 -08:00
Chris LuandClaude Opus 5.5 a91b333658 s3 lifecycle: persist daily walk checkpoints and resume them safely (#12650)
* s3 lifecycle: walk checkpoints take each entry's resume position

Versions of one object share a Path, so a checkpoint set from Path after
the first version made a resume skip the rest. The ListFunc now gives
each entry the start value that continues after it, and leaves it empty
on all but an object's last version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: resume a bucket listing where the walk stopped

The filer listing skipped entries with key <= start, but its order is
not key order: each directory emits its .versions groups before its
files, and a directory's children come before a sibling like dir.txt.
Positions are now one (pass, name) frame per directory level, so a
resume seeds each listing and skips exactly what was finished. A version
group is one unit, and a skipped group still keeps its bare null
version out of the second pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: content hash of a walk view

Hashes every non-disabled action of a view and the versioning of their
buckets, so a saved walk position can be tied to the walk it came from:
another rule set, another walk mode, or a bucket that turned versioned
gives another hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: persist daily walk progress and resume it

A walk that failed or was cut short started over on the next pass,
listing again every bucket it had already finished. WalkBuckets now
keeps the finished buckets and each unfinished bucket's position in a
checkpoint file next to the shard cursors, one per shard set, and the
next walk of the same view and shards resumes from it. The record is
saved every 30s and when the walk stops, and cleared when a walk
completes, so the next walk is full again and sees keys added behind
the position; a clear that fails fails the walk rather than leave a
record that would skip buckets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a stuck resumed walk starts over

A bucket that fails at the same place on every pass kept the walk from
completing, so the buckets it had finished were never walked again and
their due objects waited forever. A resumed walk that fails again
without finishing anything clears its checkpoint, and the next walk is
full. A canceled walk keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: do not resume a walk checkpoint left for a week

A checkpoint is cleared only by a later walk of the same shard set, so a
set that stopped walking, such as a one-off per-shard walk, left its
record behind, and a walk of that set much later would skip buckets
finished long before. Records now carry their save time and are not
resumed after seven days; a walk that keeps retrying saves on every
attempt and stays fresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a failed walk without progress leaves its checkpoint alone

A pass canceled while it read the checkpoint failed the read, then
saved its own empty progress over the record it never loaded, so the
next pass started every bucket again. A failed walk that finished
nothing has nothing new to record and no longer writes; the stuck
resume reset still clears.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: space out walk checkpoint saves after a failed one

The save time advanced only on success, so once the filer refused a
periodic save every following entry tried again and logged another
warning. The interval now counts from the last attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a walk checkpoint save that errors may still be on disk

A save whose reply was lost left onDisk false, so a walk that then
completed skipped the clear and the next walk resumed from the stale
record instead of walking everything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: keep a stalled walk checkpoint for a day

A resumed walk that failed again without progress dropped its record
right away, so an outage spanning two attempts restarted the whole
walk. Treat the walk as stuck only once its record has not advanced
for a day.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a resumed walk counts its earlier buckets as walked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: replay a resumed recovery walk from the walk that began it

A recovery or cold-start pass rewinds replay to runNow - maxTTL. When the
walk resumed a checkpoint, its finished buckets were listed in an earlier
attempt, so an object there that was not yet due then and whose write is
now older than maxTTL was neither expired by the walk nor replayed.

The checkpoint now keeps the start of the walk that began it, WalkBuckets
returns that time (its own start for a fresh walk), and runShard floors
the recovery rewind and the cold-start replay at it. A record without a
start is not resumed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: a cold start that resumed a walk replays on the next pass

The pass's shared subscription starts at runNow - maxTTL for a shard
without a cursor, before its walk reports an earlier start, so flooring
the cold-start drain at the walk start could not deliver the older
events. Such a shard now saves its cursor at the walk start minus maxTTL
and returns, like the recovery branch, and the next pass replays the
window from that cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: test that a cursor below the floor opens the next subscription

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3 lifecycle: test the cold-start replay across two Run passes

A cold start whose walk resumed an earlier attempt sees an older event
only on the next pass. The test runs Run twice against a filer that
serves events past the requested floor, with a later in-window event
that would otherwise move the cursor past the older one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:35:49 -08:00
4f70ad015e mount: fail the write when the swap file chunk cannot be created (#12655)
* mount: fail the write when the swap file chunk cannot be created

#7957 added a nil check after NewSwapFileChunk so a failed swap file
creation returns an error instead of panicking. The result was assigned
to pageChunk, a PageChunk interface, before the check, and an interface
holding a nil *SwapFileChunk is not nil, so the check never fired:
SaveDataAt stored the nil chunk and panicked in WriteDataAt.

Check the *SwapFileChunk before converting it. The new test points the
swap directory below a regular file; on master it panics in
SwapFileChunk.WriteDataAt.

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>

* mount: grow the file only after its write is buffered

Write set the new size, times, pending append offset and uncommitted
bytes before AddPage. When AddPage failed (now that a swap file chunk
that cannot be created returns an error), the write was reported as
failed but the larger size stayed on the handle's entry, so the next
flush published it with a hole where the data should be.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: report a partly buffered write as a short write

PageWriter.AddPage fills one chunk at a time, so when a later chunk
cannot be created the earlier chunks already hold their bytes. Return
how much was buffered, and let Write grow the size and times over that
prefix and report it, instead of failing the whole write while the
prefix still reaches the next flush.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: report the bytes a failed copy_file_range already buffered

A streaming copy whose page fails partway returned an error even though
earlier pages, or the start of the failing one, were already buffered and
would reach the next flush with the destination size left short. Count
the buffered bytes, grow the destination over them, and return them as a
short copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: free the copy test's destination pages

The buffered memory chunk counts toward the process-wide memory chunk
ceiling, so repeated runs of the test pushed later ones onto the
unusable swap directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: count only the bytes a swap chunk stored

A swap chunk whose file write fails stores a prefix or nothing, but
SaveDataAt returned no error and AddPage counted the whole span as
buffered. SaveDataAt now reports the short write, and AddPage passes the
stored count up so a write is never acknowledged past it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fail a partly buffered writeback write

Kernel writeback ignores the count in a WRITE reply, so a short write
there drops the unbuffered rest without an error. A write flagged as
page-cache writeback now keeps its buffered prefix but returns the
error, which the kernel reports on fsync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: anant <170962632+antcybersec@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:34:43 -08:00
github-actions[bot] ddd3b3666f docs: regenerate star history chart 2026-11-15 00:34:44 +00:00
Chris LuandClaude Opus 5.5 cdb01f8150 install.sh: add --enterprise (#12660)
* install.sh: offer the vector engine on linux only

Releases build weed-vector for linux amd64/arm64 only, so --component vector
on darwin or windows downloaded a missing asset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* install.sh: add --enterprise

Installs from seaweedfs/artifactory: weed-enterprise-<os>_<arch>[_large_disk],
weed-volume-enterprise[_large_disk], weed-worker-enterprise and
weed-vector-enterprise. The latest tag skips vfs-* releases, and the Rust
volume server is linux-only there, so --component all skips it elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* Revert "install.sh: offer the vector engine on linux only"

Releases after 4.53 publish weed-vector for darwin and windows too
(rust-vector-platforms.yml).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* install.sh: Enterprise vector engine is linux-only

Enterprise releases publish weed-vector-enterprise for linux amd64/arm64;
open-source releases keep their darwin and windows engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test: installer --enterprise asset names, platforms and latest tag

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* install.sh: Enterprise latest is the newest plain version tag

artifactory also releases previews and a dev build, and a prerelease such
as kvcache-filer-native-v0.1.0-preview.1 sits in the release list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* README: show passing --enterprise through bash -s --

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* install.sh: the open-source weed for windows is a .zip too

Releases publish windows_amd64[_large_disk].zip, so asking for a .tar.gz
404s on every Windows host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* install.sh: install the windows weed as weed.exe

weed-volume and weed-vector keep their .exe on Windows; weed lost it, so
cmd and PowerShell could not run the installed binary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* install.sh: suggest weed-volume only when it was installed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:50:18 -08:00
847 changed files with 76458 additions and 7452 deletions

No files matched your search

+3 -1
View File
@@ -28,7 +28,9 @@ runs:
# Cosign 3 also defaults to --use-signing-config, which insists on a
# bundle for its output; turning it off falls back to the default
# Fulcio and Rekor URLs, which is all the .sig layout ever used.
cosign sign --yes --recursive \
# --recursive signs every platform manifest in every registry, which
# outlasts the 3m default timeout when Fulcio or Rekor is slow.
cosign sign --yes --recursive --timeout 15m \
--new-bundle-format=false --use-signing-config=false \
$IMAGES
+92 -21
View File
@@ -22,6 +22,16 @@ CHART = ROOT / "k8s/charts/seaweedfs"
SECTIONS = ("jwt.signing", "jwt.signing.read", "jwt.filer_signing", "jwt.filer_signing.read")
KEYS = {section: f"active-{index}" for index, section in enumerate(SECTIONS)}
ESCAPED_HEADER = '["jw\\u0074".signing]\nkey = "existing"'
# No workload is needed to exercise Helm's real lookup and update.
RELEASE_SETTINGS = (
"master.enabled=false", "volume.enabled=false", "filer.enabled=false",
"global.seaweedfs.createClusterRole=false",
"global.seaweedfs.securityConfig.jwtSigning.volumeWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.volumeRead=true",
"global.seaweedfs.securityConfig.jwtSigning.filerWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.filerRead=true",
)
CONFIGMAP_CHART = ("seaweedfs", "--repo", "https://seaweedfs.github.io/seaweedfs/helm", "--version", "4.54.0")
def run(*args):
@@ -77,8 +87,7 @@ def fixtures():
def check_generated(value):
decoded = base64.b64decode(value, validate=True).decode("ascii")
assert len(decoded) == 10 and decoded.isascii() and decoded.isalnum(), "invalid generated JWT key"
assert len(value) == 64 and value.isascii() and value.isalnum(), "invalid generated JWT key"
def check_helpers(helm, reference_helm):
@@ -147,20 +156,11 @@ def check_upgrades(helm, context):
legacy = "seaweedfs-security-config"
kubectl = ["kubectl", "--context", context, "-n", namespace]
release_args = ["jk", str(CHART), "--kube-context", context, "-n", namespace]
# No workload is needed to exercise Helm's real ConfigMap lookup and update.
for setting in (
"master.enabled=false", "volume.enabled=false", "filer.enabled=false",
"global.seaweedfs.createClusterRole=false",
"global.seaweedfs.securityConfig.jwtSigning.volumeWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.volumeRead=true",
"global.seaweedfs.securityConfig.jwtSigning.filerWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.filerRead=true",
):
for setting in RELEASE_SETTINGS:
release_args += ["--set", setting]
def stored():
cm = json.loads(run(*kubectl, "get", "configmap", current, "-o", "json"))
return keys(cm["data"]["security.toml"])
return secret_keys(kubectl, current)
def upgrade():
run(helm, "upgrade", *release_args)
@@ -168,8 +168,8 @@ def check_upgrades(helm, context):
def patch(raw):
# Seed previous-release content without taking Helm 4's SSA ownership.
run(*kubectl, "patch", "configmap", current, "--type=merge", "--field-manager=helm", "-p",
json.dumps({"data": {"security.toml": raw}}))
run(*kubectl, "patch", "secret", current, "--type=merge", "--field-manager=helm", "-p",
json.dumps({"stringData": {"security.toml": raw}}))
run(*kubectl, "create", "namespace", namespace)
try:
@@ -194,17 +194,24 @@ def check_upgrades(helm, context):
assert upgrade() == actual, f"{name}: subsequent upgrade changed a key"
print(f"PASS upgrade: {name}")
# Migration from the old chart name, followed by precedence of the current name.
# Migration from the ConfigMaps of earlier chart versions, then precedence of the Secret.
configmap_raw = "\n".join(f'[{section}]\nkey = "configmap-{index}"'
for index, section in enumerate(SECTIONS))
run(*kubectl, "create", "configmap", current, "--from-literal=security.toml=" + configmap_raw)
run(*kubectl, "delete", "secret", current)
assert upgrade() == keys(configmap_raw), "ConfigMap keys were not preserved"
print("PASS upgrade: ConfigMap migration")
legacy_raw = "\n".join(f'[{section}]\nkey = "legacy-{index}"'
for index, section in enumerate(SECTIONS))
run(*kubectl, "create", "configmap", legacy, "--from-literal=security.toml=" + legacy_raw)
run(*kubectl, "delete", "configmap", current)
run(*kubectl, "create", "configmap", legacy, "--from-literal=security.toml=" + legacy_raw)
run(*kubectl, "delete", "secret", current)
assert upgrade() == keys(legacy_raw), "legacy ConfigMap keys were not preserved"
print("PASS upgrade: legacy ConfigMap migration")
current_raw = next(fixtures())[1]
patch(current_raw)
assert upgrade() == keys(current_raw), "legacy ConfigMap overrode current ConfigMap"
print("PASS upgrade: current ConfigMap takes precedence")
assert upgrade() == keys(current_raw), "legacy ConfigMap overrode the Secret"
print("PASS upgrade: Secret takes precedence")
patch(ESCAPED_HEADER)
try:
@@ -213,13 +220,76 @@ def check_upgrades(helm, context):
assert "unsupported quoted section header" in error.stderr, error.stderr
else:
raise AssertionError("unsupported quoted header silently rotated its key")
assert keys(run(*kubectl, "get", "configmap", current, "-o",
"jsonpath={.data.security\\.toml}"))["jwt.signing"] == "existing"
assert stored()["jwt.signing"] == "existing"
print("PASS upgrade: unsupported quoted header leaves stored key untouched")
finally:
run(*kubectl, "delete", "namespace", namespace, "--wait=false")
def secret_keys(kubectl, name):
secret = json.loads(run(*kubectl, "get", "secret", name, "-o", "json"))
return keys(base64.b64decode(secret["data"]["security.toml"]).decode())
def check_configmap_release_upgrade(helm, context):
namespace = "jwt-key-migrate-" + uuid.uuid4().hex[:8]
name = "jk-seaweedfs-security-config"
kubectl = ["kubectl", "--context", context, "-n", namespace]
common = ["--kube-context", context, "-n", namespace]
for setting in RELEASE_SETTINGS:
common += ["--set", setting]
upgrade = ["upgrade", "jk", str(CHART), *common, "--set", "master.enabled=true"]
def refuse_partitioned(stage):
try:
run(helm, *upgrade, "--set", "master.updatePartition=1")
except subprocess.CalledProcessError as error:
assert "updatePartition=0" in error.stderr, error.stderr
else:
raise AssertionError(f"partitioned upgrade removed the ConfigMap ({stage})")
def exists(kind):
return run(*kubectl, "get", kind, name, "--ignore-not-found", "-o", "name").strip()
run(*kubectl, "create", "namespace", namespace)
try:
run(helm, "install", "jk", *CONFIGMAP_CHART, *common)
before = keys(run(*kubectl, "get", "configmap", name, "-o", "jsonpath={.data.security\\.toml}"))
assert set(before) == set(SECTIONS), "ConfigMap chart omitted a JWT section"
refuse_partitioned("ConfigMap release")
print("PASS upgrade: partitioned upgrade from the ConfigMap chart is refused")
# Fail an upgrade after Helm created the Secret, so it never removes the ConfigMap.
run(*kubectl, "create", "quota", "no-statefulsets", "--hard=count/statefulsets.apps=0")
try:
run(helm, *upgrade)
except subprocess.CalledProcessError as error:
assert "quota" in error.stderr, error.stderr
else:
raise AssertionError("upgrade was not blocked by the quota")
run(*kubectl, "delete", "quota", "no-statefulsets")
assert exists("secret") and exists("configmap"), "failed upgrade did not leave both objects"
refuse_partitioned("retry after a failed upgrade")
print("PASS upgrade: partitioned retry after a failed migration is refused")
run(helm, "upgrade", "jk", str(CHART), *common)
assert secret_keys(kubectl, name) == before, "upgrade from the ConfigMap chart changed a key"
assert not exists("configmap"), "upgrade left the ConfigMap behind"
print("PASS upgrade: ConfigMap chart release moves its keys to the Secret")
# The unprefixed legacy name can belong to another release in the namespace.
other = "seaweedfs-security-config"
run(*kubectl, "create", "configmap", other, '--from-literal=security.toml=[jwt.signing]\nkey = "other"')
run(*kubectl, "annotate", "configmap", other, "meta.helm.sh/release-name=other",
"meta.helm.sh/release-namespace=" + namespace)
run(helm, *upgrade, "--set", "master.updatePartition=1")
assert secret_keys(kubectl, name) == before, "another release's ConfigMap changed a key"
assert run(*kubectl, "get", "configmap", other, "-o", "name").strip(), "removed another release's ConfigMap"
print("PASS upgrade: another release's legacy ConfigMap does not block a partitioned upgrade")
finally:
run(*kubectl, "delete", "namespace", namespace, "--wait=false")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--helm", default="helm")
@@ -230,6 +300,7 @@ def main():
check_helpers(args.helm, args.reference_helm)
if args.context:
check_upgrades(args.helm, args.context)
check_configmap_release_upgrade(args.helm, args.context)
if __name__ == "__main__":
+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.3
uses: github/codeql-action/init@v4.39.4
# 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.3
uses: github/codeql-action/autobuild@v4.39.4
# ℹ️ 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.3
uses: github/codeql-action/analyze@v4.39.4
+1 -1
View File
@@ -434,7 +434,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.3
uses: github/codeql-action/upload-sarif@v4.39.4
if: always()
with:
sarif_file: trivy-results.sarif
@@ -515,7 +515,7 @@ jobs:
- name: Upload Trivy scan results to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v4.39.3
uses: github/codeql-action/upload-sarif@v4.39.4
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
+98 -21
View File
@@ -37,7 +37,7 @@ jobs:
with:
version: v3.18.4
- uses: actions/setup-go@v6
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
@@ -104,8 +104,51 @@ jobs:
grep -A 4 "^ strategy:" /tmp/s3-rollout.yaml | grep -q "maxUnavailable: 0"
grep -A 4 "^ strategy:" /tmp/s3-rollout.yaml | grep -q "type: RollingUpdate"
grep -A 5 "^ lifecycle:" /tmp/s3-rollout.yaml | grep -q -- "- sleep"
test "$(grep -c -- '-preStopSeconds' /tmp/s3-rollout-defaults.yaml)" -eq 0
echo "S3 rollout settings render correctly"
echo "=== Testing S3 preStopSeconds ==="
if helm template test $CHART_DIR --show-only templates/s3/s3-deployment.yaml \
--set s3.enabled=true --set s3.preStopSeconds=20 > /tmp/s3-prestop-short.yaml 2>&1; then
echo "FAIL: s3.preStopSeconds=20 rendered with the default 10s grace period"; exit 1
fi
grep -q "must be at least 35" /tmp/s3-prestop-short.yaml
helm template test $CHART_DIR --show-only templates/s3/s3-deployment.yaml \
--set s3.enabled=true --set s3.preStopSeconds=20 \
--set s3.terminationGracePeriodSeconds=35 > /tmp/s3-prestop.yaml
grep -q -- "-preStopSeconds=20 " /tmp/s3-prestop.yaml
grep -q "terminationGracePeriodSeconds: 35$" /tmp/s3-prestop.yaml
helm template test $CHART_DIR --show-only templates/filer/filer-statefulset.yaml \
--set filer.s3.enabled=true > /tmp/filer-s3-prestop-defaults.yaml
test "$(grep -c -- '-s3.preStopSeconds' /tmp/filer-s3-prestop-defaults.yaml)" -eq 0
grep -q "terminationGracePeriodSeconds: 60$" /tmp/filer-s3-prestop-defaults.yaml
helm template test $CHART_DIR --show-only templates/filer/filer-statefulset.yaml \
--set filer.s3.enabled=true --set filer.s3.preStopSeconds=20 > /tmp/filer-s3-prestop.yaml
grep -q -- "-s3.preStopSeconds=20 " /tmp/filer-s3-prestop.yaml
grep -q "terminationGracePeriodSeconds: 80$" /tmp/filer-s3-prestop.yaml
helm template test $CHART_DIR --show-only templates/all-in-one/all-in-one-deployment.yaml \
--set allInOne.enabled=true --set allInOne.s3.enabled=true > /tmp/aio-s3-prestop-defaults.yaml
test "$(grep -c -- '-s3.preStopSeconds' /tmp/aio-s3-prestop-defaults.yaml)" -eq 0
grep -q "terminationGracePeriodSeconds: 60$" /tmp/aio-s3-prestop-defaults.yaml
helm template test $CHART_DIR --show-only templates/all-in-one/all-in-one-deployment.yaml \
--set allInOne.enabled=true --set allInOne.s3.enabled=true \
--set s3.preStopSeconds=20 > /tmp/aio-s3-prestop.yaml
grep -q -- "-s3.preStopSeconds=20 " /tmp/aio-s3-prestop.yaml
grep -q "terminationGracePeriodSeconds: 80$" /tmp/aio-s3-prestop.yaml
helm template test $CHART_DIR --show-only templates/all-in-one/all-in-one-deployment.yaml \
--set allInOne.enabled=true --set allInOne.s3.enabled=true \
--set s3.preStopSeconds=20 --set allInOne.s3.preStopSeconds=0 > /tmp/aio-s3-prestop-off.yaml
test "$(grep -c -- '-s3.preStopSeconds' /tmp/aio-s3-prestop-off.yaml)" -eq 0
grep -q "terminationGracePeriodSeconds: 60$" /tmp/aio-s3-prestop-off.yaml
helm template test $CHART_DIR --show-only templates/all-in-one/all-in-one-deployment.yaml \
--set allInOne.enabled=true --set allInOne.s3.enabled=true \
--set s3.preStopSeconds=20 --set allInOne.s3.preStopSeconds=25 > /tmp/aio-s3-prestop-own.yaml
grep -q -- "-s3.preStopSeconds=25 " /tmp/aio-s3-prestop-own.yaml
grep -q "terminationGracePeriodSeconds: 85$" /tmp/aio-s3-prestop-own.yaml
echo "S3 preStopSeconds renders correctly"
echo "=== Testing the S3 config checksum is stable across renders ==="
# s3-secret.yaml keeps its generated keys with lookup. Hashing the rendered
# Secret drew new keys for the checksum whenever lookup found nothing (on
@@ -216,6 +259,40 @@ jobs:
grep -q "security-config" /tmp/security.yaml
echo "Security configuration renders correctly"
echo "=== Testing volume server HTTPS ==="
awk '/^ *\[https.client\]$/{f=1;next} /^ *\[/{f=0} f' /tmp/security.yaml | grep -q 'enabled = false'
helm template test $CHART_DIR \
--set global.seaweedfs.enableSecurity=true \
--set global.seaweedfs.volumeHttps.enabled=true \
--set volumes.hot.replicas=1 \
> /tmp/volume-https.yaml
awk '/^ *\[https.client\]$/{f=1;next} /^ *\[/{f=0} f' /tmp/volume-https.yaml > /tmp/volume-https-client.txt
grep -q 'enabled = true' /tmp/volume-https-client.txt
grep -q 'cert = "/usr/local/share/ca-certificates/client/tls.crt"' /tmp/volume-https-client.txt
grep -q 'ca = "/usr/local/share/ca-certificates/ca/tls.crt"' /tmp/volume-https-client.txt
awk '/^ *\[https.volume\]$/{f=1;next} /^ *\[/{f=0} f' /tmp/volume-https.yaml \
| grep -q 'cert = "/usr/local/share/ca-certificates/volume/tls.crt"'
grep -q "'\*.test-seaweedfs-volume.default'" /tmp/volume-https.yaml
grep -q "'\*.test-seaweedfs-volume-hot.default'" /tmp/volume-https.yaml
test "$(grep -c 'scheme: HTTPS' /tmp/volume-https.yaml)" -eq 4
test "$(grep -c 'checksum/volume-https:' /tmp/volume-https.yaml)" -eq 4
if grep -q 'checksum/volume-https' /tmp/security.yaml; then
echo "FAIL: the volume HTTPS rollout annotation should only render while the option is on"
exit 1
fi
if helm template test $CHART_DIR --set global.seaweedfs.volumeHttps.enabled=true > /dev/null 2>/tmp/volume-https-nosec.err; then
echo "FAIL: volumeHttps without enableSecurity should fail to render"
exit 1
fi
grep -q "requires global.seaweedfs.enableSecurity" /tmp/volume-https-nosec.err
if helm template test $CHART_DIR --set global.seaweedfs.enableSecurity=true \
--set global.seaweedfs.volumeHttps.enabled=true --set allInOne.enabled=true > /dev/null 2>/tmp/volume-https-aio.err; then
echo "FAIL: volumeHttps with allInOne should fail to render"
exit 1
fi
grep -q "not supported with allInOne" /tmp/volume-https-aio.err
echo "Volume server HTTPS renders [https.volume], [https.client], certificate names, HTTPS probes and rollout annotations"
echo "=== Testing secure bucket-creation hook certificate mounts ==="
helm template test $CHART_DIR \
--show-only templates/shared/post-install-bucket-hook.yaml \
@@ -317,9 +394,9 @@ jobs:
def docs(manifest):
return [d for d in yaml.safe_load_all(manifest) if d]
def configmap(manifest, name):
def security_config(manifest, name):
for d in docs(manifest):
if d.get("kind") == "ConfigMap" and d["metadata"]["name"] == name:
if d.get("kind") == "Secret" and d["metadata"]["name"] == name:
return d
return None
@@ -344,13 +421,13 @@ jobs:
# security-related; preserve that so this PR is non-breaking on
# existing installs.
out = render({})
if configmap(out, "test-seaweedfs-security-config") is not None:
failed.append("defaults: security ConfigMap should not render")
if security_config(out, "test-seaweedfs-security-config") is not None:
failed.append("defaults: security Secret should not render")
else:
print("defaults: no security-config ConfigMap (unchanged)")
print("defaults: no security-config Secret (unchanged)")
# Case 2: filerWrite=true alone is the documented opt-in for
# the Admin UI Users tab. Configmap must render with
# the Admin UI Users tab. The Secret must render with
# [jwt.filer_signing] and NO [grpc.*] sections (cert paths
# only exist with mTLS).
out = render({
@@ -360,11 +437,11 @@ jobs:
# refuses to bind without authentication.
"admin.secret.adminPassword": "ci-admin-password",
})
cm = configmap(out, "test-seaweedfs-security-config")
cm = security_config(out, "test-seaweedfs-security-config")
if cm is None:
failed.append("filerWrite=true: security ConfigMap missing")
failed.append("filerWrite=true: security Secret missing")
else:
toml = cm["data"]["security.toml"]
toml = cm["stringData"]["security.toml"]
if "[jwt.filer_signing]" not in toml:
failed.append("filerWrite=true: security.toml missing [jwt.filer_signing]")
if "[grpc" in toml:
@@ -372,7 +449,7 @@ jobs:
if "[jwt.filer_signing]" in toml and "[grpc" not in toml:
print("filerWrite=true: security.toml has [jwt.filer_signing], no [grpc.*]")
# Case 3: filer + admin pods must MOUNT the security ConfigMap
# Case 3: filer + admin pods must MOUNT the security Secret
# under filerWrite=true so the JWT key reaches both processes.
# Cert volumes must NOT be present (no mTLS).
for wl in ("test-seaweedfs-filer", "test-seaweedfs-admin"):
@@ -392,11 +469,11 @@ jobs:
# with both [jwt.signing] and [grpc.*]. Guards against the
# decoupling change accidentally regressing the mTLS path.
out = render({"global.seaweedfs.enableSecurity": "true"})
cm = configmap(out, "test-seaweedfs-security-config")
cm = security_config(out, "test-seaweedfs-security-config")
if cm is None:
failed.append("enableSecurity=true: security ConfigMap missing")
failed.append("enableSecurity=true: security Secret missing")
else:
toml = cm["data"]["security.toml"]
toml = cm["stringData"]["security.toml"]
missing = [s for s in ("[jwt.signing]", "[grpc.master]") if s not in toml]
if missing:
failed.append(f"enableSecurity=true: security.toml missing {missing}")
@@ -413,8 +490,8 @@ jobs:
except subprocess.CalledProcessError as e:
failed.append(f"{null_path}=null: render failed: {e.output[:200] if e.output else e}")
continue
if configmap(out, "test-seaweedfs-security-config") is not None:
failed.append(f"{null_path}=null: should not render configmap")
if security_config(out, "test-seaweedfs-security-config") is not None:
failed.append(f"{null_path}=null: should not render the security Secret")
else:
print(f"{null_path}=null: render tolerates explicit null")
@@ -518,16 +595,16 @@ jobs:
mount = next((m for m in pod["containers"][0].get("volumeMounts", []) if m["name"] == "security-config"), None)
# The file has to land on one of weed's config search paths, so
# the target matters as much as the volume itself - and a volume
# of that name backed by anything but the chart's ConfigMap
# of that name backed by anything but the chart's Secret
# leaves `weed shell` without the signing key just the same.
target = ("/etc/seaweedfs/security.toml", "security.toml")
configmap = "test-seaweedfs-security-config"
secret = "test-seaweedfs-security-config"
if vol is None or mount is None:
failed.append("filerWrite=true: bucket hook does not mount security-config (s3.configure would fail)")
elif (mount.get("mountPath"), mount.get("subPath")) != target:
failed.append(f"filerWrite=true: bucket hook mounts security-config as {mount}")
elif vol.get("configMap", {}).get("name") != configmap:
failed.append(f"filerWrite=true: security-config is not backed by the {configmap} ConfigMap: {vol}")
elif vol.get("secret", {}).get("secretName") != secret:
failed.append(f"filerWrite=true: security-config is not backed by the {secret} Secret: {vol}")
else:
print("filerWrite=true: bucket hook mounts security-config at /etc/seaweedfs/security.toml")
@@ -2033,7 +2110,7 @@ jobs:
"--set", "admin.enabled=true", "--set", "admin.secret.adminPassword=ci",
"--set", "cosi.enabled=true", "--set", "networkPolicy.enabled=true",
"--set", "volumes.dc2.replicas=1",
# render the security ConfigMap without its generated jwt key
# render the security Secret without its generated jwt key
"--set", "global.seaweedfs.enableSecurity=true",
"--set", "global.seaweedfs.securityConfig.jwtSigning.volumeWrite=false",
]
+1 -1
View File
@@ -48,7 +48,7 @@ jobs:
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: actions/setup-python@v6
- uses: actions/setup-python@v7
with:
python-version: '3.13'
- uses: actions/cache/restore@v6
@@ -168,9 +168,6 @@ jobs:
- name: Run Rust unit tests
run: cd seaweed-volume && cargo test
- name: Run Rust unit tests (redb experimental cursor)
run: cd seaweed-volume && cargo test --features redb-experimental-cursor --lib storage::needle_map
rust-unit-tests-windows:
name: Rust Unit Tests (Windows)
runs-on: windows-latest
@@ -208,9 +205,6 @@ jobs:
- name: Run Rust unit tests
run: cd seaweed-volume && cargo test
- name: Run Rust unit tests (redb experimental cursor)
run: cd seaweed-volume && cargo test --features redb-experimental-cursor --lib storage::needle_map
rust-integration-tests:
name: Rust Integration Tests
runs-on: ubuntu-24.04
@@ -0,0 +1,74 @@
name: "S3 listing study tests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/listing_study/**'
- '.github/workflows/s3-listing-study-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/listing_study/**'
- '.github/workflows/s3-listing-study-tests.yml'
concurrency:
group: ${{ github.event.pull_request.number || github.ref }}/s3-listing-study-tests
cancel-in-progress: true
permissions:
contents: read
jobs:
listing-study:
name: s3-listing-study tools and strategies
runs-on: ubuntu-24.04
timeout-minutes: 40
defaults:
run:
working-directory: test/s3/listing_study
steps:
- name: Check out code
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Cache pinned listing tools
uses: actions/cache@v6
with:
path: test/s3/listing_study/.work/tools
key: listing-study-tools-${{ runner.os }}-${{ hashFiles('test/s3/listing_study/Makefile', 'test/s3/listing_study/install_tools.py') }}
- name: Build weed and install the study's pinned tools
run: make build-weed tools
- name: Run the listing study against SeaweedFS
timeout-minutes: 15
run: make test
- name: Show logs on failure
if: failure()
run: |
tail -200 .work/weed.log || true
- name: Upload results
if: always()
uses: actions/upload-artifact@v7
with:
name: s3-listing-study-results
path: |
test/s3/listing_study/.work/run/results.json
test/s3/listing_study/.work/weed.log
retention-days: 14
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ['3.9', '3.11', '3.12']
python-version: ['3.10', '3.11', '3.12']
steps:
- name: Checkout code
+11 -1
View File
@@ -68,7 +68,15 @@ jobs:
with:
java-version: '17'
distribution: 'temurin'
cache: ${{ runner.environment == 'github-hosted' && 'maven' || '' }}
- name: Cache suite Maven dependencies
if: runner.environment == 'github-hosted'
uses: actions/cache@v6
with:
path: ~/.m2/repository
key: snowflake-s3compat-m2-${{ hashFiles('test/s3/snowflake/run.sh') }}
restore-keys: |
snowflake-s3compat-m2-
- name: Install SeaweedFS
run: |
@@ -78,6 +86,8 @@ jobs:
- name: Run Snowflake S3Compat API tests
timeout-minutes: 20
env:
MAVEN_ARGS: -ntp -s ${{ github.workspace }}/test/s3/snowflake/maven-settings.xml
run: |
# Starts weed server, creates the buckets/objects the suite needs,
# clones the upstream suite, and runs mvn -Dtest=S3CompatApiTest.
+6
View File
@@ -684,6 +684,12 @@ jobs:
pull() { for i in 1 2 3; do docker pull "$1" && return 0; sleep 15; done; return 1; }
pull apache/spark:3.5.1
- name: Cache Iceberg jars
uses: actions/cache@v6
with:
path: ~/.cache/seaweedfs-test-jars
key: iceberg-jars-${{ hashFiles('test/s3tables/catalog_spark/setup_test.go') }}
- name: Run go mod tidy
run: go mod tidy
@@ -0,0 +1,57 @@
name: "S3 Tigris Compatibility Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/server/filer_server_handlers_*.go'
- 'test/s3/tigris_compat/**'
- '.github/workflows/s3-tigris-compat-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/server/filer_server_handlers_*.go'
- 'test/s3/tigris_compat/**'
- '.github/workflows/s3-tigris-compat-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:
s3-tigris-compat-tests:
name: s3-api-compat-tests (Tigris)
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Run s3-api-compat-tests
working-directory: test/s3/tigris_compat
run: make test
- name: Show server log on failure
if: failure()
working-directory: test/s3/tigris_compat
run: tail -200 weed-test.log || true
- name: Upload report
if: always()
uses: actions/upload-artifact@v7
with:
name: s3-tigris-compat-results
path: test/s3/tigris_compat/results.json
if-no-files-found: ignore
retention-days: 7
+4 -4
View File
@@ -50,7 +50,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: '3.9'
python-version: '3.10'
- name: Clone s3-tests
run: |
@@ -410,7 +410,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: '3.9'
python-version: '3.10'
- name: Clone s3-tests
run: |
@@ -581,7 +581,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: '3.9'
python-version: '3.10'
- name: Clone s3-tests
run: |
@@ -810,7 +810,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: '3.9'
python-version: '3.10'
- name: Clone s3-tests
run: |
@@ -6,12 +6,16 @@ on:
paths:
- 'telemetry/**'
- 'weed/telemetry/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/telemetry-integration.yml'
pull_request:
branches: [ master ]
paths:
- 'telemetry/**'
- 'weed/telemetry/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/telemetry-integration.yml'
concurrency:
@@ -56,8 +56,12 @@ jobs:
- name: Setup Caddy
run: |
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=amd64" -o caddy
chmod +x caddy
CADDY_VERSION=2.11.9
base="https://github.com/caddyserver/caddy/releases/download/v${CADDY_VERSION}"
curl -fsSLO "${base}/caddy_${CADDY_VERSION}_linux_amd64.tar.gz"
curl -fsSLO "${base}/caddy_${CADDY_VERSION}_checksums.txt"
grep " caddy_${CADDY_VERSION}_linux_amd64.tar.gz$" "caddy_${CADDY_VERSION}_checksums.txt" | sha512sum -c -
tar -xzf "caddy_${CADDY_VERSION}_linux_amd64.tar.gz" caddy
./caddy version
echo "{
auto_https disable_redirects
+2
View File
@@ -67,6 +67,8 @@ Download the latest binary from the [releases](https://github.com/seaweedfs/seaw
curl -fsSL https://raw.githubusercontent.com/seaweedfs/seaweedfs/master/install.sh | bash
```
For SeaweedFS Enterprise binaries, pass `--enterprise` to the script: `... | bash -s -- --enterprise`.
Then start a ready-to-use S3 object store:
```bash
+51 -52
View File
@@ -5,7 +5,7 @@ go 1.26.6
require (
cloud.google.com/go v0.123.0 // indirect
cloud.google.com/go/pubsub v1.51.1
cloud.google.com/go/storage v1.67.0
cloud.google.com/go/storage v1.69.0
github.com/Shopify/sarama v1.38.1
github.com/aws/aws-sdk-go v1.55.8
github.com/beorn7/perks v1.0.1 // indirect
@@ -84,24 +84,24 @@ require (
github.com/xdg-go/scram v1.2.0
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.etcd.io/etcd/api/v3 v3.7.1
go.etcd.io/etcd/client/v3 v3.7.1
go.etcd.io/etcd/api/v3 v3.7.3
go.etcd.io/etcd/client/v3 v3.7.3
go.mongodb.org/mongo-driver v1.17.9
go.opencensus.io v0.24.0 // indirect
gocloud.dev v0.47.0
gocloud.dev/pubsub/natspubsub v0.46.0
gocloud.dev v0.49.0
gocloud.dev/pubsub/natspubsub v0.49.0
gocloud.dev/pubsub/rabbitpubsub v0.47.0
golang.org/x/crypto v0.58.0
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
golang.org/x/image v0.46.0
golang.org/x/net v0.62.0
golang.org/x/oauth2 v0.37.0
golang.org/x/sys v0.49.0
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.51.0 // indirect
golang.org/x/tools v0.52.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.310.0
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 // indirect
google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b // indirect
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089
google.golang.org/protobuf v1.36.12
gopkg.in/inf.v0 v0.9.1 // indirect
@@ -123,10 +123,10 @@ require (
github.com/apache/iceberg-go v0.7.0
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/aws/aws-sdk-go-v2 v1.47.7
github.com/aws/aws-sdk-go-v2/config v1.33.6
github.com/aws/aws-sdk-go-v2/credentials v1.20.6
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.1
github.com/aws/aws-sdk-go-v2 v1.48.0
github.com/aws/aws-sdk-go-v2/config v1.33.9
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
github.com/cespare/xxhash/v2 v2.3.0
github.com/cognusion/imaging v1.0.4
github.com/fluent/fluent-logger-golang v1.10.1
@@ -145,7 +145,7 @@ require (
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.32.0
github.com/pkg/sftp v1.13.12
github.com/rabbitmq/amqp091-go v1.15.0
github.com/rabbitmq/amqp091-go v1.16.0
github.com/rclone/rclone v1.75.1
github.com/rdleal/intervalst v1.5.0
github.com/redis/go-redis/v9 v9.23.0
@@ -162,6 +162,7 @@ require (
github.com/ydb-platform/ydb-go-sdk/v3 v3.155.1
go.etcd.io/etcd/client/pkg/v3 v3.7.3
go.uber.org/atomic v1.12.0
go.yaml.in/yaml/v3 v3.0.6
golang.org/x/sync v0.24.0
golang.org/x/tools/godoc v0.1.0-deprecated
google.golang.org/grpc/security/advancedtls v1.0.0
@@ -184,7 +185,7 @@ require (
github.com/anchore/go-lzo v0.1.1 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/thrift v0.24.0 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/bazelbuild/rules_go v0.46.0 // indirect
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
@@ -247,7 +248,7 @@ require (
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/mschoch/smat v0.2.0 // indirect
github.com/oklog/ulid/v2 v2.1.1 // indirect
github.com/oklog/ulid/v2 v2.1.2 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/openzipkin/zipkin-go v0.4.3 // indirect
@@ -276,37 +277,35 @@ require (
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/zipkin v1.45.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/mock v0.5.2 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/mod v0.42.0 // indirect
gonum.org/v1/gonum v0.17.0 // indirect
)
require (
cel.dev/expr v0.25.3 // indirect
cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a // indirect
cloud.google.com/go/auth v0.24.1 // indirect
cloud.google.com/go/auth/oauth2adapt v0.3.0 // indirect
cloud.google.com/go/compute/metadata v0.10.0 // indirect
cloud.google.com/go/iam v1.14.0 // indirect
cloud.google.com/go/monitoring v1.30.0 // indirect
cloud.google.com/go/monitoring v1.31.0 // indirect
filippo.io/edwards25519 v1.2.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1
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/azblob v1.8.3
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 // indirect
github.com/Azure/go-ntlmssp v0.1.1 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 // indirect
github.com/Files-com/files-sdk-go/v3 v3.3.194 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.38.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.61.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 // indirect
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 // indirect
github.com/IBM/go-sdk-core/v5 v5.23.1 // indirect
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd // indirect
github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 // indirect
@@ -320,22 +319,22 @@ require (
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
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.46.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.51.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.52.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.8
github.com/aws/smithy-go v1.28.9
github.com/boltdb/bolt v1.3.1 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
github.com/buengese/sgzip v0.1.1 // indirect
@@ -370,14 +369,14 @@ require (
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-openapi/errors v0.22.8 // indirect
github.com/go-openapi/strfmt v0.27.0 // indirect
github.com/go-openapi/errors v0.22.9 // indirect
github.com/go-openapi/strfmt v0.27.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.3 // indirect
github.com/go-resty/resty/v2 v2.17.2 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/goccy/go-json v0.10.6 // indirect
github.com/goccy/go-json v0.11.2 // indirect
github.com/gofrs/flock v0.13.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
@@ -387,7 +386,7 @@ require (
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/gorilla/sessions v1.4.0
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
@@ -419,8 +418,8 @@ require (
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nats-io/nats.go v1.49.0 // indirect
github.com/nats-io/nkeys v0.4.15 // indirect
github.com/nats-io/nats.go v1.54.0 // indirect
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/ncw/swift/v2 v2.0.5 // indirect
@@ -434,7 +433,7 @@ require (
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pierrec/lz4/v4 v4.1.29
github.com/pierrec/lz4/v4 v4.1.33
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
@@ -456,7 +455,7 @@ require (
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spacemonkeygo/monkit/v3 v3.0.25-0.20251022131615-eb24eb109368 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/spiffe/go-spiffe/v2 v2.8.2 // indirect
github.com/spiffe/go-spiffe/v2 v2.9.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/t3rm1n4l/go-mega v0.0.0-20260717075258-c6acd6a5bd04 // indirect
github.com/tarantool/go-iproto v1.1.0 // indirect
@@ -481,9 +480,9 @@ require (
github.com/zeebo/errs v1.4.0 // indirect
go.etcd.io/bbolt v1.5.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.46.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.47.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
@@ -493,7 +492,7 @@ require (
go.uber.org/zap v1.28.0 // indirect
golang.org/x/term v0.47.0
golang.org/x/time v0.16.0
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/validator.v2 v2.0.1 // indirect
+110 -112
View File
@@ -4,8 +4,8 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a h1:jW1ZLFy9oa5ai8LOI40z6s+DL1cO/L1KSm9hVGnibn8=
cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c=
cloud.google.com/go/auth v0.24.1 h1:NTmd2iJb4DsGIav0KiqFMYI88nMshA2wnFMBatRmoCs=
cloud.google.com/go/auth v0.24.1/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c=
cloud.google.com/go/auth/oauth2adapt v0.3.0 h1:FY8oSZpCYoUNv6QxVODuMjQz4IlSOVeiQtZ08vLPz88=
cloud.google.com/go/auth/oauth2adapt v0.3.0/go.mod h1:7+2uCm7++XFO+/lN06c2HXpDXb/NMNn2/UwyBPbTnkk=
cloud.google.com/go/compute/metadata v0.10.0 h1:pyKMUQSwchgkIBBJGdILqQbs/BNJXqwSA7Ej6LAvvtY=
@@ -18,14 +18,14 @@ cloud.google.com/go/logging v1.20.0 h1:l7yzCB8/JSY5PHT9RsaqdT1jaBGbM6KlSJDX210Hl
cloud.google.com/go/logging v1.20.0/go.mod h1:ALUaJQZM691Eeujy9kFx0xREq3AMPuGd+pTRZuTYv+w=
cloud.google.com/go/longrunning v1.3.0 h1:lZ6c8SJJBmILp/Wnr3vGnBLa0q+cYfSHRCcUfVI2hpI=
cloud.google.com/go/longrunning v1.3.0/go.mod h1:wpgLxCn+UA3/TZ1bj/fW39mfDpwVlMPu1xKJyoMt7V0=
cloud.google.com/go/monitoring v1.30.0 h1:r/d+JUbyKmJ8b07iznuKfzVzrIXTWxHQ3lBRm3x2LlY=
cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM=
cloud.google.com/go/monitoring v1.31.0 h1:LCuAoYiq8snyL/eDAG/VC73uWFXeax8+YEfmoNGJUrY=
cloud.google.com/go/monitoring v1.31.0/go.mod h1:7uk2dIJIf7ra64dI1VuQ0ttoFqvtKjdzq46u6zNP1hU=
cloud.google.com/go/pubsub v1.51.1 h1:R3G1wCOxBO7jRpL8x2pdZMv1GAJDF6ax/m2zPOtvTNE=
cloud.google.com/go/pubsub v1.51.1/go.mod h1:y2T0IKtW1iWwVvazYaRpqOAFO4gy2+O7dTDt9TWY/5U=
cloud.google.com/go/pubsub/v2 v2.7.0 h1:MFrBTZZa6PDWZzCi4NJRsHKMm2w0a4oAaYNqwjgbQTE=
cloud.google.com/go/pubsub/v2 v2.7.0/go.mod h1:JaFvWNVRk3Knoil/4M1ECeLOaI9D8drbmJWypQlK5aM=
cloud.google.com/go/storage v1.67.0 h1:8xD3NvKuHE4c+b/kmSIVBdTc0BiOjplx+KecKGR9fr8=
cloud.google.com/go/storage v1.67.0/go.mod h1:UsS9OgFg/XHOSYakQ8ZtLWWeyGkk1WnmD/GsGfN0BHM=
cloud.google.com/go/storage v1.69.0 h1:jAAMC1411HEh78nKsU0Zns+eFj3TnhjAWIhg5Ud/XBM=
cloud.google.com/go/storage v1.69.0/go.mod h1:PELYsxTYm2peE4mwLEC1+mS1dA/kUSRUxNv56rOy44g=
cloud.google.com/go/trace v1.16.0 h1:GmQovzFc5F0CNfl0VLgL64aoTtu7xsM0YajW2GlG9+E=
cloud.google.com/go/trace v1.16.0/go.mod h1:r+bdAn16dKLSV1G2D5v3e58IlQlizfxWrUfjx7kM7X0=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
@@ -48,8 +48,8 @@ github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 h1:FbH3BbSb4bvGlu
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1/go.mod h1:9V2j0jn9jDEkCkv8w/bKTNppX/d0FVA1ud77xCIP4KA=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA=
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.2 h1:tQJdgQjbKKffEiMOKJmcQPkY01eFHRqWIZVefqP44nI=
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.2/go.mod h1:kTkpJchXAdO7LGkKZP97a+Ou8TgaF4NT6MHwOIy5uSQ=
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3 h1:zoPQ7KXGgzqeUmNWl+b6IwVAqsb5lROEJhqAmqXQtm0=
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3/go.mod h1:ei/sDx/dwDIUtZE3PQP1u8+qrA+CRy4q7qW+A2MbgB4=
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 h1:cuiKf1UVyWHu+XSQghPZR/qEF43JIcuk2CDqMlPiT6M=
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0/go.mod h1:9JSyvgXLPAOC4jfhgZg58XeU2FJHsGmxuYSclCFQ4ZY=
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 h1:X/bTwe0qpvmvPPutc+LWo7T4cKMqDP9JHP4k+Co9ZB4=
@@ -60,8 +60,8 @@ github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDP
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0 h1:MDT4FxAPve5FnYn6vOL1r7RCRDG+l9cI7a5LlCuHsqA=
github.com/AzureAD/microsoft-authentication-library-for-go v1.9.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI=
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 h1:0O6j18nQDoIff6/mtosT5LNU2WehEwp+LqfX6699oqY=
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1/go.mod h1:xdYAf5bjkOpsd3auA8riiJW4vneBubt9caavL7626jQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d h1:iG9B49Q218F/XxXNRM7k/vWf7MKmLIS8AcJV9cGN4nA=
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d/go.mod h1:RVnhzAX71far8Kc3TQeA0k/dcaEKUnTDSOyet/JCmGI=
@@ -75,14 +75,12 @@ github.com/FilenCloudDienste/filen-sdk-go v0.0.39 h1:tgV5jYL6dsXop9TpDTIQU6UwJjw
github.com/FilenCloudDienste/filen-sdk-go v0.0.39/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
github.com/Files-com/files-sdk-go/v3 v3.3.194 h1:dtOFxSTWWRpkmvXa6ycNiw8dVDu1wkgzcXyVV1VafNc=
github.com/Files-com/files-sdk-go/v3 v3.3.194/go.mod h1:rl0WumSN9gSo775DgvQv+wMQ8rlb0ES/1hU5jkMtLXg=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.38.0 h1:rmzbFS2CkHq0y2L5LkMVWm+QXjjNEXxjmhrJqga/QGk=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.38.0/go.mod h1:iIyrdhveU5Ow84ipRlxtjCOQnIM0DiqSMxuxm50xwZY=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0 h1:BeC1Bub7Ttk33TF8v3ZeQ2L8acvz4ZLqtQuLyJAZquc=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.61.0/go.mod h1:UgG/Xn9+NXb1/ueSczIFxyuya3hs3srFDiZG2JrpJwY=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.61.0 h1:eSgSuKdcpY7RTN1oXSzC6S39rPBImn03ubLMsWK4RRg=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.61.0/go.mod h1:ifhe5teRNcbxg9p353DhOkOgczzL/IBLYFqT1cm1zpM=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.61.0 h1:KhpL26/GviYITHMCEGGqT/l50siFaBCBBKrjv6Z0G/k=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.61.0/go.mod h1:sg6Wqbl0BKKZ5zKnQj2q0qic/3ziF894SCx1LpbX37Y=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 h1:5y2LR2pripbccOte6BpZ+guv5O5W0OQIfKvUYZrGaAQ=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0/go.mod h1:b3f7EifFRqkVt142USoGIP62uUeZm7ALCPrs1ZjWXYo=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.62.0 h1:tRsXhJnn0w0TNwJpVrB94wsrimzjWKFzdQlUhRdNUzc=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.62.0/go.mod h1:ifhe5teRNcbxg9p353DhOkOgczzL/IBLYFqT1cm1zpM=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 h1:aPMa5qZU9dp4fU34o+jQgVIPFIOi20oxYg8TLigmZLg=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0/go.mod h1:sg6Wqbl0BKKZ5zKnQj2q0qic/3ziF894SCx1LpbX37Y=
github.com/IBM/go-sdk-core/v5 v5.23.1 h1:fxLusCG+GlGY1SM7BYAAiiSFhzKUs5zqs0P8knDqeFU=
github.com/IBM/go-sdk-core/v5 v5.23.1/go.mod h1:yO+OQpByKDLTvpEcsFFexgzpeR8eRfCFWAYzxkAu4bk=
github.com/Jille/raft-grpc-transport v1.6.1 h1:gN3sjapb+fVbiebS7AfQQgbV2ecTOI7ur7NPPC7Mhoc=
@@ -173,50 +171,50 @@ github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJ
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/aws/aws-sdk-go-v2 v1.47.7 h1:jBmtzRtGWVAzbfc4RBWo1dTte0ZZH8p9U42YJIw2+Bw=
github.com/aws/aws-sdk-go-v2 v1.47.7/go.mod h1:I8lFSH4MGrZiw2m7miCrRYHsgpC1+HW8uiVGOiPYPcw=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20 h1:GPRlPwz40I2B2VrBEASOA3Bi77NyeqejNLkifosX0rs=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.20/go.mod h1:g7PNzKcsOKWb4fkSRBA7BZVAS6Y8IcxzN+nRohhQ1Q8=
github.com/aws/aws-sdk-go-v2/config v1.33.6 h1:MBjkSTLczek/UgiK+EYPIoRTqE7gP8vtW3OFbFo7Nug=
github.com/aws/aws-sdk-go-v2/config v1.33.6/go.mod h1:grRAFzdAZJrwcbasJRg2MPvIrVjtlfXllHssN6+E1JE=
github.com/aws/aws-sdk-go-v2/credentials v1.20.6 h1:NpAFXCU7NzXNkdGK3zQTtsRJ+3v9tZQV0xcdRw8uBdw=
github.com/aws/aws-sdk-go-v2/credentials v1.20.6/go.mod h1:mcZCoiPnyMvP8VMNbygNX5lLqSlkYJIMPODylQMurOk=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1 h1:8gALAAmacnIXh+z6VkdDanv4/IkG5APdg4DZLDTmLog=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.1/go.mod h1:Z7IJhJU+poOdJjUR2wpyY21ossQ1XS/R3Lk9Msq5kM4=
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0=
github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg=
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 h1:gr3b87OLB29jymWPzp/CAyXwQRJVE+sC4Wm0qBIKHsk=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3/go.mod h1:BRjf4L/Yx2hY54o+ZibPbLJyMMeSwqYQXwcJfqW66a8=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHAjf0L/22H8cnhxZC0uPwtMtg=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34/go.mod h1:eToXR/Gk1uqpn04eSmdgVXwfS0WvH8aG4eBFr8ygbpU=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3 h1:vsFkmFrfzODkxVbyuPLscv5j5lC8KbG48LZwV+p56Y0=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.3/go.mod h1:pjQYVtvVBEtlsf2p6nXMsjPuDaWs9GM44FMdHbmnmYU=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5 h1:/TYsZXdA8UTa+WCtCYSAJIr1vwl0+eho6TUgJGwFFO8=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.5/go.mod h1:qPqp1Uwd/BqdhPufv6oem9j5J7HNsgc2V22dUiDPn+s=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4 h1:pPiWfgeNxqluKEph7hvU88kuGKBPOWzO+Dk9t2zqqNs=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.4/go.mod h1:YlwGoIUDG/3kBQbdNOVs/xKZ9J01G8e/6D1mRBj9uTk=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.1 h1:9T6eO8/WXhij4PQaa2WaYsdekSCmT9Hw66Pw0S8do0Q=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.1/go.mod h1:9APRWGLFITKD+xzWSIyT9V7QV4bNlEuIieWlzXgGFlI=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1 h1:DzCCWLzcIRQ77F3DEUljud7bEjTgFOIKXP52NmVRyhU=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.1/go.mod h1:xpo/geVldu8payT375WekctUzopG/hBU7miiqItMUlw=
github.com/aws/aws-sdk-go-v2/service/sns v1.46.0 h1:fD02zeo2Kc4hlFUvGX3FfA+gGOwd4BBcYgPDHDEzx9Y=
github.com/aws/aws-sdk-go-v2/service/sns v1.46.0/go.mod h1:/lB2ILjoT5/q0zSwtHnrJPjXBvjalnEIl0IgSEdvHec=
github.com/aws/aws-sdk-go-v2/service/sqs v1.51.0 h1:FghdY9ebeZf9iIan9J0xfBEID8arYibNBeZ1XHvs4oA=
github.com/aws/aws-sdk-go-v2/service/sqs v1.51.0/go.mod h1:wu7uOJ/2nAdenjvhHikeF6j0al99kfPVG6ZDU4e76OY=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1 h1:Umtl/0YZhng4xndfW3lKJrYYP7NLEjI6bGXVomwLcs0=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.1/go.mod h1:rRD/dnm7q0HYE/I5TMaPgkWyyUGLcwuxHLABsLnQ3e0=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1 h1:orIWdNiLgzrhu/11RcPPKO/SBzUUymbUQuZbSPImghg=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.1/go.mod h1:skwM/xsbR/1ReUTesv9BhpJp1VjajR7DWQnuVLwiXsQ=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16 h1:q9YuNkYR/7lxflWCcEv3C0cecUt3Zvrh2hn9ZNxieNA=
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16/go.mod h1:3BSeJQF55QQI+dDFHx4WTIjTvX/Lvtk8Jaaf/SGAnBM=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A=
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M=
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5 h1:4EezYQsIY0xPbD6u7TbQLfnpicSMQgA8n9paomVV4Zo=
github.com/aws/aws-sdk-go-v2/service/sns v1.47.5/go.mod h1:Yr4VqXnyoyjWnOWJck8BOidkJtleQ1c8ypgd2n0epxE=
github.com/aws/aws-sdk-go-v2/service/sqs v1.52.4 h1:D+Zmdt3T3P770MrqTmZvalbj6ADO7xA7n+qnNakGvrI=
github.com/aws/aws-sdk-go-v2/service/sqs v1.52.4/go.mod h1:dUYH3ia3qEO5ogaWDLp2tjtb4u4Y9xRbae7tOr1ClIA=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 h1:ChCtagixSFOxltv0o6E3NT8F7ksvZtZGPwUBynO5Nmk=
github.com/aws/aws-sdk-go-v2/service/sso v1.38.4/go.mod h1:+FEO9jrVMpc9oN3CdAxJbtlQEu3z8UddDPSedpeM3PY=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEBrucJEryfrQU0TffmACk=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw=
github.com/aws/smithy-go v1.28.8 h1:aEmdAq7gVCoGCnvf1NnELlu3I6D/nhqrC321FyFiQkQ=
github.com/aws/smithy-go v1.28.8/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
@@ -509,12 +507,12 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-openapi/errors v0.22.8 h1:oP7sW7TWc3wFFjrzzj0nI83H2qMBkNjNfSd+XRejk/I=
github.com/go-openapi/errors v0.22.8/go.mod h1:BuUoHcYrU6E7V9gfj1I5wLQqgtIHnup/alXZ8KdgQ0w=
github.com/go-openapi/strfmt v0.27.0 h1:kbcTeaD9TXuXD0hhMXzuYa1sdTo6+dWGvwjW93E80IM=
github.com/go-openapi/strfmt v0.27.0/go.mod h1:s/qhDqfY72irigXUGJmtgid2Rm+3tnz3k8hZaRmvWYc=
github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug=
github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=
github.com/go-openapi/errors v0.22.9 h1:HI9+SyVYiRzyeBQGv0CbWbQa+u2S0nny7G7AhY+UMiM=
github.com/go-openapi/errors v0.22.9/go.mod h1:R73q66sXP2smzAGgFOI4nqtusRK2xN5pYCjsij+KX58=
github.com/go-openapi/strfmt v0.27.2 h1:SG32SlbwNy92s0KJiVxt2joJeFdqIYHvwrA0OU6HqzQ=
github.com/go-openapi/strfmt v0.27.2/go.mod h1:M4CKsMO0Fb8qR10+1Ra75wCKNNquy+Vj+4LWZrhTo2E=
github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho=
github.com/go-openapi/testify/v2 v2.8.0/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@@ -546,8 +544,8 @@ github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlnd
github.com/go-zookeeper/zk v1.0.2/go.mod h1:nOB03cncLtlp4t+UAkGSV+9beXP/akpekBwL+UX1Qcw=
github.com/go-zookeeper/zk v1.0.4 h1:DPzxraQx7OrPyXq2phlGlNSIyWEsAox0RJmjTseMV6I=
github.com/go-zookeeper/zk v1.0.4/go.mod h1:nOB03cncLtlp4t+UAkGSV+9beXP/akpekBwL+UX1Qcw=
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-json v0.11.2 h1:jdZv93Tt4ioR8yW1CoNsvSxrcZlCXAUU1aZXN7gpXUA=
github.com/goccy/go-json v0.11.2/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
@@ -563,8 +561,8 @@ github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 h1:gtexQ/VGyN+VVFRXSFig
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.7.0-rc.1 h1:YojYx61/OLFsiv6Rw1Z96LpldJIy31o+UHmwAUMJ6/U=
@@ -649,8 +647,8 @@ github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDa
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8=
github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 h1:Bd7KaOxzULLxtZ/K5s1aLbWhR0+5RToO65TXHsf3bqQ=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0/go.mod h1:nN7ts3dFXKtCZWc//yfkpcQNKJABg16/uDVAZpLDalo=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -915,10 +913,10 @@ github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU=
github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg=
github.com/nats-io/nats-server/v2 v2.11.15 h1:StSf9TINInaZtr4oww2+kXmfwa9SkN//g/LwS19/UJ0=
github.com/nats-io/nats-server/v2 v2.11.15/go.mod h1:zwhv8Y0PE3KHyKgznJc/9Xoai638SaJd83zzJ5GJn74=
github.com/nats-io/nats.go v1.49.0 h1:yh/WvY59gXqYpgl33ZI+XoVPKyut/IcEaqtsiuTJpoE=
github.com/nats-io/nats.go v1.49.0/go.mod h1:fDCn3mN5cY8HooHwE2ukiLb4p4G4ImmzvXyJt+tGwdw=
github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=
github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
@@ -929,8 +927,8 @@ github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY=
github.com/nxadm/tail v1.4.11/go.mod h1:OTaG3NK980DZzxbRq6lEuzgU+mug70nY11sMd4JXXHc=
github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=
github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
github.com/oklog/ulid/v2 v2.1.2 h1:IEclFb9JNvzYA6MW2SCxbLzcHTVsfqm3PrqGQJH5zec=
github.com/oklog/ulid/v2 v2.1.2/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
github.com/olivere/elastic/v7 v7.0.32 h1:R7CXvbu8Eq+WlsLgxmKVKPox0oOwAE/2T9Si5BnvK6E=
github.com/olivere/elastic/v7 v7.0.32/go.mod h1:c7PVmLe3Fxq77PIfY/bZmxY/TAamBhCzZ8xDOE09a9k=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
@@ -979,8 +977,8 @@ github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741/go.mod h1:pxMtw7c
github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pierrec/lz4/v4 v4.1.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pierrec/lz4/v4 v4.1.33 h1:GjG1TJ1V4IzKP8L96muuuDNpTwd7D+l2ccXrjAbe014=
github.com/pierrec/lz4/v4 v4.1.33/go.mod h1:7SE9MC2STkNtL4PIwGhjmyVwvILaGI9/COYQNBhKM/c=
github.com/pierrre/compare v1.0.2 h1:k4IUsHgh+dbcAOIWCfxVa/7G6STjADH2qmhomv+1quc=
github.com/pierrre/compare v1.0.2/go.mod h1:8UvyRHH+9HS8Pczdd2z5x/wvv67krDwVxoOndaIIDVU=
github.com/pierrre/geohash v1.0.0 h1:f/zfjdV4rVofTCz1FhP07T+EMQAvcMM2ioGZVt+zqjI=
@@ -1051,8 +1049,8 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/rabbitmq/amqp091-go v1.15.0 h1:LEQL4/yp48/Wigt6A6XOu18RQRo8ZHtB5I/KZJn+gkw=
github.com/rabbitmq/amqp091-go v1.15.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/rabbitmq/amqp091-go v1.16.0 h1:1O8oQqnj9hLACoo6CVMgn57z2pLWXvgemhh4GsquV+Y=
github.com/rabbitmq/amqp091-go v1.16.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/rclone/Proton-API-Bridge v1.0.5 h1:K1++Qtk3PvgkiCCiv6Pahju1TMOzKY6VSwiwT7XLAVc=
github.com/rclone/Proton-API-Bridge v1.0.5/go.mod h1:vCeOPhlXzevN0AFojgh1zsjhetiShy/ArvJ/xkFUDWk=
github.com/rclone/go-proton-api v1.0.4 h1:AJW0e9pB4j0hVK4WqyGErFwaI+5MUQWPCtj5FYYxtPg=
@@ -1155,8 +1153,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/spiffe/go-spiffe/v2 v2.8.2 h1:jUEsvCMD6fH25J8K/w3q/XnIx8W1lb8+YLaEEHIjHmc=
github.com/spiffe/go-spiffe/v2 v2.8.2/go.mod h1:w2CLWKLMTX/PPYUEUPv3ltH0RXsw5S8suwNF46w9/Aw=
github.com/spiffe/go-spiffe/v2 v2.9.0 h1:g5qTg3qIP1HXV+GzuyEfSJFVxUCpEP5Ui1OINVJHPB4=
github.com/spiffe/go-spiffe/v2 v2.9.0/go.mod h1:w2CLWKLMTX/PPYUEUPv3ltH0RXsw5S8suwNF46w9/Aw=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
@@ -1351,36 +1349,36 @@ go.einride.tech/aip v0.83.0 h1:TI21IdeOnLTwZEJ3BxtImIZk6bsN2Q+sd0x99SLiQ+M=
go.einride.tech/aip v0.83.0/go.mod h1:E8+wdTApA70odnpFzJgsGogHozC2JCIhFJBKPr8bVig=
go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
go.etcd.io/etcd/api/v3 v3.7.1 h1:KJG0/DcWGfe3Y1otDf/fsBf0TSSgpxZ5RO/L8SFt73E=
go.etcd.io/etcd/api/v3 v3.7.1/go.mod h1:8bXIpCMeV7E3/XL0Ix123ATn3dB+0V7d9zklHbB0m78=
go.etcd.io/etcd/api/v3 v3.7.3 h1:2tumepXe+wi7Wab64uUO71K7ISQyUWLGC1DJbbc59sY=
go.etcd.io/etcd/api/v3 v3.7.3/go.mod h1:HOR9Qn4gb/1/hVAmYprmlLpvTe6ZgfgNS9Z/+Ty65po=
go.etcd.io/etcd/client/pkg/v3 v3.7.3 h1:5zMwNu3ycrzCeA5NwOfQbxFRhqq974chq1DrYMua4QI=
go.etcd.io/etcd/client/pkg/v3 v3.7.3/go.mod h1:/OhzqYrF0U7d1NOk55VMyUQGbYD1WoIe4bJwxb47wOk=
go.etcd.io/etcd/client/v3 v3.7.1 h1:0PEMMC0KuZmVIN+RAbdqfkZ45pYTgKVtmBEbRCvZFUg=
go.etcd.io/etcd/client/v3 v3.7.1/go.mod h1:ffNqALa8tRCYhYo1F9oR489y23K39Gz+BSR3ApAGYq0=
go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q=
go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE=
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.46.0 h1:PI8dGkqDaQkwJ8kOopqMhDTbrnK3UIeG/RCHH4HErbo=
go.opentelemetry.io/contrib/detectors/gcp v1.46.0/go.mod h1:nsrN5c/sOLoY2vsPxN/rQ0V0nvGrWJCqcW4UXLtqNG8=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0/go.mod h1:dylvB+ZiiwMvsDij9O84Uy7SijLgHMX4mbkncds+4Sw=
go.opentelemetry.io/contrib/detectors/gcp v1.47.0 h1:Ct6+aaiSO6Nk5SOb6PYcR7iWp+83YF/pL1OJcGqOmbg=
go.opentelemetry.io/contrib/detectors/gcp v1.47.0/go.mod h1:3N259ss0b1AVOs+fYw7lOO0mcUwNqSIpQ+Zitpuqx00=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.46.0 h1:qkDYCAFiZXLcs1L4aY+tP2wguQ4kURANqHOQMA2et2s=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.46.0/go.mod h1:tkipS4DRzmpAmvg+Gw4++O1IdDq6TVDnvnYU6cmbQVs=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.47.0 h1:LaLVGJtIzHcvHjVs2OftmKcc+M9mdOqS8vZ1fBD1Yes=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.47.0/go.mod h1:vF6H5sNDuQBJWgSX00iZgbIqk2MZZoVMH0ar5t5bOpw=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0 h1:RuynHbfU8JUEw7DyONgkVYg2SVtsoF28y0LGIr69jgA=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0/go.mod h1:qZF+/lBs71APw8mlnEZcqZHMzqrYrsFiJOv83lX1OGo=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 h1:w53CDeOA/Kurp7yRsegSr6pbbr759dOvJ+yNmWM6Hxs=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0/go.mod h1:BOmGMCbAtvcJiSJ+hLuhgPLdDbimnraSl8irz3iY8sY=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 h1:UFpxOpYPmMNUtOWhdb+nC1WELIgVf8z9higURrbzYU4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0/go.mod h1:YBGjxe3lt0jtXoEXxGrGhv/jM7oUBUDVK7zhAvNyEjc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.45.0 h1:QBajQ2SrwQijzHyZbQlPsuIzpl/ll8DY6wPWsajeGcI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.45.0/go.mod h1:08ZQLjrPLQ6R4kAXvuOvODEer5Yh4CoFvll5qB2BCI8=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.46.0 h1:PR9eAf7o0dQs3hshZNZpE9aW2dXWX/KdDf6pJilVD3U=
@@ -1400,8 +1398,8 @@ go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syod
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
@@ -1427,10 +1425,10 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4=
go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
gocloud.dev v0.47.0 h1:qN4/0vtutn97f1X5ziisf3WXuaFL9AR0FIRnyJRYzgA=
gocloud.dev v0.47.0/go.mod h1:OdMnyXQRhM17U0a0DwU57pe0c01qN3lJNmaeeRYW0D0=
gocloud.dev/pubsub/natspubsub v0.46.0 h1:cTmJnWOmhb3dYRzX7PvNkq2m5mQdBLFFxZbl/21pfjk=
gocloud.dev/pubsub/natspubsub v0.46.0/go.mod h1:hbEEsNt6mGQoonGQi39VOjHfx2f13DOmWouh4hGsfrU=
gocloud.dev v0.49.0 h1:02y4IBHX12xiCBK3Nv80IzuCmZXLsOfgpKwMEKzR9O4=
gocloud.dev v0.49.0/go.mod h1:uN+hz2x8ieyW5RjeMetvmpV/nRqFOr7DF0CKVY0Owp8=
gocloud.dev/pubsub/natspubsub v0.49.0 h1:Jk1bywJ6LvqvBbxOQ0qs0q4aa+ORgg1FzjhTy+5O4cI=
gocloud.dev/pubsub/natspubsub v0.49.0/go.mod h1:bmtxptoOPBNAgvTW9tWzoZvw9vzunDoNk6l4cHGd6nc=
gocloud.dev/pubsub/rabbitpubsub v0.47.0 h1:iDSspbLlDbPL2avESbDfMNBK4r3B6H04Ejx+/hqh9JE=
gocloud.dev/pubsub/rabbitpubsub v0.47.0/go.mod h1:2tSZnGnGLPw2ayW4pVaUmnA1LCjP7rekpXPkaBUZt0o=
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
@@ -1451,8 +1449,8 @@ golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297 h1:YXnL44eJ77R+ji4/ooy8UsXIhz+lbi2Qgdlc8iRN0gY=
golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297/go.mod h1:Mkmymgv+uMpSQ/XxJ/7GpdrdYoqm3u72jEbpCLiJmNk=
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A=
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -1608,8 +1606,8 @@ golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/tools/godoc v0.1.0-deprecated h1:o+aZ1BOj6Hsx/GBdJO/s815sqftjSnrZZwyYTHODvtk=
golang.org/x/tools/godoc v0.1.0-deprecated/go.mod h1:qM63CriJ961IHWmnWa9CjZnBndniPt4a3CK0PVB9bIg=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -1631,10 +1629,10 @@ google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfG
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY=
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941 h1:CXq2XEi5aEyLjjPZIwqrmQH8ZY4ctUwK7uyAx3mjX/U=
google.golang.org/genproto v0.0.0-20261012220534-4341edf3f941/go.mod h1:3gK0ehnhP0V7/x3ypGoLyT3d0n6TSi/EcsphIjHrcz4=
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 h1:DS/w3N8rsfrwxwgGSj6WhMsPo7aNQGmDx74J81zd0NQ=
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941/go.mod h1:AuGAdi9KnXss7xbLxIKhCvk+Ro/SxpET/iS45DNYN+M=
google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b h1:+t2qGqt6R8CO622uiX1JpnRvRvSOQoVRV0DiPzUjKXg=
google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b/go.mod h1:XRIfc1yr5xsbF8xFw5+g7SEmLJX/eQ7MMazTRbnMMvI=
google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b h1:nB3spRIaSPtxJpxb0k41yljROvm2Jrwfs2pSNdKS5y8=
google.golang.org/genproto/googleapis/api v0.0.0-20261019180522-ce908d29299b/go.mod h1:9N4vtjEwvgQKEdlFVQO0M44ErhecQ9DCSQfGoZ51M6w=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
+80 -31
View File
@@ -7,12 +7,14 @@
# curl -fsSL https://raw.githubusercontent.com/seaweedfs/seaweedfs/master/install.sh | bash
# curl -fsSL ... | bash -s -- --component volume-rust --large-disk
# curl -fsSL ... | bash -s -- --version 4.34 --dir /usr/local/bin
# curl -fsSL ... | bash -s -- --enterprise --component all
#
# Options:
# --component COMP Which binary to install: weed, volume-rust, worker-rust, vector, all (default: weed)
# --version VER Release version tag (default: latest)
# --large-disk Use large disk variant (5-byte offset, 8TB max volume)
# --dir DIR Installation directory (default: /usr/local/bin)
# --enterprise Install SeaweedFS Enterprise binaries (from seaweedfs/artifactory)
# --help Show this help message
set -euo pipefail
@@ -24,6 +26,10 @@ LARGE_DISK=false
INSTALL_DIR="/usr/local/bin"
WORKER_INSTALLED=false
VECTOR_INSTALLED=false
VOLUME_INSTALLED=false
ENTERPRISE=false
# Enterprise assets carry this after the binary name, e.g. weed-vector-enterprise_linux_amd64.tar.gz.
EDITION=""
# Colors (if terminal supports them)
if [ -t 1 ]; then
@@ -53,6 +59,7 @@ while [ $# -gt 0 ]; do
--version) VERSION="$2"; shift 2 ;;
--large-disk) LARGE_DISK=true; shift ;;
--dir) INSTALL_DIR="$2"; shift 2 ;;
--enterprise) ENTERPRISE=true; REPO="seaweedfs/artifactory"; EDITION="-enterprise"; shift ;;
--help|-h) usage ;;
*) error "Unknown option: $1. Use --help for usage." ;;
esac
@@ -81,15 +88,22 @@ detect_platform() {
}
# Get latest release tag from GitHub API
# The Enterprise repo also releases other products (vfs-*, previews), which can
# be its latest release, so take the newest plain version tag like 4.53.
get_latest_version() {
local url="https://api.github.com/repos/${REPO}/releases/latest"
if [ "$ENTERPRISE" = true ]; then
url="https://api.github.com/repos/${REPO}/releases?per_page=30"
fi
local body
if command -v curl &>/dev/null; then
curl -fsSL "$url" | grep '"tag_name"' | head -1 | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/'
body="$(curl -fsSL "$url")"
elif command -v wget &>/dev/null; then
wget -qO- "$url" | grep '"tag_name"' | head -1 | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/'
body="$(wget -qO- "$url")"
else
error "Neither curl nor wget found. Please install one."
fi
echo "$body" | grep '"tag_name"' | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/' | grep -E '^[0-9]+(\.[0-9]+)+$' | head -1 || true
}
# Download a file
@@ -110,17 +124,22 @@ go_asset_name() {
if [ "$LARGE_DISK" = true ]; then
suffix="${suffix}_large_disk"
fi
echo "${suffix}.tar.gz"
if [ "$ENTERPRISE" = true ]; then
suffix="weed-enterprise-${suffix}"
fi
if [ "$os" = "windows" ]; then
echo "${suffix}.zip"
else
echo "${suffix}.tar.gz"
fi
}
# Build Rust volume server asset name
rust_asset_name() {
local os="$1" arch="$2"
local prefix="weed-volume"
local prefix="weed-volume${EDITION}"
if [ "$LARGE_DISK" = true ]; then
prefix="weed-volume_large_disk"
else
prefix="weed-volume"
prefix="${prefix}_large_disk"
fi
local suffix="${os}_${arch}"
if [ "$os" = "windows" ]; then
@@ -130,6 +149,19 @@ rust_asset_name() {
fi
}
# Enterprise publishes the Rust volume server for linux only.
rust_volume_platform_supported() {
case "$2" in
amd64|arm64) ;;
*) return 1 ;;
esac
case "$1" in
linux) return 0 ;;
darwin|windows) [ "$ENTERPRISE" != true ] ;;
*) return 1 ;;
esac
}
# Does a release carry this asset? Answers 0 for yes and 1 for a 404, and stops
# the installer on anything else: a rate limit or a network blip must not read
# as "this release predates the binary" and quietly skip it.
@@ -154,19 +186,23 @@ asset_exists() {
# maintains tables through the namespace and never opens a volume file.
worker_asset_name() {
local os="$1" arch="$2"
echo "weed-worker_${os}_${arch}.tar.gz"
echo "weed-worker${EDITION}_${os}_${arch}.tar.gz"
}
# The vector engine behind the S3 Vectors API, published for linux only like
# the worker.
# The vector engine behind the S3 Vectors API, built like the worker.
vector_asset_name() {
local os="$1" arch="$2"
echo "weed-vector_${os}_${arch}.tar.gz"
if [ "$os" = "windows" ]; then
echo "weed-vector${EDITION}_${os}_${arch}.zip"
else
echo "weed-vector${EDITION}_${os}_${arch}.tar.gz"
fi
}
vector_platform_supported() {
case "$1/$2" in
linux/amd64|linux/arm64) return 0 ;;
darwin/amd64|darwin/arm64|windows/amd64) [ "$ENTERPRISE" != true ] ;;
*) return 1 ;;
esac
}
@@ -186,7 +222,10 @@ install_component() {
download "$download_url" "${tmpdir}/${asset_name}"
info "Extracting ${asset_name}..."
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
case "$asset_name" in
*.zip) unzip -q "${tmpdir}/${asset_name}" -d "$tmpdir" ;;
*) tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir" ;;
esac
# The Go release action puts the binary inside a directory
local weed_bin
@@ -199,20 +238,16 @@ install_component() {
fi
chmod +x "$weed_bin"
install_binary "$weed_bin" "weed"
ok "Installed weed to ${INSTALL_DIR}/weed"
local dest_name="weed"
if [ "$os" = "windows" ]; then
dest_name="weed.exe"
fi
install_binary "$weed_bin" "$dest_name"
ok "Installed weed to ${INSTALL_DIR}/${dest_name}"
;;
volume-rust)
# Check platform support for Rust volume server
case "$os" in
linux|darwin|windows) ;;
*) error "Rust volume server is not available for ${os}. Supported: linux, darwin, windows" ;;
esac
case "$arch" in
amd64|arm64) ;;
*) error "Rust volume server is not available for ${arch}. Supported: amd64, arm64" ;;
esac
rust_volume_platform_supported "$os" "$arch" || error "The Rust volume server is not available for ${os}/${arch}"
asset_name="$(rust_asset_name "$os" "$arch")"
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
@@ -244,6 +279,7 @@ install_component() {
dest_name="weed-volume.exe"
fi
install_binary "$rust_bin" "$dest_name"
VOLUME_INSTALLED=true
ok "Installed weed-volume to ${INSTALL_DIR}/${dest_name}"
;;
@@ -280,19 +316,26 @@ install_component() {
;;
vector)
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}. Supported: linux/amd64, linux/arm64"
vector_platform_supported "$os" "$arch" || error "The vector engine is not available for ${os}/${arch}"
asset_name="$(vector_asset_name "$os" "$arch")"
download_url="https://github.com/${REPO}/releases/download/${VERSION}/${asset_name}"
download "$download_url" "${tmpdir}/${asset_name}"
info "Extracting ${asset_name}..."
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
local vector_name="weed-vector"
if [ "$os" = "windows" ]; then
command -v unzip >/dev/null || error "unzip is required for Windows vector archives"
unzip -q "${tmpdir}/${asset_name}" -d "$tmpdir"
vector_name="weed-vector.exe"
else
tar xzf "${tmpdir}/${asset_name}" -C "$tmpdir"
fi
local vector_bin
vector_bin="$(find "$tmpdir" -name weed-vector -type f | head -1)"
[ -n "$vector_bin" ] || error "Could not find weed-vector binary in archive"
vector_bin="$(find "$tmpdir" -name "$vector_name" -type f | head -1)"
[ -n "$vector_bin" ] || error "Could not find $vector_name binary in archive"
chmod +x "$vector_bin"
install_binary "$vector_bin" weed-vector
install_binary "$vector_bin" "$vector_name"
VECTOR_INSTALLED=true
ok "Installed weed-vector to ${INSTALL_DIR}/weed-vector"
;;
@@ -349,7 +392,11 @@ main() {
case "$COMPONENT" in
all)
install_component "weed" "$os" "$arch"
install_component "volume-rust" "$os" "$arch"
if rust_volume_platform_supported "$os" "$arch"; then
install_component "volume-rust" "$os" "$arch"
else
warn "Skipping the Rust volume server: no build for ${os}/${arch}"
fi
# The worker is published for linux amd64/arm64 only, and only by
# releases new enough to carry it; skip either case rather than fail
# an install that has already put two binaries in place.
@@ -378,7 +425,7 @@ main() {
if [ "$COMPONENT" = "weed" ] || [ "$COMPONENT" = "all" ]; then
info " weed: ${INSTALL_DIR}/weed"
fi
if [ "$COMPONENT" = "volume-rust" ] || [ "$COMPONENT" = "all" ]; then
if [ "$VOLUME_INSTALLED" = true ]; then
info " weed-volume: ${INSTALL_DIR}/weed-volume"
fi
if [ "$WORKER_INSTALLED" = true ]; then
@@ -391,7 +438,9 @@ main() {
info "Quick start:"
info " weed master # Start master server"
info " weed volume -mserver=localhost:9333 # Start Go volume server"
info " weed-volume -mserver localhost:9333 # Start Rust volume server"
if [ "$VOLUME_INSTALLED" = true ]; then
info " weed-volume -mserver localhost:9333 # Start Rust volume server"
fi
if [ "$WORKER_INSTALLED" = true ]; then
info " weed-worker --admin localhost:12535 # Start the Rust maintenance worker"
fi
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.53"
appVersion: "4.55"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.53.1
version: 4.55.0
+21 -6
View File
@@ -30,10 +30,12 @@ so your deployment will be spread/HA.
The chart's templates render with Helm 3.16.3 and newer versions tested in CI.
Earlier Helm versions are not covered by this chart's compatibility checks.
When JWT signing is enabled, a live upgrade reuses keys from the existing
security ConfigMap (including the legacy ConfigMap name); a key absent from
that ConfigMap is generated. Plain `helm template` does not read cluster state;
use an install and upgrade against a cluster to check key persistence.
When JWT signing is enabled, `security.toml` is kept in the
`<fullname>-security-config` Secret. A live upgrade reuses keys from that
Secret, or from the security ConfigMap of earlier chart versions (including
the legacy ConfigMap name); a key absent from them is generated. Plain
`helm template` does not read cluster state; use an install and upgrade
against a cluster to check key persistence.
The key reader supports single-line quoted TOML strings in JWT sections,
including indented assignments, quoted key names, and bare or simply quoted
@@ -569,6 +571,8 @@ s3:
With `rules` left empty the route sends all traffic to the component's own Service and port. A rule may set `matches`, `filters`, `timeouts` and `backendRefs`, and a rule without `backendRefs` still routes to that Service. In all-in-one mode the master, volume, filer and s3 routes target the all-in-one Service. When S3 runs only on the filer (`filer.s3.enabled` without `s3.enabled`), the s3 route uses `filer.s3.port`.
Outside all-in-one mode, the volume Ingress and the default volume route target the `client-volume` Service, which lists only Ready volume pods. The `volume` Service also publishes pods that are not Ready yet, so their DNS records can exist before readiness. An explicit `backendRefs` entry that names the `volume` Service can therefore reach a volume server before it is Ready. Name the `client-volume` Service instead, with `volume.port`, and copy its `metadata.name` from `helm template` because long release names are truncated.
## Network Policies
In a namespace with a default-deny policy the install hangs: the components cannot resolve each other, and the post-install bucket hook waits on the master and filer until it gives up. `networkPolicy.enabled` renders one `NetworkPolicy` per component, selecting its pods by the standard `app.kubernetes.io/{name,instance,component}` labels and admitting traffic from the other pods of the release on the ports that component listens on.
@@ -610,6 +614,17 @@ Two things worth knowing before you turn this on:
The DNS selectors default to CoreDNS as kubeadm, kind and the managed offerings from AWS, Google and Azure install it. On OpenShift, override `egress.dnsNamespaceSelector` and `egress.dnsPodSelector` to match `openshift-dns`; see the comment in `values.yaml`.
## Volume server HTTPS
With `global.seaweedfs.enableSecurity`, gRPC between components uses mutual TLS, but the volume servers' HTTP port, which carries the file data, stays plaintext. Set `global.seaweedfs.volumeHttps.enabled: true` to serve it over TLS:
- `[https.volume]` points at the volume certificate, which then also names every volume group's service (`*.<fullname>-volume.<namespace>`), since volume servers register as `<pod>.<fullname>-volume.<namespace>`. With `certificates.externalCertificates`, the provided `<fullname>-volume-cert` needs those names.
- `[https.client]` is enabled with the client certificate and the chart CA, so every chart pod that talks to the volume servers does it over HTTPS.
- The volume probes use HTTPS.
- Every pod that reads `security.toml` gets a `checksum/volume-https` annotation, so switching the option on or off restarts them together.
The volume servers do not require client certificates, because kubelet probes cannot present one; enable JWT signing (`securityConfig.jwtSigning`) to authorize volume reads and writes. `[https.client]` also sends the admin UI's HTTP lookups on masters and S3 over HTTPS, which their plain listeners refuse, so the UI can miss volume public URLs and refuse SSE-S3 vector buckets. A volume Ingress or HTTPRoute needs its controller's HTTPS-backend setting. `weed mount`, the CSI driver and other clients outside the chart need their own `[https.client]` with the chart CA. The option is not supported with `allInOne`, whose volume server registers by pod IP.
## Common labels
`commonLabels` adds labels to the metadata of every object the chart creates. It may be a map or a template string rendering to one. The chart's own labels cannot be overridden, and pods (see `podLabels`) and `volumeClaimTemplates` are left unchanged.
@@ -714,11 +729,11 @@ global:
The engine registers its pod address with the masters and stores indexes through the filers and volume servers. Both Go and Rust volume servers use the same setup. The maintenance worker builds and updates ANN indexes; queries can scan data before indexing completes. Enabling filer write signing also requires clients writing directly to the filer HTTP API to supply a signed JWT.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The cache defaults to 512 MiB and is configured with `vector.readCacheMB`.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The engine sizes its caches to a quarter of its memory limit.
`global.seaweedfs.enableSecurity` provisions and mounts the vector certificate and shared security configuration. With external certificates, provide the `<fullname>-vector-cert` secret (`my-seaweedfs-vector-cert` for release `my`). `fullname` follows `seaweedfs.fullname`, including `fullnameOverride`, `nameOverride`, and DNS-name truncation. Provide this secret alongside the existing CA and client secrets.
The default `vector.metricsPort: 0` and TCP probes support existing engine images. The default 4.53 image does not accept metrics flags; enabling metrics with it is rejected at render time. For engine builds with `/metrics`, `/health`, and `/ready`, set `vector.imageOverride` to that compatible image and `vector.metricsPort: 9329`; readiness then checks master registration. Enabling `global.seaweedfs.monitoring.enabled` also creates the vector ServiceMonitor. NetworkPolicy includes the configured gRPC and metrics ports.
The default `vector.metricsPort: 0` keeps TCP probes. Set `vector.metricsPort: 9329` to serve `/metrics`, `/health`, and `/ready` from the engine; readiness then checks master registration. Images older than 4.54 do not accept the metrics flag, so leave metrics off when pinning `image.tag` or `vector.imageOverride` to one. Enabling `global.seaweedfs.monitoring.enabled` also creates the vector ServiceMonitor. NetworkPolicy includes the configured gRPC and metrics ports.
To provision vector buckets during installation and upgrades, set:
@@ -56,6 +56,7 @@ spec:
{{- with .Values.admin.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.admin.restartPolicy }}
{{- if .Values.admin.affinity }}
@@ -188,6 +189,10 @@ spec:
{{- else }}
-masters={{ range $index := until (.Values.master.replicas | int) }}${SEAWEEDFS_FULLNAME}-master-{{ $index }}.${SEAWEEDFS_FULLNAME}-master.{{ include "seaweedfs.namespace" $ }}:{{ $.Values.master.port }}{{ if lt $index (sub ($.Values.master.replicas | int) 1) }},{{ end }}{{ end }} \
{{- end }}
{{- /* admin lists the filers and S3 gateways the workers use from this group */}}
{{- if .Values.filer.filerGroup }}
-filerGroup={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if $urlPrefix }}
-urlPrefix={{ $urlPrefix }} \
{{- end }}
@@ -313,8 +318,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -1,5 +1,16 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.allInOne.enabled }}
{{- if include "seaweedfs.volumeHttps" . }}
{{- fail "global.seaweedfs.volumeHttps is not supported with allInOne: its volume server registers by pod IP, which the volume certificate cannot name" }}
{{- end }}
{{- $s3PreStopSeconds := 0 }}
{{- if .Values.allInOne.s3.enabled }}
{{- $s3PreStopSeconds = .Values.allInOne.s3.preStopSeconds }}
{{- if kindIs "invalid" $s3PreStopSeconds }}
{{- $s3PreStopSeconds = .Values.s3.preStopSeconds }}
{{- end }}
{{- $s3PreStopSeconds = $s3PreStopSeconds | int }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -64,7 +75,7 @@ spec:
{{- tpl .Values.allInOne.tolerations . | nindent 8 }}
{{- end }}
{{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
terminationGracePeriodSeconds: 60
terminationGracePeriodSeconds: {{ add 60 (max $s3PreStopSeconds 0) }}
enableServiceLinks: false
{{- if .Values.allInOne.priorityClassName }}
priorityClassName: {{ .Values.allInOne.priorityClassName | quote }}
@@ -260,6 +271,9 @@ spec:
{{- if $auditLogConfig }}
-s3.auditLogConfig=/etc/sw/s3/s3_auditLogConfig.json \
{{- end }}
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
-sftp \
@@ -493,8 +507,8 @@ spec:
name: {{ include "seaweedfs.fullname" . }}-master-config
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -38,6 +38,14 @@ spec:
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ include "seaweedfs.namespace" . }}'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ include "seaweedfs.namespace" . }}.svc'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ include "seaweedfs.namespace" . }}.svc.cluster.local'
{{- if include "seaweedfs.volumeHttps" . }}
{{- range $vname, $_ := deepCopy .Values.volumes | mergeOverwrite (dict "" .Values.volume) }}
{{- $volumeService := printf "%s.%s" (include "seaweedfs.componentName" (list $ (trimSuffix "-" (printf "volume-%s" $vname)))) (include "seaweedfs.namespace" $) }}
- '*.{{ $volumeService }}'
- '*.{{ $volumeService }}.svc'
- '*.{{ $volumeService }}.svc.cluster.local'
{{- end }}
{{- end }}
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
@@ -39,6 +39,7 @@ spec:
{{- with .Values.cosi.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.cosi.restartPolicy }}
{{- if .Values.cosi.affinity }}
@@ -195,8 +196,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -1,5 +1,9 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.filer.enabled }}
{{- $s3PreStopSeconds := 0 }}
{{- if .Values.filer.s3.enabled }}
{{- $s3PreStopSeconds = .Values.filer.s3.preStopSeconds | int }}
{{- end }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
@@ -53,6 +57,7 @@ spec:
{{- end }}
annotations:
{{- toYaml $podAnnotations | nindent 8 }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.filer.restartPolicy }}
{{- if .Values.filer.affinity }}
@@ -69,7 +74,7 @@ spec:
{{- end }}
{{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
serviceAccountName: {{ .Values.filer.serviceAccountName | default (include "seaweedfs.serviceAccountName" .) | quote }} # for deleting statefulset pods after migration
terminationGracePeriodSeconds: 60
terminationGracePeriodSeconds: {{ add 60 (max $s3PreStopSeconds 0) }}
{{- if .Values.filer.priorityClassName }}
priorityClassName: {{ .Values.filer.priorityClassName | quote }}
{{- end }}
@@ -278,6 +283,9 @@ spec:
{{- if .Values.filer.s3.auditLogConfig }}
-s3.auditLogConfig=/etc/sw/filer_s3_auditLogConfig.json \
{{- end }}
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- end }}
-master={{ include "seaweedfs.masterServerArg" . }} \
{{- range .Values.filer.extraArgs }}
@@ -445,8 +453,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -48,6 +48,7 @@ spec:
{{- $_ := set $podAnnotations "checksum/master-config" (include "seaweedfs.master.configChecksum" .) }}
annotations:
{{- toYaml $podAnnotations | nindent 8 }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.master.restartPolicy }}
{{- if .Values.master.affinity }}
@@ -299,8 +300,8 @@ spec:
name: {{ include "seaweedfs.fullname" . }}-master-config
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -1,5 +1,10 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.s3.enabled }}
{{- $preStopSeconds := .Values.s3.preStopSeconds | int }}
{{- $minGracePeriod := add $preStopSeconds 15 }}
{{- if and (gt $preStopSeconds 0) (lt (.Values.s3.terminationGracePeriodSeconds | int) $minGracePeriod) }}
{{- fail (printf "s3.terminationGracePeriodSeconds (%v) must be at least %d: the gateway keeps serving for s3.preStopSeconds (%d) after SIGTERM, then gives in-flight requests up to 15s to finish; add the time any s3.lifecycle.preStop hook takes" .Values.s3.terminationGracePeriodSeconds $minGracePeriod $preStopSeconds) -}}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -49,6 +54,7 @@ spec:
{{- end }}
annotations:
{{- toYaml $podAnnotations | nindent 8 }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.s3.restartPolicy }}
{{- if .Values.s3.affinity }}
@@ -154,6 +160,9 @@ spec:
{{- if .Values.s3.auditLogConfig }}
-auditLogConfig=/etc/sw/s3_auditLogConfig.json \
{{- end }}
{{- if gt $preStopSeconds 0 }}
-preStopSeconds={{ $preStopSeconds }} \
{{- end }}
-filer={{ include "seaweedfs.componentName" (list . "filer-client") }}.{{ include "seaweedfs.namespace" . }}:{{ .Values.filer.port }} \
{{- if .Values.s3.icebergPort }}
-port.iceberg={{ .Values.s3.icebergPort }} \
@@ -280,8 +289,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -43,6 +43,7 @@ spec:
{{- with .Values.sftp.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.sftp.restartPolicy }}
{{- if .Values.sftp.affinity }}
@@ -297,8 +298,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -269,15 +269,20 @@ true
{{- end -}}
{{- end -}}
{{/* Lance namespace URL the worker's Lance container maintains; empty when unreachable */}}
{{/* The S3 service's Lance namespace URL, for a worker pinned before 4.56; empty when it serves none */}}
{{- define "seaweedfs.worker.lanceNamespaceUrl" -}}
{{- if .Values.worker.namespaceUrl -}}
{{- .Values.worker.namespaceUrl -}}
{{- else if and .Values.s3.enabled .Values.s3.lancePort -}}
{{- if and .Values.s3.enabled .Values.s3.lancePort -}}
{{- printf "http://%s.%s:%d" (include "seaweedfs.componentName" (list . "s3")) (include "seaweedfs.namespace" .) (int .Values.s3.lancePort) -}}
{{- end -}}
{{- end -}}
{{/* "true" when the worker runs its Lance container: an S3 gateway of this release serves a Lance namespace, or the worker serves an external admin, which names its cluster's */}}
{{- define "seaweedfs.worker.lanceEnabled" -}}
{{- if or (include "seaweedfs.worker.lanceNamespaceUrl" .) .Values.filer.s3.enabled .Values.worker.adminServer -}}
true
{{- end -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -491,6 +496,25 @@ true
{{- end -}}
{{- end -}}
{{/* True when the volume servers serve HTTPS. Their certificates come from
enableSecurity, so the option fails without it. */}}
{{- define "seaweedfs.volumeHttps" -}}
{{- if ((.Values.global.seaweedfs).volumeHttps).enabled -}}
{{- if not .Values.global.seaweedfs.enableSecurity -}}
{{- fail "global.seaweedfs.volumeHttps.enabled requires global.seaweedfs.enableSecurity, which provides the certificates" -}}
{{- end -}}
true
{{- end -}}
{{- end -}}
{{/* Pod annotation that restarts the readers of security.toml when volume
HTTPS is switched on or off. */}}
{{- define "seaweedfs.volumeHttpsAnnotation" -}}
{{- with include "seaweedfs.volumeHttps" . -}}
checksum/volume-https: {{ sha256sum . | quote }}
{{- end -}}
{{- end -}}
{{/* Read a JWT key from the chart's existing security.toml without fromToml
(which requires Helm >=3.17). Args: (list "<section>" $raw).
Return the single-line TOML string token, including its quotes, so escapes
@@ -104,7 +104,7 @@
{{- if .Values.worker.metricsPort }}
{{- $ports = append $ports .Values.worker.metricsPort }}
{{- end }}
{{- if and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- if and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- $ports = append $ports .Values.worker.lanceMetricsPort }}
{{- end }}
{{- $targets = append $targets (dict "component" "worker" "ports" $ports) }}
@@ -286,8 +286,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -1,7 +1,7 @@
{{- include "seaweedfs.compat" . -}}
{{- if include "seaweedfs.securityConfigEnabled" . }}
apiVersion: v1
kind: ConfigMap
kind: Secret
metadata:
name: {{ include "seaweedfs.fullname" . }}-security-config
namespace: {{ include "seaweedfs.namespace" . | quote }}
@@ -11,7 +11,8 @@ metadata:
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
data:
type: Opaque
stringData:
{{- $fullname := include "seaweedfs.fullname" . }}
{{- $securityConfigName := printf "%s-security-config" $fullname }}
{{- $existing := lookup "v1" "ConfigMap" (include "seaweedfs.namespace" .) $securityConfigName }}
@@ -19,7 +20,11 @@ data:
{{- $legacyName := printf "%s-%s" (include "seaweedfs.name" .) "security-config" }}
{{- $existing = lookup "v1" "ConfigMap" (include "seaweedfs.namespace" .) $legacyName }}
{{- end }}
{{- $existingToml := dig "data" "security.toml" "" $existing }}
{{- $ownConfigMap := eq (dig "metadata" "annotations" "meta.helm.sh/release-name" "" $existing) .Release.Name }}
{{- if and $ownConfigMap (or (and .Values.master.enabled (gt (int .Values.master.updatePartition) 0)) (and .Values.filer.enabled (gt (int .Values.filer.updatePartition) 0))) }}
{{- fail "this upgrade moves security.toml from a ConfigMap to a Secret and removes the ConfigMap; run it with master.updatePartition=0 and filer.updatePartition=0 so no pod is left on the old template" }}
{{- end }}
{{- $existingToml := dig "data" "security.toml" "" (lookup "v1" "Secret" (include "seaweedfs.namespace" .) $securityConfigName) | b64dec | default (dig "data" "security.toml" "" $existing) }}
{{- $securityConfigValues := .Values.global.seaweedfs.securityConfig | default dict }}
{{- $jwtSigning := $securityConfigValues.jwtSigning | default dict }}
{{- $expiresAfterSeconds := $jwtSigning.expiresAfterSeconds | default dict }}
@@ -30,7 +35,7 @@ data:
# the jwt signing key is read by master and volume server
# the jwt defaults to expire after 10 seconds
[jwt.signing]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing" $existingToml) | default (randAlphaNum 64 | quote) }}
{{- if gt (int $expiresAfterSeconds.volumeWrite) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.volumeWrite }}
{{- end }}
@@ -42,7 +47,7 @@ data:
# - the Volume server validates the JWT on reading
# the jwt defaults to expire after 60 seconds
[jwt.signing.read]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing.read" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing.read" $existingToml) | default (randAlphaNum 64 | quote) }}
{{- if gt (int $expiresAfterSeconds.volumeRead) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.volumeRead }}
{{- end }}
@@ -54,7 +59,7 @@ data:
# - the Filer server validates the JWT on writing
# the jwt defaults to expire after 10 seconds
[jwt.filer_signing]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing" $existingToml) | default (randAlphaNum 64 | quote) }}
{{- if gt (int $expiresAfterSeconds.filerWrite) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.filerWrite }}
{{- end }}
@@ -66,7 +71,7 @@ data:
# - the Filer server validates the JWT on reading
# the jwt defaults to expire after 60 seconds
[jwt.filer_signing.read]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing.read" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing.read" $existingToml) | default (randAlphaNum 64 | quote) }}
{{- if gt (int $expiresAfterSeconds.filerRead) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.filerRead }}
{{- end }}
@@ -121,13 +126,25 @@ data:
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
# volume server https options
# Note: work in progress!
# this does not work with other clients, e.g., "weed filer|mount" etc, yet.
{{- if include "seaweedfs.volumeHttps" . }}
[https.client]
enabled = true
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
ca = "/usr/local/share/ca-certificates/ca/tls.crt"
[https.volume]
cert = "/usr/local/share/ca-certificates/volume/tls.crt"
key = "/usr/local/share/ca-certificates/volume/tls.key"
{{- else }}
# volume server https: set global.seaweedfs.volumeHttps.enabled
[https.client]
enabled = false
[https.volume]
cert = ""
key = ""
{{- end }}
{{- end }}
{{- end }}
@@ -1,8 +1,5 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.vector.enabled }}
{{- if and .Values.vector.metricsPort (not .Values.vector.imageOverride) (eq (toString (.Values.image.tag | default .Chart.AppVersion)) "4.53") }}
{{- fail "vector.metricsPort requires vector.imageOverride selecting an engine with metrics support; the default 4.53 image does not support metrics" }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -28,6 +25,7 @@ spec:
annotations:
{{- with .Values.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
{{- with .Values.vector.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
{{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
automountServiceAccountToken: {{ .Values.global.seaweedfs.automountServiceAccountToken }}
@@ -58,13 +56,9 @@ spec:
- 'case "$POD_IP" in *:*) POD_IP="[$POD_IP]";; esac; exec /usr/bin/weed-vector --listen="$POD_IP:{{ .Values.vector.port }}" "$@"'
- vector
- {{ printf "--masters=%s" (.Values.vector.masters | default $masters) | quote }}
- {{ printf "--read-cache-mb=%d" (int .Values.vector.readCacheMB) | quote }}
{{- if .Values.filer.filerGroup }}
- {{ printf "--filer-group=%s" .Values.filer.filerGroup | quote }}
{{- end }}
{{- if .Values.vector.nprobes }}
- {{ printf "--nprobes=%d" (int .Values.vector.nprobes) | quote }}
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- --security-toml=/etc/seaweedfs/security.toml
{{- end }}
@@ -153,8 +147,8 @@ spec:
emptyDir: {}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
{{- range list "ca" "client" "vector" }}
@@ -1,6 +1,6 @@
{{- $volumeEnabled := or .Values.volume.enabled .Values.allInOne.enabled }}
{{- if and $volumeEnabled .Values.volume.httpRoute.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "volume")) .Values.allInOne.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "client-volume")) .Values.allInOne.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
@@ -2,7 +2,7 @@
{{- $volumeEnabled := or .Values.volume.enabled .Values.allInOne.enabled }}
{{- if and $volumeEnabled .Values.volume.ingress.enabled }}
{{- /* Determine service name based on deployment mode */}}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "volume")) .Values.allInOne.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "client-volume")) .Values.allInOne.enabled }}
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
@@ -0,0 +1,42 @@
{{- /* Ready-only backend for the volume ingress and HTTPRoute; the volume Service publishes not-ready pods for DNS.
Not named volume-client: every volume-<key> name belongs to a group under .Values.volumes. */}}
{{- if and .Values.volume.enabled (not .Values.allInOne.enabled) (or .Values.volume.ingress.enabled .Values.volume.httpRoute.enabled) }}
{{- $name := include "seaweedfs.componentName" (list . "client-volume") }}
{{- $volumes := deepCopy .Values.volumes | mergeOverwrite (dict "" .Values.volume) }}
{{- range $vname, $volume := $volumes }}
{{- $volumeName := trimSuffix "-" (printf "volume-%s" $vname) }}
{{- $volume := mergeOverwrite (deepCopy $.Values.volume) (dict "enabled" true) $volume }}
{{- if and $volume.enabled (eq (include "seaweedfs.componentName" (list $ $volumeName)) $name) }}
{{- fail (printf "The volume Ingress/HTTPRoute Service %q has the same name as the %s Service after truncation. Shorten fullnameOverride or the release name." $name $volumeName) }}
{{- end }}
{{- end }}
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}
namespace: {{ include "seaweedfs.namespace" . | quote }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: volume
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
{{- if .Values.volume.annotations }}
annotations:
{{- toYaml .Values.volume.annotations | nindent 4 }}
{{- end }}
spec:
clusterIP: None
internalTrafficPolicy: {{ .Values.volume.internalTrafficPolicy | default "Cluster" }}
{{- /* No metrics port, so the volume ServiceMonitor does not scrape each pod twice */}}
ports:
- name: "swfs-volume"
port: {{ .Values.volume.port }}
targetPort: {{ .Values.volume.port }}
protocol: TCP
selector:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: volume
{{- end }}
@@ -23,6 +23,9 @@ metadata:
{{- end }}
spec:
clusterIP: None
{{- /* The master hands out ${POD_NAME}.<this service> as soon as a volume server heartbeats, before it is Ready.
Ingress and HTTPRoute use the client-volume Service instead, which publishes only Ready pods. */}}
publishNotReadyAddresses: true
internalTrafficPolicy: {{ $volume.internalTrafficPolicy | default "Cluster" }}
ports:
- name: "swfs-volume"
@@ -55,6 +55,7 @@ spec:
{{- with $volume.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
{{- if $volume.affinity }}
affinity:
@@ -281,7 +282,7 @@ spec:
httpGet:
path: {{ $volume.readinessProbe.httpGet.path }}
port: {{ $volume.port }}
scheme: {{ $volume.readinessProbe.httpGet.scheme }}
scheme: {{ if include "seaweedfs.volumeHttps" $ }}HTTPS{{ else }}{{ $volume.readinessProbe.httpGet.scheme }}{{ end }}
initialDelaySeconds: {{ $volume.readinessProbe.initialDelaySeconds }}
periodSeconds: {{ $volume.readinessProbe.periodSeconds }}
successThreshold: {{ $volume.readinessProbe.successThreshold }}
@@ -293,7 +294,7 @@ spec:
httpGet:
path: {{ $volume.livenessProbe.httpGet.path }}
port: {{ $volume.port }}
scheme: {{ $volume.livenessProbe.httpGet.scheme }}
scheme: {{ if include "seaweedfs.volumeHttps" $ }}HTTPS{{ else }}{{ $volume.livenessProbe.httpGet.scheme }}{{ end }}
initialDelaySeconds: {{ $volume.livenessProbe.initialDelaySeconds }}
periodSeconds: {{ $volume.livenessProbe.periodSeconds }}
successThreshold: {{ $volume.livenessProbe.successThreshold }}
@@ -370,8 +371,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" $ }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" $ }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" $ }}-security-config
{{- end }}
{{- if $.Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -46,6 +46,7 @@ spec:
{{- with .Values.worker.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.worker.restartPolicy }}
{{- if .Values.worker.affinity }}
@@ -227,7 +228,7 @@ spec:
{{- if .Values.worker.containerSecurityContext.enabled }}
securityContext: {{- omit .Values.worker.containerSecurityContext "enabled" | toYaml | nindent 12 }}
{{- end }}
{{- if include "seaweedfs.worker.lanceNamespaceUrl" . }}
{{- if include "seaweedfs.worker.lanceEnabled" . }}
- name: worker-lance
image: {{ template "seaweedfs.worker.image" . }}
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
@@ -236,13 +237,21 @@ spec:
valueFrom:
fieldRef:
fieldPath: metadata.name
{{- /* the URL crosses a shell line; metacharacters must arrive as data, not syntax */}}
- name: LANCE_NAMESPACE_URL
value: {{ include "seaweedfs.worker.lanceNamespaceUrl" . | quote }}
{{- /* only a worker pinned before 4.56 reads these; later ones learn the cluster from admin */}}
{{- with include "seaweedfs.worker.lanceNamespaceUrl" . }}
- name: WEED_LANCE_NAMESPACE
value: {{ . | quote }}
{{- end }}
- name: WEED_MASTERS
value: {{ include "seaweedfs.masterServerArg" . | quote }}
{{- if .Values.filer.filerGroup }}
- name: WEED_FILER_GROUP
value: {{ .Values.filer.filerGroup | quote }}
{{- end }}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.worker "target" $mergedExtraEnvironmentVars) }}
{{- /* a duplicate would win over the chart's value and change --id or --namespace */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "LANCE_NAMESPACE_URL" }}
{{- /* a duplicate would win over the chart's value and change --id or the cluster */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "WEED_LANCE_NAMESPACE" "WEED_MASTERS" "WEED_FILER_GROUP" }}
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
{{- $value := index $mergedExtraEnvironmentVars $key }}
- name: {{ $key }}
@@ -271,11 +280,6 @@ spec:
{{- else }}
--admin={{ template "seaweedfs.fullname" . }}-admin.{{ include "seaweedfs.namespace" . }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
{{- end }}
--namespace="$LANCE_NAMESPACE_URL" \
--masters={{ include "seaweedfs.masterServerArg" . }} \
{{- if .Values.filer.filerGroup }}
--filer-group={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
--tls-ca=/usr/local/share/ca-certificates/ca/tls.crt \
--tls-cert=/usr/local/share/ca-certificates/worker/tls.crt \
@@ -298,7 +302,7 @@ spec:
- name: ca-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/ca/
{{- /* grpc.client, which the worker dials the masters and filers with */}}
{{- /* grpc.client, which the worker dials the filers with */}}
- name: client-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
@@ -341,7 +345,7 @@ spec:
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.worker.sidecars "context" $) | nindent 8 }}
{{- end }}
volumes:
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceNamespaceUrl" .) "")) | nindent 8 }}
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceEnabled" .) "")) | nindent 8 }}
{{- if eq .Values.worker.data.type "hostPath" }}
- name: worker-data
hostPath:
@@ -374,8 +378,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -13,7 +13,7 @@ metadata:
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
spec:
clusterIP: None # Headless service
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- if or .Values.worker.metricsPort $lanceMetrics }}
ports:
{{- if .Values.worker.metricsPort }}
@@ -1,6 +1,6 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.worker.enabled }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- if or .Values.worker.metricsPort $lanceMetrics }}
{{- if .Values.global.seaweedfs.monitoring.enabled }}
apiVersion: monitoring.coreos.com/v1
+6 -8
View File
@@ -136,13 +136,11 @@ func TestVectorNetworkPolicyOverrides(t *testing.T) {
}
}
func TestVectorMetricsImageCompatibility(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
func TestVectorMetricsDefaultImage(t *testing.T) {
output, _ := render(t, "vector.enabled=true", "vector.metricsPort=9329")
for _, want := range []string{"--metrics-port=9329", "path: /ready", "path: /health"} {
if !strings.Contains(output, want) {
t.Fatalf("default image missing %q", want)
}
}
out, err := exec.Command("helm", "template", "vector-test", "..", "--set", "vector.enabled=true", "--set", "vector.metricsPort=9329").CombinedOutput()
if err == nil || !strings.Contains(string(out), "default 4.53 image does not support metrics") {
t.Fatalf("incompatible image accepted: %v %s", err, out)
}
render(t, "vector.enabled=true", "vector.metricsPort=9329", "vector.imageOverride=example/metrics-engine:test")
}
@@ -0,0 +1,107 @@
package tests
import (
"fmt"
"os/exec"
"strings"
"testing"
)
func findDocument(documents []map[string]interface{}, kind, name string) map[string]interface{} {
for _, document := range documents {
if document["kind"] == kind && document["metadata"].(map[string]interface{})["name"] == name {
return document
}
}
return nil
}
func TestVolumeServicePublishesNotReadyPods(t *testing.T) {
_, documents := render(t)
service := findDocument(documents, "Service", "vector-test-seaweedfs-volume")
if service == nil {
t.Fatal("no volume service")
}
if service["spec"].(map[string]interface{})["publishNotReadyAddresses"] != true {
t.Fatal("volume pod DNS names must resolve before the pods are Ready")
}
if findDocument(documents, "Service", "vector-test-seaweedfs-client-volume") != nil {
t.Fatal("client-volume service rendered without ingress or httpRoute")
}
}
func TestVolumeIngressUsesReadyOnlyService(t *testing.T) {
_, documents := render(t, "volume.ingress.enabled=true", "volume.httpRoute.enabled=true", "volume.metricsPort=9327")
client := findDocument(documents, "Service", "vector-test-seaweedfs-client-volume")
if client == nil {
t.Fatal("no client-volume service")
}
spec := client["spec"].(map[string]interface{})
if _, found := spec["publishNotReadyAddresses"]; found {
t.Fatal("client-volume must publish only Ready pods")
}
for _, port := range spec["ports"].([]interface{}) {
if port.(map[string]interface{})["name"] == "metrics" {
t.Fatal("client-volume must not expose metrics, or the ServiceMonitor scrapes each pod twice")
}
}
ingress := findDocument(documents, "Ingress", "ingress-vector-test-seaweedfs-volume")
if ingress == nil {
t.Fatal("no volume ingress")
}
path := ingress["spec"].(map[string]interface{})["rules"].([]interface{})[0].(map[string]interface{})["http"].(map[string]interface{})["paths"].([]interface{})[0].(map[string]interface{})
if backend := path["backend"].(map[string]interface{})["service"].(map[string]interface{})["name"]; backend != "vector-test-seaweedfs-client-volume" {
t.Fatalf("volume ingress backend is %v", backend)
}
route := findDocument(documents, "HTTPRoute", "vector-test-seaweedfs-volume")
if route == nil {
t.Fatal("no volume httpRoute")
}
rule := route["spec"].(map[string]interface{})["rules"].([]interface{})[0].(map[string]interface{})
if backend := rule["backendRefs"].([]interface{})[0].(map[string]interface{})["name"]; backend != "vector-test-seaweedfs-client-volume" {
t.Fatalf("volume httpRoute backend is %v", backend)
}
}
func TestVolumeRoutingServiceDoesNotCollideWithVolumeGroups(t *testing.T) {
_, documents := render(t, "volume.ingress.enabled=true", "volume.httpRoute.enabled=true", "volumes.client.replicas=1")
seen := map[string]bool{}
for _, document := range documents {
key := fmt.Sprint(document["kind"], "/", document["metadata"].(map[string]interface{})["name"])
if seen[key] {
t.Fatalf("%s rendered twice", key)
}
seen[key] = true
}
if !seen["Service/vector-test-seaweedfs-volume-client"] || !seen["Service/vector-test-seaweedfs-client-volume"] {
t.Fatal("volumes.client group Service and the routing Service must both render")
}
}
func TestVolumeRoutingServiceRejectsTruncatedCollision(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
fullname := strings.Repeat("a", 49) + "-client"
output, err := exec.Command("helm", "template", "test", "..", "--set", "fullnameOverride="+fullname, "--set", "volume.ingress.enabled=true").CombinedOutput()
if err == nil || !strings.Contains(string(output), "same name as the volume Service") {
t.Fatalf("colliding routing Service accepted: %v %s", err, output)
}
}
func TestVolumeIngressAllInOne(t *testing.T) {
_, documents := render(t, "allInOne.enabled=true", "volume.ingress.enabled=true")
if findDocument(documents, "Service", "vector-test-seaweedfs-client-volume") != nil {
t.Fatal("client-volume service rendered in all-in-one mode")
}
ingress := findDocument(documents, "Ingress", "ingress-vector-test-seaweedfs-volume")
if ingress == nil {
t.Fatal("no volume ingress")
}
path := ingress["spec"].(map[string]interface{})["rules"].([]interface{})[0].(map[string]interface{})["http"].(map[string]interface{})["paths"].([]interface{})[0].(map[string]interface{})
if backend := path["backend"].(map[string]interface{})["service"].(map[string]interface{})["name"]; backend != "vector-test-seaweedfs-all-in-one" {
t.Fatalf("all-in-one volume ingress backend is %v", backend)
}
}
+31 -9
View File
@@ -45,6 +45,18 @@ global:
volumeRead: 0
filerWrite: 0
filerRead: 0
# Serve the volume servers' HTTP port over TLS with the chart's volume
# certificate, and make every chart component reach them over HTTPS
# ([https.volume] and [https.client] in security.toml). Requires
# enableSecurity and is not supported with allInOne. Clients outside the
# chart (weed mount, the CSI driver) need their own [https.client].
# The volume servers do not ask for client certificates, because kubelet
# probes cannot present one; JWT signing keeps authorizing volume access.
# [https.client] also sends the admin UI's HTTP lookups on masters and
# S3 over HTTPS, which their plain listeners refuse, so the UI can miss
# volume public URLs and refuse SSE-S3 vector buckets.
volumeHttps:
enabled: false
# we will use this serviceAccountName for all ClusterRoles/ClusterRoleBindings
serviceAccountName: "seaweedfs"
serviceAccountAnnotations: {}
@@ -1070,6 +1082,10 @@ filer:
httpsPort: 0
# Suffix of the host name, {bucket}.{domainName}
domainName: ""
# Seconds the gateway keeps serving after SIGTERM while its health checks
# return 503 (see s3.preStopSeconds). Added to the filer pod's 60s
# termination grace period.
preStopSeconds: 0
# enable user & permission to s3 (need to inject to all services)
enableAuth: false
# set to the name of an existing kubernetes Secret with the s3 json config file
@@ -1118,8 +1134,17 @@ s3:
# maxUnavailable: 0
# maxSurge: 25%
updateStrategy: {}
# Time the s3 pod is given to shut down, including any preStop hook
# Time the s3 pod is given to shut down, including any preStop hook.
# With preStopSeconds set, it must be at least preStopSeconds + 15 (the
# in-flight request drain), or the chart refuses to render. A lifecycle
# preStop hook runs before SIGTERM, so add its duration on top; the chart
# cannot tell how long an exec hook takes. preStopSeconds replaces a
# preStop sleep hook.
terminationGracePeriodSeconds: 10
# Seconds the gateway keeps serving after SIGTERM while its health checks
# return 503, so the pod leaves the Service endpoints before it stops
# listening. 0 stops at once.
preStopSeconds: 0
bindAddress: 0.0.0.0
port: 8333
# add additional https port
@@ -1136,7 +1161,7 @@ s3:
# Set to a port number to enable, or 0/null to disable
icebergPort: null
# Lance Namespace port; weed serves 9101 by default, 0 disables it
# (and, unless worker.namespaceUrl points elsewhere, the worker's Lance container)
# (and the worker's Lance container)
lancePort: 9101
loggingOverrideLevel: null
# enable user & permission to s3 (need to inject to all services)
@@ -1318,7 +1343,8 @@ s3:
# Lifecycle hooks for the s3 container. A preStop sleep lets the pod leave
# the Service endpoints before it receives SIGTERM; keep it shorter than
# terminationGracePeriodSeconds.
# terminationGracePeriodSeconds. s3.preStopSeconds does the same from
# inside the gateway and also fails its health checks.
# ref: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/
# Example:
# lifecycle:
@@ -1748,8 +1774,6 @@ vector:
port: 8090
metricsPort: 0
masters: ""
readCacheMB: 512
nprobes: null
extraArgs: []
extraEnvironmentVars: {}
podLabels: {}
@@ -1806,7 +1830,7 @@ worker:
# The lance_* jobs run in their own container, /usr/bin/weed-worker.
# amd64/arm64 only; pin mixed clusters with worker.affinity/nodeSelector.
# It keeps tables through the filers the masters list and reads
# Admin tells it the filers and the S3 gateways' Lance namespaces; it reads
# security.toml. The Lance namespace knows it by a token derived from
# jwt.filer_signing.key, which the chart renders only with
# global.seaweedfs.securityConfig.jwtSigning.filerWrite: true. When S3 has
@@ -1815,9 +1839,6 @@ worker:
# HTTP writes, so clients writing to the filer's HTTP API directly need a JWT
# signed with that key.
# Lance namespace URL override; empty derives it from s3.lancePort.
namespaceUrl: ""
# Metrics port for the Lance worker container; the Go worker keeps metricsPort
lanceMetricsPort: 9328
@@ -2011,6 +2032,7 @@ allInOne:
# The s3-secret.yaml template only reads from .Values.s3.credentials.
# See: s3.credentials.admin.accessKey, s3.credentials.read.accessKey
auditLogConfig: null # S3 audit log configuration (null inherits from s3.auditLogConfig)
preStopSeconds: null # Seconds to keep serving after SIGTERM, added to the pod's 60s grace period (null inherits from s3.preStopSeconds, 0 disables)
trafficDistribution: null # Service traffic distribution (e.g., "PreferClose"); auto-converts to "PreferSameZone" on k8s >=1.35
# You may specify buckets to be created during the install process.
# Buckets may be exposed publicly by setting `anonymousRead` to `true`
+3 -1
View File
@@ -45,6 +45,8 @@ Rule of thumb: start with 3 masters, then grow volume servers with data.
- Metadata store options: PostgreSQL, MySQL, Redis, Cassandra, TiKV, etc.
- Run **3 filers** for HA
- Filers are stateless relative to each other — state lives in the DB
- No quorum among filers: 2 already survive one failure; the third keeps a spare while one is down for upgrades
- Give clients every filer address (e.g. `-filer=f1:8888,f2:8888,f3:8888`) or a load balancer that forwards both the HTTP and gRPC ports (8888 and 18888)
**S3 Servers**
@@ -77,7 +79,7 @@ Keeps housekeeping off the hot path.
|----------------|----------------------|-----------------------------------|
| Master | 3 | Raft quorum, topology, volume map |
| Volume Server | N (scale out) | Stores data needles |
| Filer | 3 | Metadata gateway |
| Filer | 3 (2 minimum) | Metadata gateway, no quorum |
| Metadata DB | HA cluster | Persists filer metadata |
| S3 Server | N (by throughput) | S3 API frontend |
| Admin | 1 | Background job coordinator |
+1019 -1084
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 53 KiB

@@ -156,11 +156,14 @@ public class SeaweedWrite {
entry.clearChunks();
entry.addAllChunks(chunks);
filerClient.getBlockingStub().createEntry(
FilerProto.CreateEntryResponse response = filerClient.getBlockingStub().createEntry(
FilerProto.CreateEntryRequest.newBuilder()
.setDirectory(parentDirectory)
.setEntry(entry)
.build());
if (!Strings.isNullOrEmpty(response.getError())) {
throw new IOException(response.getError());
}
}
}
@@ -262,6 +262,8 @@ message CreateEntryRequest {
// Set on a create a filer forwarded to the entry's ring owner, so the owner
// applies it locally instead of forwarding again. Clients leave it unset.
bool is_moved = 8;
// The store write must be durable before the reply, as for ?fsync=true.
bool fsync = 9;
}
// WriteCondition is the precondition the filer evaluates against the existing
+720 -4
View File
@@ -2302,6 +2302,113 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Writable Volumes per Disk",
"description": "Disks holding more than one writable volume of a collection, and the most writable volumes of a collection on one disk.",
"type": "timeseries",
"id": 262,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 69
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "count by (collection) (sum by (cluster, collection, data_center, rack, node, disk_id) (SeaweedFS_master_writable_volumes_per_disk{cluster=~\"$cluster\", state=\"writable\"}) > 1)",
"range": true,
"refId": "A",
"legendFormat": "{{collection}} disks with 2+"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "max by (collection) (sum by (cluster, collection, data_center, rack, node, disk_id) (SeaweedFS_master_writable_volumes_per_disk{cluster=~\"$cluster\", state=\"writable\"}))",
"range": true,
"refId": "B",
"legendFormat": "{{collection}} max on one disk"
}
],
"pluginVersion": "10.3.1"
}
]
},
@@ -3335,6 +3442,102 @@
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Vacuum Dropped Needles",
"description": "Live needles vacuum dropped because their data could not be read back intact (CRC mismatch, malformed or short record), counted since the volume server started. Any non-zero value means a lost replica copy; the volume server log has each dropped key.",
"type": "timeseries",
"id": 267,
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 54
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, collection) (SeaweedFS_volumeServer_vacuuming_dropped_needles{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{instance}} {{collection}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
@@ -6629,6 +6832,423 @@
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Subscribe Delivery Lag",
"description": "Seconds from a metadata event's mutation until the filer sends it to a subscriber, by stream scope",
"type": "timeseries",
"id": 263,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 71
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_delivery_lag_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "A",
"legendFormat": "p99 {{scope}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.5, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_delivery_lag_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "B",
"legendFormat": "p50 {{scope}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Watermark Hold Duration",
"description": "How long an aggregated read stayed held at one entry until the peers' watermark released it (memory: delivery watermark, disk: flush watermark)",
"type": "timeseries",
"id": 264,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 71
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_hold_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "A",
"legendFormat": "p99 {{scope}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.5, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_hold_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "B",
"legendFormat": "p50 {{scope}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Delivery Claim / Peer Low-Watermark Age",
"description": "Seconds the filer's delivery claim and the peers' delivery and flush low-watermarks trail the clock; -1 while a tracked peer has not signalled",
"type": "timeseries",
"id": 265,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 79
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "max by (instance) (SeaweedFS_filer_meta_delivery_claim_age_seconds{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "claim {{instance}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "max by (instance, kind) (SeaweedFS_filer_meta_peer_low_watermark_age_seconds{cluster=~\"$cluster\"})",
"range": true,
"refId": "B",
"legendFormat": "peer low {{kind}} {{instance}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Subscribers Resumed from Disk",
"description": "Times a metadata subscriber fell off the in-memory ring and resumed from the persisted log",
"type": "timeseries",
"id": 266,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 79
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, scope) (rate(SeaweedFS_filer_subscribe_resume_from_disk{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{scope}} {{instance}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
@@ -6642,7 +7262,7 @@
"h": 8,
"w": 12,
"x": 0,
"y": 71
"y": 87
},
"fieldConfig": {
"defaults": {
@@ -6738,7 +7358,7 @@
"h": 8,
"w": 12,
"x": 12,
"y": 71
"y": 87
},
"fieldConfig": {
"defaults": {
@@ -6834,7 +7454,7 @@
"h": 8,
"w": 12,
"x": 0,
"y": 79
"y": 95
},
"fieldConfig": {
"defaults": {
@@ -6930,7 +7550,7 @@
"h": 8,
"w": 12,
"x": 12,
"y": 79
"y": 95
},
"fieldConfig": {
"defaults": {
@@ -8537,6 +9157,102 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "S3 PUT Stage Duration p99",
"description": "Time an object write (PutObject, UploadPart) spends waiting on the request body, volume assigns, chunk uploads apart from body reads, and the metadata commit after the upload.",
"type": "timeseries",
"id": 268,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 49
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_s3_put_stage_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, operation, stage))",
"range": true,
"refId": "A",
"legendFormat": "{{operation}} {{stage}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
+6
View File
@@ -7143,8 +7143,10 @@ dependencies = [
"aes",
"aes-gcm",
"anyhow",
"arrow-array",
"arrow-cast",
"arrow-schema",
"arrow-select",
"async-trait",
"base64 0.22.1",
"bytes",
@@ -7158,6 +7160,7 @@ dependencies = [
"hmac 0.12.1",
"http",
"hyper-util",
"jsonb",
"jsonwebtoken",
"lance",
"lance-datafusion",
@@ -7190,6 +7193,7 @@ dependencies = [
"tower",
"tracing",
"tracing-subscriber",
"uuid",
"x509-parser",
"zstd",
]
@@ -7208,6 +7212,7 @@ dependencies = [
"lance",
"lance-index",
"lance-linalg",
"lance-select",
"lance-table",
"object_store",
"roaring",
@@ -7236,6 +7241,7 @@ dependencies = [
"futures",
"lance",
"lance-arrow",
"lance-index",
"lance-linalg",
"moka",
"object_store",
+3 -3
View File
@@ -15,12 +15,12 @@ Point an AWS S3 Vectors client at the S3 endpoint, normally `http://localhost:83
| `--masters` | Required | Comma-separated master addresses |
| `--listen` | `127.0.0.1:8090` | gRPC listener and registered address |
| `--filer-group` | Empty | Filer group used for table storage |
| `--read-cache-mb` | `512` | Immutable data/index read cache; zero disables it |
| `--nprobes` | Automatic | ANN partitions searched per query |
| `--metrics-port` | `0` | HTTP metrics and health listener; zero disables it |
| `--metrics-ip` | `127.0.0.1` | HTTP listener address |
| `--security-toml` | Discovered | Cluster certificates, signing keys and encryption keys |
The engine caches a quarter of the memory it may use (its cgroup limit, else the machine's), split 2:4:1 between file reads, loaded indexes and table metadata, and logs the sizes at startup. Each query probes a tenth of the index's partitions, at least 8, and more under a filter.
The HTTP listener provides `/health`, `/ready`, and `/metrics`. Readiness requires an active registration with the master. The gRPC listener also implements the standard health service for `vector_pb.VectorService` and the whole server. These health statuses follow master registration.
Metrics use the `SeaweedFS_vector_` prefix:
@@ -35,6 +35,6 @@ The S3 gateway separately publishes `SeaweedFS_s3_` request metrics with `type="
For mutual TLS, configure `[grpc.vector]` for the engine's server certificate, `[grpc.client]` for its master/filer connections, and the cluster CA. HTTPS volume reads also use `[https.client]`. The engine follows the same signing and encryption configuration as the other cluster clients.
Run the Lance maintenance worker against the same masters and Lance namespace to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
Run the Lance maintenance worker against the cluster's admin to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
The integration suite at `test/s3vectors` runs the same API and observability checks against both Go and Rust volume servers, including mutual TLS, signed volume reads, and encrypted volume data.
+1
View File
@@ -22,6 +22,7 @@ object_store = "0.13"
lance-index = "10"
lance-linalg = "10"
lance-table = "10"
lance-select = "10"
arrow-array = "58"
arrow-cast = "58"
arrow-schema = "58"
@@ -139,6 +139,7 @@ mod tests {
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
@@ -167,6 +168,7 @@ mod tests {
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let filtered = ann(&dataset, &table, &query).await.unwrap();
let exact = flat(&dataset, &table, &query).await.unwrap();
@@ -204,6 +206,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
+17 -7
View File
@@ -4,6 +4,7 @@
//! compares the elements as typed JSON values: Lance's compares their text, so
//! 1 would match "1".
use std::collections::HashMap;
use std::sync::Arc;
use arrow_array::builder::{BooleanBuilder, StringBuilder};
@@ -19,13 +20,21 @@ use lance::deps::datafusion::logical_expr::{
ColumnarValue, Expr, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Volatility,
};
/// Set `filter` on the scanner with the JSONPath functions swapped.
pub(crate) fn apply(scanner: &mut Scanner, filter: &str) -> anyhow::Result<()> {
/// Set `filter` on the scanner with the JSONPath functions swapped and the
/// conjuncts on `ready` indexed keys answered by their columns, which it
/// returns.
pub(crate) fn apply(
scanner: &mut Scanner,
filter: &str,
ready: &HashMap<String, String>,
) -> anyhow::Result<Vec<crate::indexed_filter::Indexed>> {
scanner.filter(filter)?;
if let Some(expr) = scanner.get_expr_filter()? {
scanner.filter_expr(swap(expr)?);
}
Ok(())
let Some(expr) = scanner.get_expr_filter()? else {
return Ok(Vec::new());
};
let (expr, indexed) = crate::indexed_filter::rewrite(expr, ready);
scanner.filter_expr(swap(expr)?);
Ok(indexed)
}
fn swap(expr: Expr) -> Result<Expr> {
@@ -268,7 +277,7 @@ mod tests {
async fn keys(dataset: &Dataset, filter: &str, swapped: bool) -> anyhow::Result<Vec<String>> {
let mut scanner = dataset.scan();
if swapped {
apply(&mut scanner, filter)?;
apply(&mut scanner, filter, &HashMap::new())?;
} else {
scanner.filter(filter)?;
}
@@ -395,6 +404,7 @@ mod tests {
apply(
&mut scanner,
r#"json_extract(`metadata`, '$["k"]') = '"v"' AND json_exists(`metadata`, '$["k"]') AND json_get_string(`metadata`, 'k') = 'v' AND json_array_contains(`metadata`, '$["k"]', '"v"') AND NOT json_array_contains(`metadata`, '$["k"]', key)"#,
&HashMap::new(),
)
.unwrap();
let mut swapped = Vec::new();
+78
View File
@@ -104,6 +104,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
}
}
@@ -198,6 +199,83 @@ mod tests {
assert_eq!(filtered.len(), 10);
}
/// A filtered query through the index returns every eligible row when
/// fewer than k match, though the probed partitions cannot hold them all:
/// 400 of 4000 rows match, the index has 63 partitions and probes at most
/// 32 of them.
#[tokio::test]
async fn filtered_ann_returns_every_match_below_k() {
let dir = TempDir::new().unwrap();
let rows = scattered(4000, 8, 0x9E3779B97F4A7C15);
let tags: Vec<&str> = (0..4000)
.map(|i| if i % 10 == 0 { "rare" } else { "common" })
.collect();
let mut dataset = testing::write_dataset(&dir, &rows, &tags).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(
&mut dataset,
&table.vector_column,
INDEX_NAME,
partitions_for(4000),
false,
)
.await
.unwrap();
assert_eq!(partitions_for(4000), 63);
for vector in &scattered(3, 8, 0xD1B54A32D192ED03) {
let q = Query {
filter: Some("tag = 'rare'".to_string()),
..exact(vector, 500)
};
let flat = query::flat(&dataset, &table, &q).await.unwrap();
assert_eq!(flat.len(), 400);
let ann = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(ann.len(), 400, "the index path dropped eligible rows");
for (f, a) in flat.iter().zip(ann.iter()) {
assert!((f.distance - a.distance).abs() < 1e-5);
}
}
}
/// When no more than k rows match, every match comes back with its own
/// distance, nearest first — not the rows the probes missed with an
/// infinite distance. Ten fragments of 400 rows, 5 of them matching.
#[tokio::test]
async fn filtered_ann_scores_every_match_at_or_below_k() {
let dir = TempDir::new().unwrap();
let rows = scattered(4000, 8, 0x9E3779B97F4A7C15);
let tags: Vec<&str> = (0..4000)
.map(|i| if i % 800 == 0 { "rare" } else { "common" })
.collect();
let mut dataset = testing::write_dataset(&dir, &rows[..400], &tags[..400]).await;
for chunk in 1..10 {
let r = chunk * 400..(chunk + 1) * 400;
testing::append_dataset(&mut dataset, &rows[r.clone()], &tags[r]).await;
}
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(&mut dataset, &table.vector_column, INDEX_NAME, 63, false)
.await
.unwrap();
for vector in &scattered(3, 8, 0xD1B54A32D192ED03) {
for k in [5, 10] {
let q = Query {
filter: Some("tag = 'rare'".to_string()),
..exact(vector, k)
};
let flat = query::flat(&dataset, &table, &q).await.unwrap();
assert_eq!(flat.len(), 5);
let ann = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(ann.len(), 5);
for (f, a) in flat.iter().zip(ann.iter()) {
assert!(
(f.distance - a.distance).abs() < 1e-5,
"k={k}: {flat:?} vs {ann:?}"
);
}
}
}
}
#[tokio::test]
async fn default_probes_take_the_largest_index() {
use lance::index::DatasetIndexExt;
@@ -0,0 +1,739 @@
//! Filters on indexed metadata keys (see `weed_lance_worker::metadata_index`).
//!
//! The gateway renders a string `$eq` or `$in` on a key as an OR of
//! `json_extract(metadata, P) = '"v"'` (or `IN`) and
//! `json_array_contains(metadata, P, '"v"')` over the same values. In the
//! parsed filter, such a top-level conjunct on a ready key is replaced by
//! `array_has` / `array_has_any` on the key's column, which its LABEL_LIST
//! index answers. Everything else, including `$ne` and `$nin`, stays on the
//! JSON path.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use anyhow::Result;
use jsonb::OwnedJsonb;
use lance::Dataset;
use lance::deps::datafusion::common::{Column, ScalarValue};
use lance::deps::datafusion::functions_nested::expr_fn::{array_has, array_has_any};
use lance::deps::datafusion::logical_expr::utils::split_conjunction_owned;
use lance::deps::datafusion::logical_expr::{BinaryExpr, Expr, Operator};
use lance::deps::datafusion::prelude::lit;
use weed_lance_worker::metadata_index::{self, State};
const METADATA_COLUMN: &str = "metadata";
/// The column of each ready indexed key of `dataset`, by metadata key.
pub(crate) fn ready_columns(dataset: &Dataset) -> HashMap<String, String> {
let schema: arrow_schema::Schema = dataset.schema().into();
metadata_index::indexed_keys(&schema)
.into_iter()
.filter(|k| k.state == Some(State::Ready))
.map(|k| (k.key, k.column))
.collect()
}
/// A conjunct a key's column answers: rows whose `column` holds one of
/// `values`.
#[derive(Debug, Clone)]
pub(crate) struct Indexed {
pub column: String,
pub values: Vec<String>,
pub expr: Expr,
}
/// `filter` with each top-level conjunct that is a string `$eq` or `$in` on
/// a key in `ready` answered by the key's column instead, and those
/// replacements.
pub(crate) fn rewrite(filter: Expr, ready: &HashMap<String, String>) -> (Expr, Vec<Indexed>) {
if ready.is_empty() {
return (filter, Vec::new());
}
let mut indexed: Vec<Indexed> = Vec::new();
let mut rewritten: Option<Expr> = None;
for conjunct in split_conjunction_owned(filter) {
let replacement = string_membership(&conjunct).and_then(|(key, values)| {
let name = ready.get(&key)?;
let column = Expr::Column(Column::from_name(name));
let expr = match values.as_slice() {
[one] => array_has(column, lit(one.as_str())),
_ => {
let values: Vec<ScalarValue> = values
.iter()
.map(|v| ScalarValue::Utf8(Some(v.clone())))
.collect();
let list = ScalarValue::new_list(&values, &arrow_schema::DataType::Utf8, true);
array_has_any(column, Expr::Literal(ScalarValue::List(list), None))
}
};
Some(Indexed {
column: name.clone(),
values,
expr,
})
});
let part = match replacement {
Some(found) => {
let expr = found.expr.clone();
indexed.push(found);
expr
}
None => conjunct,
};
rewritten = Some(and(rewritten, part));
}
(rewritten.unwrap_or(lit(true)), indexed)
}
fn and(left: Option<Expr>, right: Expr) -> Expr {
match left {
Some(left) => Expr::BinaryExpr(BinaryExpr::new(
Box::new(left),
Operator::And,
Box::new(right),
)),
None => right,
}
}
/// The key and string values of a conjunct meaning "the key holds one of
/// these strings, or an array with one of them": the OR of scalar matches
/// and array-member matches over the same values and key.
fn string_membership(expr: &Expr) -> Option<(String, Vec<String>)> {
let mut disjuncts = Vec::new();
split_or(expr, &mut disjuncts);
let mut path: Option<&str> = None;
let mut scalars = BTreeSet::new();
let mut elements = BTreeSet::new();
for disjunct in disjuncts {
let (p, kind) = match unwrap_false_coalesce(disjunct) {
Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Eq,
right,
}) => (
json_function(left, "json_extract")?,
Member::Scalar(vec![utf8(right)?]),
),
Expr::InList(list) if !list.negated => (
json_function(&list.expr, "json_extract")?,
Member::Scalar(list.list.iter().map(utf8).collect::<Option<_>>()?),
),
Expr::ScalarFunction(f) if f.func.name() == "json_array_contains" => {
let [data, p, value] = f.args.as_slice() else {
return None;
};
if !is_metadata(data) {
return None;
}
let element: serde_json::Value = serde_json::from_str(utf8(value)?).ok()?;
(utf8(p)?, Member::Element(element.as_str()?.to_string()))
}
_ => return None,
};
if path.is_some_and(|q| q != p) {
return None;
}
path = Some(p);
match kind {
Member::Scalar(values) => scalars.extend(values.into_iter().map(str::to_string)),
Member::Element(value) => {
elements.insert(value);
}
}
}
let key = json_path_key(path?)?;
let rendered: BTreeSet<String> = elements
.iter()
.map(|s| jsonb_text(s))
.collect::<Option<_>>()?;
(!elements.is_empty() && rendered == scalars).then(|| (key, elements.into_iter().collect()))
}
enum Member<'a> {
Scalar(Vec<&'a str>),
Element(String),
}
fn split_or<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) {
match expr {
Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Or,
right,
}) => {
split_or(left, out);
split_or(right, out);
}
Expr::Alias(alias) => split_or(&alias.expr, out),
other => out.push(other),
}
}
/// `x` for `COALESCE(x, false)` or its simplified `x IS NOT NULL AND x`;
/// either is false where `x` is null, which a top-level conjunct treats alike.
fn unwrap_false_coalesce(expr: &Expr) -> &Expr {
match expr {
Expr::ScalarFunction(f) if f.func.name() == "coalesce" => match f.args.as_slice() {
[x, Expr::Literal(ScalarValue::Boolean(Some(false)), _)] => x,
_ => expr,
},
Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::And,
right,
}) => match left.as_ref() {
Expr::IsNotNull(x) if x == right => right,
_ => expr,
},
_ => expr,
}
}
fn utf8(expr: &Expr) -> Option<&str> {
match expr {
Expr::Literal(ScalarValue::Utf8(Some(s)) | ScalarValue::LargeUtf8(Some(s)), _) => {
Some(s.as_str())
}
_ => None,
}
}
fn is_metadata(expr: &Expr) -> bool {
matches!(expr, Expr::Column(c) if c.name == METADATA_COLUMN)
}
/// The JSONPath literal of `name(metadata, path)`.
fn json_function<'a>(expr: &'a Expr, name: &str) -> Option<&'a str> {
match expr {
Expr::ScalarFunction(f) if f.func.name() == name => match f.args.as_slice() {
[data, path] if is_metadata(data) => utf8(path),
_ => None,
},
_ => None,
}
}
/// The key of a `$["key"]` path, with `\\` and `\"` unescaped.
fn json_path_key(path: &str) -> Option<String> {
let inner = path.strip_prefix("$[\"")?.strip_suffix("\"]")?;
let mut key = String::with_capacity(inner.len());
let mut chars = inner.chars();
while let Some(c) = chars.next() {
match c {
'\\' => match chars.next()? {
c @ ('\\' | '"') => key.push(c),
_ => return None,
},
'"' => return None,
c => key.push(c),
}
}
Some(key)
}
/// What json_extract returns for a stored string `s`.
fn jsonb_text(s: &str) -> Option<String> {
let value: OwnedJsonb = serde_json::to_string(s).ok()?.parse().ok()?;
Some(value.to_string())
}
/// Segments searched at once when counting.
const PARALLEL_SEGMENTS: usize = 8;
/// The rows of `scope` (every fragment when None) whose column matches
/// `indexed`, or None once there are more than `limit`. Segments are
/// searched newest first, several at once, and counting stops as soon as
/// the total passes the limit. Rows the index has not reached are counted
/// by a read of the column. Deleted rows an index segment still lists
/// count too: the total is an upper bound, which only ever sends a query
/// to the vector index instead of an exact scan.
pub(crate) async fn count_indexed(
dataset: &Dataset,
indexed: &Indexed,
scope: Option<&[u64]>,
limit: u64,
) -> Result<Option<u64>> {
use futures::{StreamExt, TryStreamExt};
use lance::index::DatasetIndexInternalExt;
use lance_index::metrics::NoOpMetricsCollector;
use lance_index::scalar::{LabelListQuery, SearchResult};
use lance_select::RowSetOps;
let scope: Option<roaring::RoaringBitmap> =
scope.map(|ids| ids.iter().map(|id| *id as u32).collect());
let segments = metadata_index::segments(dataset, &indexed.column).await?;
let query = LabelListQuery::HasAnyLabel(
indexed
.values
.iter()
.map(|v| ScalarValue::Utf8(Some(v.clone())))
.collect(),
);
let mut searches: Vec<futures::future::BoxFuture<'_, Result<u64>>> = Vec::new();
for segment in segments.iter().rev() {
let fragments = match &scope {
Some(scope) => &segment.fragments & scope,
None => segment.fragments.clone(),
};
if fragments.is_empty() {
continue;
}
let uuid = segment.uuid;
let query = &query;
searches.push(Box::pin(async move {
let index = dataset
.open_scalar_index(&indexed.column, &uuid, &NoOpMetricsCollector)
.await?;
let mut found = match index.search(query, &NoOpMetricsCollector).await? {
SearchResult::Exact(rows) | SearchResult::AtMost(rows) => rows.true_rows(),
SearchResult::AtLeast(_) => anyhow::bail!("a LABEL_LIST index answered AtLeast"),
};
found.retain_fragments(fragments.iter());
Ok(found.len().unwrap_or(u64::MAX))
}));
}
let mut counts = futures::stream::iter(searches).buffered(PARALLEL_SEGMENTS);
let mut total = 0u64;
while let Some(count) = counts.try_next().await? {
total = total.saturating_add(count);
if total > limit {
return Ok(None);
}
}
let unindexed: Vec<lance_table::format::Fragment> = dataset
.fragments()
.iter()
.filter(|f| !segments.iter().any(|s| s.fragments.contains(f.id as u32)))
.filter(|f| scope.as_ref().is_none_or(|s| s.contains(f.id as u32)))
.cloned()
.collect();
if !unindexed.is_empty() {
let mut scanner = dataset.scan();
scanner
.filter_expr(indexed.expr.clone())
.with_fragments(unindexed);
total = total.saturating_add(scanner.count_rows().await?);
}
Ok((total <= limit).then_some(total))
}
/// How a filter compares a key.
pub mod operand {
pub const STRING: u8 = 1;
pub const NUMBER: u8 = 2;
pub const BOOL: u8 = 4;
pub const EXISTS: u8 = 8;
}
/// The metadata keys `filter` reads, each with the [`operand`] kinds it is
/// compared with.
pub fn filter_keys(dataset: &Dataset, filter: &str) -> Result<BTreeMap<String, u8>> {
let mut scanner = dataset.scan();
scanner.filter(filter)?;
let mut keys = BTreeMap::new();
if let Some(expr) = scanner.get_expr_filter()? {
collect_keys(&expr, &mut keys);
}
Ok(keys)
}
fn literal_kind(text: &str) -> u8 {
match serde_json::from_str::<serde_json::Value>(text) {
Ok(serde_json::Value::String(_)) => operand::STRING,
Ok(serde_json::Value::Number(_)) => operand::NUMBER,
Ok(serde_json::Value::Bool(_)) => operand::BOOL,
// json_extract's text of a string with control characters is not
// JSON, but it is quoted.
_ if text.starts_with('"') => operand::STRING,
_ => 0,
}
}
fn collect_keys(expr: &Expr, keys: &mut BTreeMap<String, u8>) {
let mut note = |path: &str, kind: u8| {
if let Some(key) = json_path_key(path) {
*keys.entry(key).or_default() |= kind;
}
};
match expr {
Expr::TryCast(cast) if extract(&cast.expr).is_some() => {
note(extract(&cast.expr).unwrap_or_default(), operand::NUMBER);
return;
}
Expr::BinaryExpr(BinaryExpr { left, right, .. }) => {
if let (Some(path), Some(value)) = (extract(left), utf8(right)) {
note(path, literal_kind(value));
return;
}
}
Expr::InList(list) => {
if let Some(path) = extract(&list.expr) {
let kind = list
.list
.iter()
.filter_map(utf8)
.fold(0, |k, v| k | literal_kind(v));
note(path, kind);
return;
}
}
Expr::ScalarFunction(f) if is_json_function(f.func.name()) => {
if let [data, path, rest @ ..] = f.args.as_slice()
&& is_metadata(data)
&& let Some(path) = utf8(path)
{
let kind = match (f.func.name(), rest) {
("json_exists", _) => operand::EXISTS,
(_, [value]) => utf8(value).map_or(0, literal_kind),
_ => 0,
};
note(path, kind);
return;
}
}
_ => {}
}
for child in children(expr) {
collect_keys(child, keys);
}
}
fn extract(expr: &Expr) -> Option<&str> {
json_function(expr, "json_extract")
}
fn is_json_function(name: &str) -> bool {
matches!(name, "json_extract" | "json_exists" | "json_array_contains")
}
fn children(expr: &Expr) -> Vec<&Expr> {
use lance::deps::datafusion::common::tree_node::TreeNode;
let mut out = Vec::new();
let _ = expr.apply_children(|child| {
out.push(child);
Ok(lance::deps::datafusion::common::tree_node::TreeNodeRecursion::Continue)
});
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query::{self, Query};
use crate::table::VectorTable;
use arrow_array::{FixedSizeListArray, RecordBatch, RecordBatchIterator, StringArray};
use arrow_schema::{DataType, Field, Schema};
use lance::index::DatasetIndexExt;
use lance_index::IndexType;
use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams};
use lance_linalg::distance::DistanceType;
use std::sync::Arc;
use tempfile::TempDir;
const DIM: usize = 4;
/// The gateway's text for `{"author": "<v>"}`.
fn eq(field: &str, json: &str) -> String {
let json = json.replace('\'', "''");
format!(
"(COALESCE(json_extract(`metadata`, '$[\"{field}\"]') = '{json}', false) OR COALESCE(json_array_contains(`metadata`, '$[\"{field}\"]', '{json}'), false))"
)
}
/// The gateway's text for `{"author": {"$in": [<strings>]}}`.
fn among(values: &[&str]) -> String {
let scalars: Vec<String> = values.iter().map(|v| format!("'\"{v}\"'")).collect();
let mut groups = vec![format!(
"COALESCE(json_extract(`metadata`, '$[\"author\"]') in ({}), false)",
scalars.join(", ")
)];
for v in values {
groups.push(format!(
"COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"{v}\"'), false)"
));
}
format!("({})", groups.join(" OR "))
}
/// Rows `u0..u<n>` by author, plus a few others, in fragments of 100,
/// with the author column ready and indexed and a vector index.
async fn dataset(dir: &TempDir, rows: usize) -> Dataset {
let metadata = Field::new("metadata", DataType::Utf8, true)
.with_metadata([("ARROW:extension:name".to_string(), "arrow.json".to_string())].into());
let 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,
),
metadata,
metadata_index::field("_mk_0", "author", State::Ready),
]));
let metas: Vec<serde_json::Value> = (0..rows)
.map(|i| match i % 10 {
0 => serde_json::json!({"author": "rare"}),
1 => serde_json::json!({"author": ["many", "rare2"]}),
_ => serde_json::json!({"author": "many", "n": i}),
})
.collect();
let batches: Vec<RecordBatch> = (0..rows)
.step_by(100)
.map(|start| {
let range = start..(start + 100).min(rows);
RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(
range.clone().map(|i| format!("k{i}")).collect::<Vec<_>>(),
)),
Arc::new(FixedSizeListArray::from_iter_primitive::<
arrow_array::types::Float32Type,
_,
_,
>(
range.clone().map(|i| {
Some((0..DIM).map(move |j| Some(((i * 31 + j * 17) % 97) as f32)))
}),
DIM as i32,
)),
Arc::new(StringArray::from(
range
.clone()
.map(|i| Some(metas[i].to_string()))
.collect::<Vec<_>>(),
)),
metadata_index::column_from_json(range.map(|i| Some(&metas[i])), "author"),
],
)
.unwrap()
})
.collect();
let uri = dir.path().to_str().unwrap();
let mut dataset = None::<Dataset>;
for batch in batches {
let reader = RecordBatchIterator::new(vec![Ok(batch)], schema.clone());
dataset = Some(match dataset {
None => Dataset::write(reader, uri, None).await.unwrap(),
Some(mut d) => {
d.append(reader, None).await.unwrap();
d
}
});
}
let mut dataset = dataset.unwrap();
dataset
.create_index(
&["_mk_0"],
IndexType::LabelList,
None,
&ScalarIndexParams::for_builtin(BuiltinIndexType::LabelList),
true,
)
.await
.unwrap();
crate::index::build(&mut dataset, "vector", crate::index::INDEX_NAME, 4, false)
.await
.unwrap();
dataset
}
fn rewritten(dataset: &Dataset, filter: &str) -> (String, Option<String>) {
let mut scanner = dataset.scan();
let indexed = crate::filter::apply(&mut scanner, filter, &ready_columns(dataset)).unwrap();
(
scanner.get_expr_filter().unwrap().unwrap().to_string(),
indexed.first().map(|i| i.expr.to_string()),
)
}
#[tokio::test]
async fn string_eq_and_in_on_a_ready_key_use_its_column() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 200).await;
assert_eq!(
ready_columns(&dataset),
HashMap::from([("author".to_string(), "_mk_0".to_string())])
);
for (filter, want) in [
(eq("author", "\"rare\""), Some("array_has(_mk_0, Utf8(\"rare\"))")),
(
among(&["rare", "many"]),
Some("array_has_any(_mk_0, List([many, rare]))"),
),
(
format!("{} AND TRY_CAST(json_extract(`metadata`, '$[\"n\"]') AS DOUBLE) > 3", eq("author", "\"rare\"")),
Some("array_has(_mk_0, Utf8(\"rare\"))"),
),
(eq("author", "\"o'neil \\\"q\\\"\""), Some("array_has(_mk_0, Utf8(\"o'neil \"q\"\"))")),
(
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"c\\u0001d\\n\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"c\\u0001d\\n\"'), false))".to_string(),
Some("array_has(_mk_0, Utf8(\"c\u{1}d\n\"))"),
),
// The scalar half's text is not what json_extract returns for
// the array half's string, so the two do not agree.
(
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"c\\u{1}d\\n\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"c\\u0001d\\n\"'), false))".to_string(),
None,
),
// Not a string, not this key, or not every value on both sides.
(eq("author", "true"), None),
(eq("other", "\"rare\""), None),
(format!("NOT {}", eq("author", "\"rare\"")), None),
(format!("NOT {}", among(&["rare", "many"])), None),
(
"COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"rare\"', false)".to_string(),
None,
),
(
among(&["rare", "many"]).replace("'\"many\"'), false))", "'\"other\"'), false))"),
None,
),
("json_exists(`metadata`, '$[\"author\"]')".to_string(), None),
(format!("({} OR json_exists(`metadata`, '$[\"n\"]'))", eq("author", "\"rare\"")), None),
] {
let (expr, indexed) = rewritten(&dataset, &filter);
assert_eq!(indexed.as_deref(), want, "{filter}");
assert_eq!(expr.contains("json_"), want.is_none() || filter.contains(" AND "), "{filter}: {expr}");
}
}
/// The planner scores few matches exactly and leaves many to the vector
/// index, per scope.
#[tokio::test]
async fn few_indexed_matches_are_scored_exactly() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 1000).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = |filter: &str, fragments: Option<Vec<u64>>| Query {
vector: vec![1.0, 2.0, 3.0, 4.0],
k: 10,
filter: Some(filter.to_string()),
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
index_segments: None,
fragments,
exact_match_limit: None,
};
let rare = eq("author", "\"rare\"");
let many = eq("author", "\"many\"");
let few = |q: Query| {
let (dataset, table) = (&dataset, &table);
async move {
query::few_indexed_matches(dataset, table, &q)
.await
.unwrap()
}
};
// 100 and 900 matches, and 90 in the first two fragments.
assert!(few(query(&rare, None)).await);
assert!(!few(query(&many, None)).await);
let first = Some(vec![0, 1]);
assert!(few(query(&many, first.clone())).await);
assert!(
!few(Query {
exact_match_limit: Some(0),
..query(&rare, None)
})
.await
);
// A JSON-only filter is not counted.
assert!(!few(query("json_exists(`metadata`, '$[\"n\"]')", None)).await);
for (filter, fragments) in [(&rare, None), (&many, first)] {
let q = query(filter, fragments);
let exact = query::flat(&dataset, &table, &q).await.unwrap();
let got = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(got.len(), 10);
for (g, e) in got.iter().zip(&exact) {
assert!(
(g.distance - e.distance).abs() < 1e-4,
"{got:?} vs {exact:?}"
);
}
}
}
#[tokio::test]
async fn the_plan_reads_the_scalar_index() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 300).await;
let mut scanner = dataset.scan();
crate::filter::apply(
&mut scanner,
&eq("author", "\"rare\""),
&ready_columns(&dataset),
)
.unwrap();
let plan = scanner.explain_plan(true).await.unwrap();
assert!(plan.contains("LabelList"), "{plan}");
assert!(!plan.contains("json_"), "{plan}");
}
#[tokio::test]
async fn filter_keys_note_how_each_key_is_compared() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 100).await;
let filter = format!(
"{} AND TRY_CAST(json_extract(`metadata`, '$[\"n\"]') AS DOUBLE) > 3 AND NOT json_exists(`metadata`, '$[\"a.b\\\"c\"]') AND COALESCE(json_extract(`metadata`, '$[\"f\"]') = 'true', false)",
eq("author", "\"rare\"")
);
let keys = filter_keys(&dataset, &filter).unwrap();
assert_eq!(
keys,
BTreeMap::from([
("a.b\"c".to_string(), operand::EXISTS),
("author".to_string(), operand::STRING),
("f".to_string(), operand::BOOL),
("n".to_string(), operand::NUMBER),
])
);
}
/// Counting walks the segments, keeps to the scope and stops once over
/// the limit.
#[tokio::test]
async fn counts_follow_segments_and_scope() {
let dir = TempDir::new().unwrap();
let mut dataset = dataset(&dir, 1000).await;
dataset.drop_index("_mk_0_idx").await.unwrap();
// Ten fragments of 100 rows: four segments of up to 300 rows.
let ids: Vec<u64> = dataset.fragments().iter().map(|f| f.id).collect();
metadata_index::index_fragments(&mut dataset, "_mk_0", 300, 0)
.await
.unwrap();
let segments = metadata_index::segments(&dataset, "_mk_0").await.unwrap();
assert_eq!(segments.len(), 4);
let ready = ready_columns(&dataset);
let indexed =
crate::filter::apply(&mut dataset.scan(), &eq("author", "\"rare\""), &ready).unwrap();
let rare = &indexed[0];
// "rare" in rows i % 10 == 0, "rare2" never matches it.
assert_eq!(
count_indexed(&dataset, rare, None, 1_000).await.unwrap(),
Some(100)
);
assert_eq!(count_indexed(&dataset, rare, None, 99).await.unwrap(), None);
assert_eq!(
count_indexed(&dataset, rare, Some(&ids[..2]), 1_000)
.await
.unwrap(),
Some(20)
);
assert_eq!(
count_indexed(&dataset, rare, Some(&ids[9..]), 1_000)
.await
.unwrap(),
Some(10)
);
assert_eq!(
count_indexed(&dataset, rare, Some(&[]), 1_000)
.await
.unwrap(),
Some(0)
);
}
}
+1
View File
@@ -8,6 +8,7 @@
pub mod coverage;
mod filter;
pub mod index;
pub mod indexed_filter;
pub mod maintenance;
pub mod query;
pub mod segments;
+74 -54
View File
@@ -2,35 +2,27 @@ use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use weed_lance_worker::catalog::{NamespaceClient, SigningKey, TableDescription, parse_id};
use weed_lance_worker::cluster::Cluster;
use weed_lance_worker::dataset::{self, Storage};
use weed_vector_core::coverage;
use weed_vector_core::index;
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 that says where a table is, and the masters whose filers hold
/// it.
/// Finds everything through the masters: the S3 gateway whose Lance Namespace
/// says where a table is, and the filers that hold it.
#[derive(Parser, Debug)]
#[command(
name = "weed-vector",
about = "Describe, query and index S3 Vectors tables"
)]
struct Args {
/// Lance namespace the tables live in.
#[arg(
long,
default_value = "http://localhost:9101",
env = "WEED_LANCE_NAMESPACE"
)]
namespace: String,
/// Comma-separated master addresses, whose filers the tables are kept
/// through. A table named by a local URI needs none.
/// Comma-separated master addresses. A table named by a local path needs
/// none.
#[arg(long, alias = "master", env = "WEED_MASTERS")]
masters: Option<String>,
/// The filer group whose filers hold the tables.
/// The filer group whose gateways and filers hold the tables.
#[arg(
long,
alias = "filer.group",
@@ -45,7 +37,7 @@ struct Args {
filer_signing_key: Option<String>,
/// The cluster's security.toml; by default the file weed processes find
/// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
/// in ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<std::path::PathBuf>,
@@ -146,34 +138,44 @@ enum IndexAction {
},
}
/// `id` is a delimiter-joined table id; when it looks like a URI the dataset
/// is opened directly, skipping the namespace: an `s3://` URI on the
/// cluster's storage, a local path (`/path/...`, `file://...`) as it is.
async fn open_dataset(
client: &NamespaceClient,
id: &str,
storage: &Storage,
) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
}
if storage.0.is_none() {
bail!("{id} is kept on the cluster and needs --masters");
}
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
/// Where tables are found: through the cluster the masters name, or, for a
/// local path, nowhere in particular.
struct Tables {
cluster: Option<Cluster>,
storage: Storage,
signing_key: Option<SigningKey>,
}
impl Tables {
/// `id` is a delimiter-joined table id, looked up in the namespace of a
/// gateway the masters name; when it looks like a URI the dataset is
/// opened directly: an `s3://` URI on the cluster's storage, a local path
/// (`/path/...`, `file://...`) as it is.
async fn open(&self, id: &str) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
}
let Some(cluster) = &self.cluster else {
bail!("{id} is kept on the cluster and needs --masters");
};
return dataset::open_at(&description, storage.wrapper(id).await?, None).await;
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
};
return dataset::open_at(&description, self.storage.wrapper(id).await?, None).await;
}
let client = NamespaceClient::new(cluster.lance_namespace().await?)
.with_signing_key(self.signing_key.as_ref());
Ok(dataset::open(&client, &parse_id(id), &self.storage)
.await?
.dataset)
}
let table = dataset::open(client, &parse_id(id), storage).await?;
Ok(table.dataset)
}
#[tokio::main]
@@ -188,20 +190,26 @@ async fn main() -> Result<()> {
.init();
let args = Args::parse();
let security =
weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?;
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
let signing_key = SigningKey::new(
args.filer_signing_key
.or_else(|| security.get("jwt.filer_signing.key")),
);
let client = NamespaceClient::new(args.namespace).with_signing_key(signing_key.as_ref());
let storage = match &args.masters {
let tables = match &args.masters {
Some(masters) => {
let cluster =
weed_lance_worker::cluster::Cluster::new(masters, &args.filer_group, &security)?;
Storage(Some(cluster.storage(&security).await?))
let cluster = Cluster::new(masters, &args.filer_group, &security)?;
let storage = Storage(Some(cluster.storage(&security).await?));
Tables {
cluster: Some(cluster),
storage,
signing_key,
}
}
None => Storage::default(),
None => Tables {
cluster: None,
storage: Storage::default(),
signing_key,
},
};
match args.command {
@@ -210,7 +218,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = tables.open(&id).await?;
let schema: arrow_schema::Schema = dataset.schema().into();
let resolved =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref());
@@ -250,7 +258,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = tables.open(&id).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
let coverages = coverage::coverage(&dataset, &vector.vector_column).await?;
@@ -262,7 +270,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = open_dataset(&client, &id, &storage).await?;
let dataset = tables.open(&id).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
for batch in query::get(&dataset, &vector, &keys, None).await? {
@@ -282,7 +290,7 @@ async fn main() -> Result<()> {
key_column,
nprobes,
} => {
let opened = open_dataset(&client, &id, &storage).await?;
let opened = tables.open(&id).await?;
let dataset = match version {
Some(v) => opened.checkout_version(v).await?,
None => opened,
@@ -309,6 +317,7 @@ async fn main() -> Result<()> {
nprobes,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let hits = if flat {
query::flat(&dataset, &vector_table, &query).await?
@@ -326,7 +335,7 @@ async fn main() -> Result<()> {
id, vector_column, ..
} => (id.clone(), vector_column.clone()),
};
let mut dataset = open_dataset(&client, &id, &storage).await?;
let mut dataset = tables.open(&id).await?;
let table = VectorTable::resolve(&dataset, vector_column.as_deref(), None)?;
let started = std::time::Instant::now();
match action {
@@ -403,6 +412,17 @@ mod tests {
.unwrap();
assert_eq!(args.masters.as_deref(), Some("m:9333"));
assert_eq!(args.filer_group, "eu");
assert!(
Args::try_parse_from([
"weed-vector",
"--namespace",
"http://s3:9101",
"describe",
"t"
])
.is_err(),
"the namespace comes from the masters"
);
assert!(
Args::try_parse_from(["weed-vector", "--encryptVolumeData", "describe", "t"]).is_err(),
"volume encryption follows the filer"
@@ -312,6 +312,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let mut ids: Vec<u64> = query::flat(&pinned, &resolved, &q)
.await
@@ -734,6 +735,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
assert!(query::flat(&dataset, &resolved, &q).await.is_err());
}
+143 -6
View File
@@ -39,8 +39,15 @@ pub struct Query {
/// a worker the unindexed-fragment sweep. Listed ids that no longer exist
/// scan nothing.
pub fragments: Option<Vec<u64>>,
/// Score the matches exactly instead of searching the vector index when
/// the filter's indexed metadata keys match at most this many rows of the
/// scope; 0 never does. None takes [`DEFAULT_EXACT_MATCH_LIMIT`].
pub exact_match_limit: Option<usize>,
}
/// Up to this many matches of an indexed metadata key are scored exactly.
pub const DEFAULT_EXACT_MATCH_LIMIT: usize = 256;
/// One row of a top-K answer.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hit {
@@ -53,14 +60,101 @@ pub struct Hit {
/// 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).await?, table).await
run(scanner(dataset, table, query, false).await?.0, 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.
///
/// A prefiltered search sees only the probed partitions: it can come back
/// short of k, or with unscored rows (infinite distance) when at most k rows
/// match. Either way it is answered again by an exact scan of the same scope.
///
/// When the filter's indexed metadata keys match few rows of that scope,
/// they are scored exactly to begin with. The decision is per scope, so
/// exact answers of several scopes merge into the exact answer.
pub async fn ann(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
run(scanner(dataset, table, query, true).await?, table).await
if few_indexed_matches(dataset, table, query).await? {
return exact_in_scope(dataset, table, query).await;
}
let (scanner, indexed) = scanner(dataset, table, query, true).await?;
let hits = run(scanner, table).await?;
if indexed
&& query.filter.is_some()
&& !query.postfilter
&& (hits.len() < query.k || hits.iter().any(|h| !h.distance.is_finite()))
{
return exact_in_scope(dataset, table, query).await;
}
Ok(hits)
}
/// [`flat`] over what [`ann`] searches for `query`: the listed fragments plus
/// the live coverage of the listed index segments, or the whole table.
async fn exact_in_scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
let exact = Query {
index_segments: None,
fragments: scope(dataset, table, query).await?,
..query.clone()
};
run(scanner(dataset, table, &exact, false).await?.0, table).await
}
/// The fragments [`ann`] searches for `query`, or None for the whole table.
async fn scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Option<Vec<u64>>> {
Ok(match &query.index_segments {
Some(segments) if !segments.is_empty() => {
let mut ids = query.fragments.clone().unwrap_or_default();
ids.extend(
crate::segments::covered_fragments(dataset, &table.vector_column, segments).await?,
);
Some(ids)
}
_ => query.fragments.clone(),
})
}
/// Whether the rows of [`ann`]'s scope matching the filter's indexed
/// metadata keys, counted through their scalar indexes, are at most the
/// query's limit. Only a search through the vector index asks.
pub(crate) async fn few_indexed_matches(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
) -> Result<bool> {
let limit = query.exact_match_limit.unwrap_or(DEFAULT_EXACT_MATCH_LIMIT);
let Some(filter) = &query.filter else {
return Ok(false);
};
if limit == 0 || query.postfilter || query.index_segments.as_ref().is_some_and(|s| s.is_empty())
{
return Ok(false);
}
let ready = crate::indexed_filter::ready_columns(dataset);
if ready.is_empty()
|| crate::index::index_names(dataset, &table.vector_column)
.await?
.is_empty()
{
return Ok(false);
}
let indexed = crate::filter::apply(&mut dataset.scan(), filter, &ready)?;
if indexed.is_empty() {
return Ok(false);
}
let scope = scope(dataset, table, query).await?;
// An AND matches at most what its most selective indexed conjunct does.
for conjunct in &indexed {
let count =
crate::indexed_filter::count_indexed(dataset, conjunct, scope.as_deref(), limit as u64)
.await?;
tracing::debug!(column = %conjunct.column, ?count, limit, "indexed metadata filter");
if count.is_some() {
return Ok(true);
}
}
Ok(false)
}
/// Fetch rows by key, projected to `columns` (all of them when None).
@@ -101,7 +195,7 @@ async fn scanner(
table: &VectorTable,
query: &Query,
use_index: bool,
) -> Result<Scanner> {
) -> Result<(Scanner, bool)> {
if query.vector.len() != table.dimension {
bail!(
"query dim({}) does not match the table's dim({})",
@@ -117,18 +211,24 @@ async fn scanner(
.use_index(use_index)
.with_row_id();
if let Some(filter) = &query.filter {
crate::filter::apply(&mut scanner, filter)?;
let ready = crate::indexed_filter::ready_columns(dataset);
crate::filter::apply(&mut scanner, filter, &ready)?;
scanner.prefilter(!query.postfilter);
}
// An explicitly empty segment list searches no index, so there is
// nothing to size probes for.
let no_segments = query.index_segments.as_ref().is_some_and(|s| s.is_empty());
let mut indexed = false;
if use_index && !no_segments {
let probes = match query.nprobes {
Some(n) => Some(crate::index::Probes { min: n, max: n }),
Some(n) => crate::index::index_names(dataset, &table.vector_column)
.await?
.first()
.map(|_| crate::index::Probes { min: n, max: n }),
None => crate::index::default_probes(dataset, &table.vector_column).await?,
};
if let Some(probes) = probes {
indexed = true;
// Lance searches `min` partitions, and under a prefilter keeps
// going up to `max` until it has k rows. An open bound would
// make it prepare every partition for that, which costs as much
@@ -178,7 +278,7 @@ async fn scanner(
columns.push(DISTANCE_COLUMN.to_string());
columns.push(ROW_ID_COLUMN.to_string());
scanner.project(&columns)?;
Ok(scanner)
Ok((scanner, indexed))
}
async fn run(scanner: Scanner, table: &VectorTable) -> Result<Vec<Hit>> {
@@ -261,6 +361,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let hits = flat(&dataset, &table, &query).await.unwrap();
assert_eq!(hits.len(), 2);
@@ -302,6 +403,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
@@ -381,6 +483,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
@@ -484,6 +587,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
assert!(flat(&dataset, &table, &query).await.is_err());
}
@@ -507,6 +611,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let indexed = ann(&dataset, &table, &query).await.unwrap();
let exact = flat(&dataset, &table, &query).await.unwrap();
@@ -515,4 +620,36 @@ mod tests {
exact.iter().map(|h| &h.key).collect::<Vec<_>>()
);
}
/// An explicit probe count does not make an unindexed table's scan count
/// as indexed, so a short filtered answer is not scanned a second time.
#[tokio::test]
async fn explicit_probes_need_an_index() {
let dir = TempDir::new().unwrap();
let rows = crate::testing::vectors(300, DIM);
let mut dataset = write_dataset(&dir, &rows, &["a"; 300]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: rows[0].clone(),
k: 10,
filter: Some("tag = 'a'".to_string()),
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
};
assert!(!scanner(&dataset, &table, &query, true).await.unwrap().1);
crate::index::build(
&mut dataset,
&table.vector_column,
crate::index::INDEX_NAME,
4,
false,
)
.await
.unwrap();
assert!(scanner(&dataset, &table, &query, true).await.unwrap().1);
}
}
@@ -139,6 +139,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let want: Vec<(u64, u32)> = query::ann(&dataset, &resolved, &base)
.await
@@ -239,6 +240,7 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: Some(vec![u64::MAX]),
exact_match_limit: None,
};
assert!(
query::ann(&dataset, &resolved, &q)
+1
View File
@@ -44,6 +44,7 @@ fn query_for(vector: Vec<f32>, k: usize) -> Query {
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
}
}
+1
View File
@@ -46,6 +46,7 @@ tracing.workspace = true
tracing-subscriber.workspace = true
[dev-dependencies]
lance-index = "10"
tempfile = "3"
[build-dependencies]
@@ -0,0 +1,392 @@
//! How often, and how slowly, each index's queries filter on each metadata
//! key over the last hour. Keys come from the parsed filter; the number of
//! indexes and of keys per index is bounded, so arbitrary keys cannot grow
//! memory without limit. Not exported as metrics: a key is no label.
use std::collections::{BTreeMap, HashMap};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use weed_vector_core::indexed_filter::operand;
use crate::pb::vector as pb;
const BUCKETS: usize = 12;
const BUCKET: Duration = Duration::from_secs(300);
pub const WINDOW: Duration = Duration::from_secs(BUCKET.as_secs() * BUCKETS as u64);
pub const MAX_INDEXES: usize = 512;
pub const MAX_KEYS_PER_INDEX: usize = 32;
const MAX_RETIRED_TABLES: usize = 4;
#[derive(Default, Clone, Copy)]
struct Bucket {
/// The bucket's number since the stats started.
at: u64,
queries: u64,
seconds: f64,
/// The operand kinds the bucket's queries compared the key with.
kinds: u8,
}
#[derive(Default)]
struct KeyStats {
buckets: [Bucket; BUCKETS],
}
#[derive(Default)]
struct IndexStats {
/// The table the stats were counted on: an index dropped and created
/// again under its name is another table.
table: String,
/// Tables the name held before, whose late queries are not counted.
retired: Vec<String>,
keys: HashMap<String, KeyStats>,
/// The last bucket a key was left uncounted in.
truncated: Option<u64>,
last: u64,
}
impl IndexStats {
/// Starts counting on `table`, retiring the table counted on before.
fn replace(&mut self, table: &str) {
let mut retired = std::mem::take(&mut self.retired);
if !self.table.is_empty() {
retired.push(std::mem::take(&mut self.table));
if retired.len() > MAX_RETIRED_TABLES {
retired.remove(0);
}
}
*self = IndexStats {
table: table.to_string(),
retired,
last: self.last,
..Default::default()
};
}
}
/// Whether bucket `at` is still in the window of bucket `now`.
fn live(at: u64, now: u64) -> bool {
at + BUCKETS as u64 > now
}
pub struct FilterStats {
start: Instant,
indexes: Mutex<HashMap<String, IndexStats>>,
}
impl Default for FilterStats {
fn default() -> Self {
Self::new()
}
}
impl FilterStats {
pub fn new() -> Self {
Self {
start: Instant::now(),
indexes: Mutex::new(HashMap::new()),
}
}
fn bucket(&self, now: Instant) -> u64 {
(now.duration_since(self.start).as_secs() / BUCKET.as_secs()) + 1
}
/// Drops the stats of `index`, which now holds `table` ("" once
/// dropped): late queries of the table it held before are not counted.
pub fn forget(&self, index: &str, table: &str) {
let mut indexes = self.indexes.lock().unwrap();
if let Some(stats) = indexes.get_mut(index)
&& (table.is_empty() || stats.table != table)
{
stats.replace(table);
}
}
/// One query of `index`, whose table is `table`, that took `elapsed` and
/// filtered on `keys`. Stats counted on another table under the name are
/// dropped; a query of a table the name no longer holds is not counted.
pub fn record(&self, index: &str, table: &str, keys: &BTreeMap<String, u8>, elapsed: Duration) {
self.record_table_at(index, table, keys, elapsed, Instant::now());
}
#[cfg(test)]
fn record_at(&self, index: &str, keys: &BTreeMap<String, u8>, elapsed: Duration, now: Instant) {
self.record_table_at(index, "", keys, elapsed, now);
}
fn record_table_at(
&self,
index: &str,
table: &str,
keys: &BTreeMap<String, u8>,
elapsed: Duration,
now: Instant,
) {
if keys.is_empty() {
return;
}
let at = self.bucket(now);
let mut indexes = self.indexes.lock().unwrap();
if !indexes.contains_key(index) && indexes.len() >= MAX_INDEXES {
let Some(oldest) = indexes
.iter()
.min_by_key(|(_, stats)| stats.last)
.map(|(name, _)| name.clone())
else {
return;
};
indexes.remove(&oldest);
}
let stats = indexes.entry(index.to_string()).or_default();
if !table.is_empty() && stats.table != table {
if stats.retired.iter().any(|t| t == table) {
return;
}
if stats.table.is_empty() {
stats.table = table.to_string();
} else {
stats.replace(table);
}
}
stats.last = stats.last.max(at);
for (key, kinds) in keys {
if !stats.keys.contains_key(key) && stats.keys.len() >= MAX_KEYS_PER_INDEX {
// Make room only by dropping a key no query used in the window.
let idle = stats
.keys
.iter()
.find(|(_, k)| k.buckets.iter().all(|b| !live(b.at, at)))
.map(|(name, _)| name.clone());
match idle {
Some(idle) => {
stats.keys.remove(&idle);
}
None => {
stats.truncated = stats.truncated.max(Some(at));
continue;
}
}
}
let entry = stats.keys.entry(key.clone()).or_default();
let bucket = &mut entry.buckets[(at % BUCKETS as u64) as usize];
if bucket.at != at {
*bucket = Bucket {
at,
..Default::default()
};
}
bucket.queries += 1;
bucket.seconds += elapsed.as_secs_f64();
bucket.kinds |= kinds;
}
}
/// The stats of `index` over the window.
pub fn snapshot(&self, index: &str) -> pb::FilterStatsResponse {
self.snapshot_at(index, Instant::now())
}
fn snapshot_at(&self, index: &str, now: Instant) -> pb::FilterStatsResponse {
let at = self.bucket(now);
let window_seconds = now.duration_since(self.start).min(WINDOW).as_secs() as u32;
let indexes = self.indexes.lock().unwrap();
let Some(stats) = indexes.get(index) else {
return pb::FilterStatsResponse {
window_seconds,
..Default::default()
};
};
let mut keys: Vec<pb::FilterKeyStats> = stats
.keys
.iter()
.filter_map(|(key, s)| {
let (queries, seconds, kinds) = s
.buckets
.iter()
.filter(|b| live(b.at, at))
.fold((0, 0.0, 0), |(q, t, k), b| {
(q + b.queries, t + b.seconds, k | b.kinds)
});
(queries > 0).then(|| pb::FilterKeyStats {
key: key.clone(),
queries,
seconds,
string_operand: kinds & operand::STRING != 0,
number_operand: kinds & operand::NUMBER != 0,
bool_operand: kinds & operand::BOOL != 0,
})
})
.collect();
keys.sort_by(|a, b| b.queries.cmp(&a.queries).then(a.key.cmp(&b.key)));
pb::FilterStatsResponse {
keys,
window_seconds,
truncated: stats.truncated.is_some_and(|t| live(t, at)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(pairs: &[(&str, u8)]) -> BTreeMap<String, u8> {
pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()
}
#[test]
fn counts_queries_and_latency_per_key_within_the_window() {
let stats = FilterStats::new();
let t0 = stats.start;
let ms = Duration::from_millis;
stats.record_at("b/i", &keys(&[("author", operand::STRING)]), ms(10), t0);
stats.record_at(
"b/i",
&keys(&[("author", operand::STRING), ("year", operand::NUMBER)]),
ms(30),
t0 + Duration::from_secs(600),
);
stats.record_at("b/j", &keys(&[("x", operand::BOOL)]), ms(5), t0);
let got = stats.snapshot_at("b/i", t0 + Duration::from_secs(900));
assert_eq!(got.window_seconds, 900);
assert_eq!(got.keys.len(), 2);
assert_eq!(got.keys[0].key, "author");
assert_eq!(got.keys[0].queries, 2);
assert!((got.keys[0].seconds - 0.04).abs() < 1e-9);
assert!(got.keys[0].string_operand && !got.keys[0].number_operand);
assert_eq!(got.keys[1].key, "year");
assert!(got.keys[1].number_operand);
// The first query leaves the window an hour after its bucket.
let later = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(1));
assert_eq!(later.window_seconds, WINDOW.as_secs() as u32);
assert_eq!(later.keys[0].queries, 1);
let year = later.keys.iter().find(|k| k.key == "year").unwrap();
assert!(year.number_operand);
// A string query that left the window no longer marks the key.
stats.record_at(
"b/i",
&keys(&[("author", operand::NUMBER)]),
ms(1),
t0 + WINDOW + Duration::from_secs(2),
);
let mixed = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(3));
let author = mixed.keys.iter().find(|k| k.key == "author").unwrap();
assert!(author.string_operand && author.number_operand);
let numeric = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(700));
let author = numeric.keys.iter().find(|k| k.key == "author").unwrap();
assert!(!author.string_operand && author.number_operand);
let gone = stats.snapshot_at("b/i", t0 + 2 * WINDOW + Duration::from_secs(900));
assert!(gone.keys.is_empty());
assert!(stats.snapshot_at("other", t0).keys.is_empty());
}
#[test]
fn indexes_and_keys_are_bounded() {
let stats = FilterStats::new();
let t0 = stats.start;
for i in 0..MAX_KEYS_PER_INDEX + 5 {
stats.record_at(
"b/i",
&keys(&[(&format!("k{i}"), operand::STRING)]),
Duration::ZERO,
t0,
);
}
let got = stats.snapshot_at("b/i", t0);
assert_eq!(got.keys.len(), MAX_KEYS_PER_INDEX);
assert!(got.truncated);
// A key idle for the whole window makes room for a new one.
let later = t0 + WINDOW + BUCKET;
stats.record_at(
"b/i",
&keys(&[("new", operand::STRING)]),
Duration::ZERO,
later,
);
let got = stats.snapshot_at("b/i", later);
assert!(!got.truncated, "the uncounted keys left the window");
assert_eq!(got.keys.len(), 1);
assert_eq!(got.keys[0].key, "new");
for i in 0..MAX_INDEXES + 3 {
stats.record_at(
&format!("b/{i}"),
&keys(&[("k", operand::STRING)]),
Duration::ZERO,
later,
);
}
assert_eq!(stats.indexes.lock().unwrap().len(), MAX_INDEXES);
}
#[test]
fn a_record_from_an_earlier_bucket_keeps_the_later_truncation() {
let stats = FilterStats::new();
let t0 = stats.start;
for i in 0..=MAX_KEYS_PER_INDEX {
stats.record_at(
"b/i",
&keys(&[(&format!("k{i}"), operand::STRING)]),
Duration::ZERO,
t0 + BUCKET,
);
}
// Took its time before the lock while the later bucket recorded.
stats.record_at(
"b/i",
&keys(&[("late", operand::STRING)]),
Duration::ZERO,
t0,
);
let got = stats.snapshot_at("b/i", t0 + WINDOW);
assert!(
got.truncated,
"the later bucket's uncounted key is in the window"
);
assert_eq!(stats.indexes.lock().unwrap()["b/i"].last, 2);
}
#[test]
fn stats_follow_the_table_behind_an_index_name() {
let stats = FilterStats::new();
let t0 = stats.start;
let author = keys(&[("author", operand::STRING)]);
let count = |stats: &FilterStats| {
stats
.snapshot_at("b/i", t0)
.keys
.first()
.map_or(0, |k| k.queries)
};
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 2);
// The index was created again: its first query starts over.
stats.record_table_at("b/i", "t2", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 1);
// A late query of the old table is not counted on the new one.
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 1);
stats.forget("b/i", "");
assert_eq!(count(&stats), 0);
// A first query records its table: a later table starts over.
stats.record_table_at("b/i", "t3", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t4", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 1);
}
#[test]
fn a_late_query_after_a_drop_is_not_counted_on_the_new_table() {
let stats = FilterStats::new();
let t0 = stats.start;
let author = keys(&[("author", operand::STRING)]);
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
stats.forget("b/i", "");
stats.record_table_at("b/i", "t2", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t2", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
assert_eq!(stats.snapshot_at("b/i", t0).keys[0].queries, 2);
}
}
@@ -0,0 +1,817 @@
//! Indexed metadata keys through the VectorService: PutVectors derives the
//! columns, and a query answers the same with or without them.
use std::sync::Arc;
use arrow_array::RecordBatch;
use arrow_schema::Schema;
use lance::Dataset;
use lance::dataset::{BatchUDF, NewColumnTransform};
use lance::index::DatasetIndexExt;
use lance_index::IndexType;
use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams};
use tonic::Request;
use weed_lance_worker::metadata_index::{self, STATE_FIELD_META, State};
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
use crate::pb::vector::{self as pb, vector_service_server::VectorService};
use crate::service::VectorServer;
const DIM: usize = 8;
const ROWS: usize = 3000;
const COLUMN: &str = "_mk_0";
/// How the engine answers a filter once `author` is indexed.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Path {
/// Through the column, at most the exact-match limit of rows: exact.
Exact,
/// Through the column, more rows: the vector index with the column's
/// prefilter.
Ivf,
/// Not through the column.
Json,
}
/// S3 Vectors filters, the gateway's translation of each, and its path.
const FILTERS: [(&str, &str, Path); 22] = [
(
"{\"author\":\"alice\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"alice\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false))",
Path::Ivf,
),
(
"{\"author\":{\"$eq\":\"bob\"}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"bob\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false))",
Path::Exact,
),
(
"{\"author\":\"carol\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"carol\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"carol\"'), false))",
Path::Exact,
),
(
"{\"author\":\"x\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"x\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"x\"'), false))",
Path::Exact,
),
(
"{\"author\":\"7\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"7\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"7\"'), false))",
Path::Exact,
),
(
"{\"author\":7}",
"(COALESCE(TRY_CAST(json_extract(`metadata`, '$[\"author\"]') AS DOUBLE) = 7, false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '7'), false))",
Path::Json,
),
(
"{\"author\":true}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = 'true', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', 'true'), false))",
Path::Json,
),
(
"{\"author\":{\"$in\":[\"alice\",\"bob\",\"x\"]}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"alice\"', '\"bob\"', '\"x\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"x\"'), false))",
Path::Ivf,
),
(
"{\"author\":{\"$in\":[\"alice\",7]}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"alice\"'), false) OR COALESCE(TRY_CAST(json_extract(`metadata`, '$[\"author\"]') AS DOUBLE) in (7), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '7'), false))",
Path::Json,
),
(
"{\"author\":{\"$ne\":\"alice\"}}",
"NOT (COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"alice\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false))",
Path::Json,
),
(
"{\"author\":{\"$nin\":[\"alice\",\"bob\"]}}",
"NOT (COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"alice\"', '\"bob\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false))",
Path::Json,
),
(
"{\"author\":{\"$exists\":false}}",
"NOT json_exists(`metadata`, '$[\"author\"]')",
Path::Json,
),
(
"{\"$and\":[{\"author\":\"alice\"},{\"genre\":\"g1\"}]}",
"((COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"alice\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false)) AND (COALESCE(json_extract(`metadata`, '$[\"genre\"]') = '\"g1\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"genre\"]', '\"g1\"'), false)))",
Path::Ivf,
),
(
"{\"$and\":[{\"author\":\"bob\"},{\"year\":{\"$gt\":2005}}]}",
"((COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"bob\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false)) AND TRY_CAST(json_extract(`metadata`, '$[\"year\"]') AS DOUBLE) > 2005)",
Path::Exact,
),
(
"{\"$or\":[{\"author\":\"bob\"},{\"genre\":\"g2\"}]}",
"((COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"bob\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false)) OR (COALESCE(json_extract(`metadata`, '$[\"genre\"]') = '\"g2\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"genre\"]', '\"g2\"'), false)))",
Path::Json,
),
(
"{\"author\":\"o'neil \\\"q\\\" \\\\ \\n\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"o''neil \\\"q\\\" \\\\ \\n\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"o''neil \\\"q\\\" \\\\ \\n\"'), false))",
Path::Exact,
),
(
"{\"author\":\"nobody\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"nobody\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"nobody\"'), false))",
Path::Exact,
),
("{\"author\":{\"$in\":[]}}", "false", Path::Json),
(
"{\"genre\":\"g1\"}",
"(COALESCE(json_extract(`metadata`, '$[\"genre\"]') = '\"g1\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"genre\"]', '\"g1\"'), false))",
Path::Json,
),
(
"{\"author\":\"u5\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"u5\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"u5\"'), false))",
Path::Exact,
),
(
"{\"author\":\"ctl\\u0001x\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"ctl\\u{1}x\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"ctl\\u0001x\"'), false))",
Path::Json,
),
(
"{\"author\":{\"$in\":[\"u5\",\"u6\"]}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"u5\"', '\"u6\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"u5\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"u6\"'), false))",
Path::Exact,
),
];
fn rng(seed: &mut u64) -> f32 {
*seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((*seed >> 33) as f32 / (1u64 << 31) as f32) - 0.5
}
fn vector_of(i: usize) -> Vec<f32> {
let mut centre = (i % 16) as u64 + 1;
let mut noise = i as u64 * 7919 + 13;
(0..DIM)
.map(|_| rng(&mut centre) * 4.0 + rng(&mut noise))
.collect()
}
fn author(i: usize) -> Option<serde_json::Value> {
use serde_json::json;
Some(match i % 100 {
0..=9 => json!("alice"),
10 => json!("bob"),
11 => json!(["carol", "x"]),
12 => json!(7),
13 => json!("7"),
14 => serde_json::Value::Null,
15 => return None,
16 => json!(true),
17 => json!("o'neil \"q\" \\ \n"),
18 => json!("ctl\u{1}x"),
19 => json!(["alice", 3]),
_ => json!(format!("u{}", i % 37)),
})
}
fn row(i: usize, author: Option<serde_json::Value>) -> pb::Vector {
let mut meta = serde_json::json!({"genre": format!("g{}", i % 3), "year": 2000 + i % 10});
if let Some(author) = author {
meta["author"] = author;
}
let serde_json::Value::Object(meta) = meta else {
unreachable!()
};
pb::Vector {
key: format!("k{i}"),
data: vector_of(i),
metadata: Some(crate::service::json_to_struct(meta)),
}
}
struct Fixture {
server: VectorServer,
exact_off: VectorServer,
table: pb::Table,
}
impl Fixture {
async fn new() -> Self {
let bucket = format!(
"mk-{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
let table = pb::Table {
id: vec![bucket.clone(), "vector".into(), "x".into()],
location: format!("shared-memory://{bucket}/vector/x"),
..Default::default()
};
let fixture = Self {
server: VectorServer::new().with_schemes(&["shared-memory"]),
exact_off: VectorServer::new()
.with_schemes(&["shared-memory"])
.with_exact_match_limit(Some(0)),
table,
};
fixture
.server
.create_index(Request::new(pb::CreateIndexRequest {
table: Some(fixture.table.clone()),
dimension: DIM as u32,
distance_metric: pb::DistanceMetric::L2 as i32,
..Default::default()
}))
.await
.unwrap();
fixture
}
async fn put(&self, vectors: Vec<pb::Vector>) {
self.server
.put_vectors(Request::new(pb::PutVectorsRequest {
table: Some(self.table.clone()),
vectors,
}))
.await
.unwrap();
}
async fn dataset(&self, version: u64) -> Dataset {
let dataset = Dataset::open(&self.table.location).await.unwrap();
if version == 0 {
dataset
} else {
dataset.checkout_version(version).await.unwrap()
}
}
/// Adds `author`'s column, indexes it and marks it ready, returning the
/// version before it was ready.
async fn index_author(&self) -> u64 {
let mut dataset = self.dataset(0).await;
let output = Arc::new(Schema::new(vec![metadata_index::field(
COLUMN,
"author",
State::Building,
)]));
let schema = output.clone();
dataset
.add_columns(
NewColumnTransform::BatchUDF(BatchUDF {
mapper: Box::new(move |batch: &RecordBatch| {
let column = metadata_index::column_from_metadata(
batch.column_by_name("metadata").unwrap().as_ref(),
"author",
)
.map_err(|e| lance::Error::invalid_input(e.to_string()))?;
Ok(RecordBatch::try_new(schema.clone(), vec![column])?)
}),
output_schema: output,
result_checkpoint: None,
}),
Some(vec!["metadata".to_string()]),
None,
)
.await
.unwrap();
dataset
.create_index(
&[COLUMN],
IndexType::LabelList,
Some(format!("{COLUMN}_idx")),
&ScalarIndexParams::for_builtin(BuiltinIndexType::LabelList),
true,
)
.await
.unwrap();
let building = dataset.version().version;
self.set_state(State::Ready).await;
building
}
async fn set_state(&self, state: State) -> u64 {
let mut dataset = self.dataset(0).await;
dataset
.update_field_metadata()
.update(COLUMN, [(STATE_FIELD_META, state.as_str())])
.unwrap()
.await
.unwrap();
dataset.version().version
}
async fn query(
&self,
server: &VectorServer,
version: u64,
filter: &str,
k: u32,
v: &[f32],
) -> Vec<(String, f32)> {
let mut table = self.table.clone();
table.version = version;
server
.query_vectors(Request::new(pb::QueryVectorsRequest {
table: Some(table),
query_vector: v.to_vec(),
top_k: k,
filter: filter.to_string(),
return_distance: true,
..Default::default()
}))
.await
.unwrap()
.into_inner()
.vectors
.into_iter()
.map(|r| (r.key, r.distance))
.collect()
}
/// Exact filtered top-k at `version`.
async fn flat(&self, version: u64, filter: &str, k: u32, v: &[f32]) -> Vec<(String, f32)> {
let dataset = self.dataset(version).await;
let table = VectorTable::resolve(&dataset, None, Some("key")).unwrap();
query::flat(
&dataset,
&table,
&Query {
vector: v.to_vec(),
k: k as usize,
filter: Some(filter.to_string()),
postfilter: false,
distance: lance_linalg::distance::DistanceType::L2,
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
.unwrap()
.into_iter()
.map(|h| (h.key, h.distance))
.collect()
}
/// Every filter answers through the column as through the JSON at
/// `json` (the same rows and indexes, the column not ready), and an
/// exact answer as the exact filtered top-k.
async fn compare(&self, json: u64, ready: u64) {
for q in [7, 1234] {
let v = vector_of(q);
for (s3, filter, path) in FILTERS {
for k in [10, 400] {
let what = format!("{s3} k={k} q={q}");
let exact = self.flat(json, filter, k, &v).await;
assert_same(&self.flat(ready, filter, k, &v).await, &exact, &what);
let json_ann = self.query(&self.server, json, filter, k, &v).await;
let off = self.query(&self.exact_off, ready, filter, k, &v).await;
assert_same(&off, &json_ann, &format!("{what}: indexed prefilter"));
let got = self.query(&self.server, ready, filter, k, &v).await;
let want = if path == Path::Exact {
&exact
} else {
&json_ann
};
assert_same(&got, want, &format!("{what}: {path:?}"));
}
}
}
}
}
fn assert_same(got: &[(String, f32)], want: &[(String, f32)], what: &str) {
assert_eq!(got.len(), want.len(), "{what}: {got:?} vs {want:?}");
// Ties may come back in either order: the same keys, and the same
// distance at each rank.
fn keys(hits: &[(String, f32)]) -> Vec<&str> {
let mut keys: Vec<&str> = hits.iter().map(|(k, _)| k.as_str()).collect();
keys.sort();
keys
}
assert_eq!(keys(got), keys(want), "{what}: {got:?} vs {want:?}");
for (g, w) in got.iter().zip(want) {
let same = (g.1 - w.1).abs() < 1e-4 || (g.1.is_infinite() && w.1.is_infinite());
assert!(same, "{what}: {got:?} vs {want:?}");
if g.0 != w.0 {
let tie = want
.iter()
.any(|(k, d)| k == &g.0 && (d - w.1).abs() < 1e-4);
assert!(
tie,
"{what}: {} at {} is no tie: {got:?} vs {want:?}",
g.0, g.1
);
}
}
}
/// Indexed and JSON answers agree on mixed types, missing keys, arrays,
/// null, untouched operators, and after updates, deletes and rows no
/// scalar or vector index covers yet.
#[tokio::test]
async fn indexed_answers_match_the_json_path() {
let fixture = Fixture::new().await;
for start in (0..ROWS).step_by(300) {
fixture
.put((start..start + 300).map(|i| row(i, author(i))).collect())
.await;
}
let mut dataset = fixture.dataset(0).await;
weed_lance_worker::vector_index::build(&mut dataset, "vector", "vector_idx", 16, false)
.await
.unwrap();
let json = fixture.index_author().await;
let schema: Schema = fixture.dataset(0).await.schema().into();
assert_eq!(
metadata_index::indexed_keys(&schema)[0].state,
Some(State::Ready)
);
fixture.compare(json, 0).await;
// Updates move rows between values, deletes drop some, and new rows land
// in fragments neither index covers; PutVectors fills the column.
fixture
.put(
(0..60)
.map(|i| row(i, Some(serde_json::json!(["moved", "bob"]))))
.chain((ROWS..ROWS + 200).map(|i| row(i, author(i))))
.collect(),
)
.await;
fixture
.server
.delete_vectors(Request::new(pb::DeleteVectorsRequest {
table: Some(fixture.table.clone()),
keys: (100..130).map(|i| format!("k{i}")).collect(),
}))
.await
.unwrap();
let json = fixture.set_state(State::Building).await;
let ready = fixture.set_state(State::Ready).await;
fixture.compare(json, ready).await;
let moved = r#"(COALESCE(json_extract(`metadata`, '$["author"]') = '"moved"', false) OR COALESCE(json_array_contains(`metadata`, '$["author"]', '"moved"'), false))"#;
let hits = fixture
.query(&fixture.server, ready, moved, 100, &vector_of(0))
.await;
assert_eq!(hits.len(), 60);
}
/// The planner counts and scores per scope: an exact answer over a fragment
/// subset is that subset's exact top-k.
#[tokio::test]
async fn a_scoped_query_is_exact_within_its_fragments() {
let fixture = Fixture::new().await;
for start in (0..ROWS).step_by(300) {
fixture
.put((start..start + 300).map(|i| row(i, author(i))).collect())
.await;
}
let mut dataset = fixture.dataset(0).await;
weed_lance_worker::vector_index::build(&mut dataset, "vector", "vector_idx", 16, false)
.await
.unwrap();
let json = fixture.index_author().await;
let ready = fixture.dataset(0).await;
let table = VectorTable::resolve(&ready, None, Some("key")).unwrap();
let ids: Vec<u64> = ready.fragments().iter().map(|f| f.id).take(4).collect();
let filter = FILTERS[1].1;
let scoped = || Query {
vector: vector_of(5),
k: 10,
filter: Some(filter.to_string()),
postfilter: false,
distance: lance_linalg::distance::DistanceType::L2,
nprobes: None,
index_segments: None,
fragments: Some(ids.clone()),
exact_match_limit: None,
};
let got = query::ann(&ready, &table, &scoped()).await.unwrap();
let old = fixture.dataset(json).await;
let want = query::flat(&old, &table, &scoped()).await.unwrap();
assert_eq!(want.len(), 10);
let pairs = |hits: Vec<weed_vector_core::Hit>| {
hits.into_iter()
.map(|h| (h.key, h.distance))
.collect::<Vec<_>>()
};
assert_same(&pairs(got), &pairs(want), "scoped bob");
}
/// The engine counts each index's filtered queries by key.
#[tokio::test]
async fn queries_are_counted_by_filter_key() {
let fixture = Fixture::new().await;
fixture
.put((0..50).map(|i| row(i, author(i))).collect())
.await;
for (_, filter, _) in &FILTERS[..3] {
fixture
.query(&fixture.server, 0, filter, 5, &vector_of(1))
.await;
}
let year = FILTERS[13].1;
fixture
.query(&fixture.server, 0, year, 5, &vector_of(1))
.await;
let stats = fixture
.server
.filter_stats(Request::new(pb::FilterStatsRequest {
table: Some(fixture.table.clone()),
}))
.await
.unwrap()
.into_inner();
let author = stats.keys.iter().find(|k| k.key == "author").unwrap();
assert_eq!(author.queries, 4);
assert!(author.string_operand && !author.number_operand);
let year = stats.keys.iter().find(|k| k.key == "year").unwrap();
assert_eq!(year.queries, 1);
assert!(year.number_operand && !year.string_operand);
}
/// A PutVectors that opened the table before its key column was added and
/// commits after: Lance rebases the write and its rows hold NULL in the new
/// column, which the write then fills from the rows' metadata.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_write_that_raced_the_column_add_fills_the_column() {
let fixture = Fixture::new().await;
fixture
.put((0..300).map(|i| row(i, author(i))).collect())
.await;
let unhealed = fixture.dataset(0).await;
let healed = fixture.dataset(0).await;
fixture.index_author().await;
let nulls = |dataset: Dataset| async move {
dataset
.count_rows(Some(format!("{COLUMN} IS NULL")))
.await
.unwrap()
};
let rows: Vec<pb::Vector> = (250..400).map(|i| row(i, author(i))).collect();
let written = crate::service::merge_vectors(unhealed, &rows)
.await
.unwrap();
assert!(written.schema().field(COLUMN).is_some());
assert!(nulls(written).await >= 100, "the race is reproduced");
let written = crate::service::write_vectors(healed, &rows).await.unwrap();
assert_eq!(nulls(written.clone()).await, 0);
let filter = FILTERS[1].1;
let latest = written.version().version;
let v = vector_of(5);
assert_same(
&fixture
.query(&fixture.server, latest, filter, 400, &v)
.await,
&fixture.flat(latest, filter, 400, &v).await,
"bob after the race",
);
assert_eq!(fixture.flat(latest, filter, 400, &v).await.len(), 4);
}
/// A write names no version: one at a version from before a key's column
/// add would commit rows without the column.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_write_at_an_older_version_is_refused() {
let fixture = Fixture::new().await;
fixture
.put((0..10).map(|i| row(i, author(i))).collect())
.await;
let before = fixture.dataset(0).await.version().version;
fixture.index_author().await;
let mut table = fixture.table.clone();
table.version = before;
let refused = fixture
.server
.put_vectors(Request::new(pb::PutVectorsRequest {
table: Some(table),
vectors: (10..20).map(|i| row(i, author(i))).collect(),
}))
.await
.unwrap_err();
assert_eq!(refused.code(), tonic::Code::InvalidArgument);
}
/// Two writes updating the same keys raced the column add, and the first
/// one's fill commits last: each write's rows get the values of its own
/// metadata, not the ones derived before it or from the other write.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_write_that_raced_the_column_add_derives_its_updated_rows() {
let fixture = Fixture::new().await;
fixture
.put((0..300).map(|i| row(i, author(i))).collect())
.await;
let first = fixture.dataset(0).await;
let second = fixture.dataset(0).await;
let written: Schema = first.schema().into();
fixture.index_author().await;
let rows = |name: &str| -> Vec<pb::Vector> {
(250..300)
.map(|i| row(i, Some(serde_json::json!(name))))
.collect()
};
let keys: Vec<String> = (250..300).map(|i| format!("k{i}")).collect();
let first = crate::service::merge_vectors(first, &rows("alice"))
.await
.unwrap();
let second = crate::service::merge_vectors(second, &rows("bob"))
.await
.unwrap();
crate::service::heal_columns(second, &written, &keys)
.await
.unwrap();
crate::service::heal_columns(first, &written, &keys)
.await
.unwrap();
let latest = fixture.dataset(0).await;
let count = |filter: String| {
let latest = latest.clone();
async move { latest.count_rows(Some(filter)).await.unwrap() }
};
assert_eq!(count(format!("{COLUMN} IS NULL")).await, 0);
for (name, filter) in [("alice", FILTERS[0].1), ("bob", FILTERS[1].1)] {
assert_eq!(
count(format!("array_has({COLUMN}, '{name}')")).await,
count(filter.to_string()).await,
"{name}"
);
}
let mut got = fixture
.server
.get_vectors(Request::new(pb::GetVectorsRequest {
table: Some(fixture.table.clone()),
keys: keys.clone(),
return_data: true,
return_metadata: true,
}))
.await
.unwrap()
.into_inner()
.vectors;
got.sort_by_key(|v| v.key[1..].parse::<usize>().unwrap());
assert_eq!(got, rows("bob"));
}
/// Operators ask through the engine; the table records the request and,
/// once the worker has done its part, the key's state, coverage and size.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn keys_are_requested_and_listed_through_the_engine() {
let fixture = Fixture::new().await;
fixture
.put((0..600).map(|i| row(i, author(i))).collect())
.await;
let update = |key: &str, remove: bool| {
fixture
.server
.update_metadata_key(Request::new(pb::UpdateMetadataKeyRequest {
table: Some(fixture.table.clone()),
key: key.to_string(),
remove,
}))
};
let listed = update("author", false).await.unwrap().into_inner();
assert_eq!(listed.keys.len(), 1);
assert_eq!(listed.keys[0].state, "requested");
assert_eq!(listed.keys[0].rows, 600);
// A retry of a committed request answers as the first one did.
let again = update("author", false).await.unwrap().into_inner();
assert_eq!(again.keys.len(), 1);
assert_eq!(again.keys[0].state, "requested");
let mut dataset = fixture.dataset(0).await;
let key = metadata_index::add_column(&mut dataset, "author")
.await
.unwrap();
metadata_index::finish_after(&mut dataset, &key, 1_000_000, std::time::Duration::ZERO)
.await
.unwrap();
let listed = fixture
.server
.metadata_keys(Request::new(pb::MetadataKeysRequest {
table: Some(fixture.table.clone()),
}))
.await
.unwrap()
.into_inner();
assert_eq!((listed.rows, listed.vector_index.as_str()), (600, ""));
let author = &listed.keys[0];
assert_eq!(
(
author.key.as_str(),
author.state.as_str(),
author.column.as_str()
),
("author", "ready", "_mk_0")
);
assert_eq!(
(author.indexed_rows, author.rows, author.segments),
(600, 600, 1)
);
assert!(author.index_bytes > 0);
// Off at once: the next query reads the JSON again.
let listed = update("author", true).await.unwrap().into_inner();
assert_eq!(listed.keys[0].state, "off");
let dataset = fixture.dataset(0).await;
assert_eq!(metadata_index::keys_of(&dataset)[0].state, Some(State::Off));
// Removing a key that is not indexed needs nothing.
let nobody = update("nobody", true).await.unwrap().into_inner();
assert_eq!(nobody.keys.len(), 1);
assert_eq!(
update("author", false).await.unwrap_err().code(),
tonic::Code::FailedPrecondition,
"being removed"
);
}
/// DeleteIndex purges the table's directory and an index created again
/// under the same name reuses it: the same running engine serves nothing of
/// the old table, neither rows, nor its indexed key, nor its filter stats.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_dropped_and_recreated_index_serves_nothing_old() {
let fixture = Fixture::new().await;
fixture
.put((0..600).map(|i| row(i, author(i))).collect())
.await;
let mut dataset = fixture.dataset(0).await;
weed_lance_worker::vector_index::build(&mut dataset, "vector", "vector_idx", 4, false)
.await
.unwrap();
fixture.index_author().await;
let bob = FILTERS[1].1;
let old = fixture
.query(&fixture.server, 0, bob, 50, &vector_of(10))
.await;
assert_eq!(old.len(), 6);
let server = &fixture.server;
let stats = || {
server.filter_stats(Request::new(pb::FilterStatsRequest {
table: Some(fixture.table.clone()),
}))
};
assert_eq!(stats().await.unwrap().into_inner().keys[0].queries, 1);
// What the catalog's DeleteTable does, then CreateIndex again.
let (store, path) = lance::io::ObjectStore::from_uri(&fixture.table.location)
.await
.unwrap();
store.remove_dir_all(path).await.unwrap();
fixture
.server
.create_index(Request::new(pb::CreateIndexRequest {
table: Some(fixture.table.clone()),
dimension: DIM as u32,
distance_metric: pb::DistanceMetric::L2 as i32,
..Default::default()
}))
.await
.unwrap();
let keys = fixture
.server
.metadata_keys(Request::new(pb::MetadataKeysRequest {
table: Some(fixture.table.clone()),
}))
.await
.unwrap()
.into_inner();
assert!(keys.keys.is_empty());
assert!(
stats().await.unwrap().into_inner().keys.is_empty(),
"the old table's filter stats"
);
fixture
.put((1000..1100).map(|i| row(i, author(i))).collect())
.await;
let new = |hits: &[(String, f32)]| {
hits.iter().all(|(k, _)| {
k[1..]
.parse::<usize>()
.is_ok_and(|i| (1000..1100).contains(&i))
})
};
let unfiltered = fixture
.query(&fixture.server, 0, "", 200, &vector_of(10))
.await;
assert_eq!(unfiltered.len(), 100);
assert!(new(&unfiltered), "{unfiltered:?}");
let bob_now = fixture
.query(&fixture.server, 0, bob, 50, &vector_of(10))
.await;
assert_eq!(bob_now.len(), 1);
assert!(new(&bob_now), "{bob_now:?}");
let author = stats().await.unwrap().into_inner().keys;
assert_eq!((author.len(), author[0].queries), (1, 1));
}
+8
View File
@@ -1,5 +1,12 @@
//! The VectorService gRPC server the S3 gateway talks to.
// PutVectors awaits two Lance merge_insert futures; proving the handler
// future Send takes deeper trait recursion than the default.
#![recursion_limit = "256"]
pub mod filter_stats;
#[cfg(test)]
mod indexed_keys_tests;
pub mod metrics;
pub mod observed;
pub mod read_cache;
@@ -15,6 +22,7 @@ pub mod master_pb {
tonic::include_proto!("master_pb");
}
pub mod master_client;
pub mod memory;
pub mod security {
pub use weed_lance_worker::security::*;
}
+16 -41
View File
@@ -5,6 +5,7 @@ use clap::Parser;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::transport::Server;
use weed_lance_worker::cluster::Cluster;
use weed_vector_server::memory::CacheSizes;
use weed_vector_server::pb::vector::vector_service_server::VectorServiceServer;
use weed_vector_server::read_cache::ReadCache;
use weed_vector_server::security::Security;
@@ -38,25 +39,11 @@ struct Args {
default_value = ""
)]
filer_group: String,
/// Memory for caching reads of write-once table files, in MiB; 0 disables.
#[arg(long, env = "WEED_VECTOR_READ_CACHE_MB", default_value_t = 512)]
read_cache_mb: u64,
/// Memory for indexes loaded by queries, kept for the next query, in MiB.
#[arg(long, env = "WEED_VECTOR_INDEX_CACHE_MB", default_value_t = 1024)]
index_cache_mb: usize,
/// Memory for table metadata (manifests, file footers) kept across
/// queries, in MiB.
#[arg(long, env = "WEED_VECTOR_METADATA_CACHE_MB", default_value_t = 256)]
metadata_cache_mb: usize,
/// Partitions each query probes in a table's vector index. Default: a
/// tenth of the index's partitions, at least 8; more under a filter.
#[arg(long, env = "WEED_VECTOR_NPROBES")]
nprobes: Option<std::num::NonZeroUsize>,
/// The cluster's security.toml: [grpc.vector] for this server,
/// [grpc.client] for the masters and filers, https.client for volume
/// servers under HTTPS, jwt.signing.read.key for signed volume reads,
/// s3.sse.kek or s3.sse.key for SSE-S3 buckets. By default the file weed
/// processes find in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
/// processes find in ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<PathBuf>,
#[arg(
@@ -73,11 +60,6 @@ struct Args {
default_value = "127.0.0.1"
)]
metrics_ip: String,
/// The directory weed's -config_dir names, searched for security.toml
/// first.
#[arg(long, alias = "config_dir", env = "WEED_VECTOR_CONFIG_DIR")]
config_dir: Option<PathBuf>,
}
// weed tools take Go-style single-dash long flags; normalize_args converts
@@ -148,7 +130,7 @@ async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse_from(normalize_args(std::env::args().collect()));
weed_lance_worker::tls::install_default_crypto_provider();
let security = Security::load(args.security_toml.as_deref(), args.config_dir.as_deref())?;
let security = Security::load(args.security_toml.as_deref())?;
if let Some(path) = security.path() {
tracing::info!("security settings from {}", path.display());
}
@@ -166,15 +148,18 @@ async fn main() -> Result<()> {
let (health, health_service) = tonic_health::server::health_reporter();
let metrics = Metrics::new()?.with_health(health);
metrics.set_connected(false).await;
let cache = (args.read_cache_mb > 0)
.then(|| ReadCache::new(args.read_cache_mb << 20).with_metrics(metrics.clone()));
let mut service = VectorServer::new()
.with_nprobes(args.nprobes.map(std::num::NonZeroUsize::get))
.with_lance_caches(args.index_cache_mb << 20, args.metadata_cache_mb << 20)
.with_storage(reads);
if let Some(cache) = &cache {
service = service.with_read_cache(cache.clone());
}
let sizes = CacheSizes::detect();
tracing::info!(
"caching {} MiB of file reads, {} MiB of indexes, {} MiB of table metadata",
sizes.read >> 20,
sizes.index >> 20,
sizes.metadata >> 20
);
let cache = ReadCache::new(sizes.read).with_metrics(metrics.clone());
let service = VectorServer::new()
.with_lance_caches(sizes.index as usize, sizes.metadata as usize)
.with_storage(reads)
.with_read_cache(cache.clone());
if args.metrics_port > 0 {
let ip = args
.metrics_ip
@@ -185,7 +170,7 @@ async fn main() -> Result<()> {
tokio::net::TcpListener::bind(std::net::SocketAddr::new(ip, args.metrics_port)).await?;
let metrics = metrics.clone();
tokio::spawn(async move {
if let Err(error) = metrics::serve_listener(metrics, listener, cache).await {
if let Err(error) = metrics::serve_listener(metrics, listener, Some(cache)).await {
tracing::error!(%error, "vector metrics server stopped");
}
});
@@ -257,16 +242,6 @@ mod tests {
);
}
#[test]
fn nprobes_must_be_positive() {
let parse = |nprobes: &str| {
Args::try_parse_from(["weed-vector", "--masters", "m:9333", "--nprobes", nprobes])
};
assert!(parse("0").is_err());
let args = parse("12").unwrap();
assert_eq!(args.nprobes.map(std::num::NonZeroUsize::get), Some(12));
}
#[test]
fn the_catalog_flags_are_gone() {
let parse = |extra: &[&str]| {
@@ -24,6 +24,7 @@ fn registration(client_addr: &str, filer_group: &str, metrics_port: u16) -> Keep
rack: String::new(),
leave_lock_ring: false,
metrics_port: metrics_port.into(),
lance_port: 0,
}
}
+155
View File
@@ -0,0 +1,155 @@
//! How much the engine caches: a share of the memory this process may use,
//! so a small pod is not overcommitted and a large host is not left idle.
use std::path::{Path, PathBuf};
/// The read, index and metadata caches, in bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheSizes {
pub read: u64,
pub index: u64,
pub metadata: u64,
}
/// Where no limit can be read, the sizes the flags used to default to.
const UNKNOWN_LIMIT_BUDGET: u64 = 1792 << 20;
impl CacheSizes {
/// A quarter of the memory limit, split 2:4:1 between file reads, loaded
/// indexes and table metadata.
pub fn for_limit(limit: Option<u64>) -> Self {
let budget = limit.map_or(UNKNOWN_LIMIT_BUDGET, |limit| limit / 4);
let seventh = budget / 7;
Self {
read: seventh * 2,
index: seventh * 4,
metadata: seventh,
}
}
pub fn detect() -> Self {
Self::for_limit(memory_limit())
}
}
/// The smallest of the machine's memory and the limits of this process's
/// memory cgroup and its ancestors: a systemd service is limited in its own
/// group, a container usually at the root it sees.
fn memory_limit() -> Option<u64> {
let read = |path: &Path| std::fs::read_to_string(path).ok();
let total = read(Path::new("/proc/meminfo")).and_then(|info| mem_total(&info));
let groups = read(Path::new("/proc/self/cgroup"))
.map(|groups| limit_files(&groups))
.unwrap_or_default();
groups
.iter()
.filter_map(|file| read(file).and_then(|limit| cgroup_limit(&limit)))
.chain(total)
.min()
}
/// The limit files of the memory cgroup `/proc/self/cgroup` names and of its
/// ancestors: v1's memory controller where it has one, else v2's unified group.
fn limit_files(self_cgroup: &str) -> Vec<PathBuf> {
let entries: Vec<(&str, &str)> = self_cgroup
.lines()
.filter_map(|line| {
let mut fields = line.splitn(3, ':');
fields.next()?;
Some((fields.next()?, fields.next()?))
})
.collect();
let v1 = entries
.iter()
.find(|(controllers, _)| controllers.split(',').any(|c| c == "memory"))
.map(|(_, group)| ("/sys/fs/cgroup/memory", *group, "memory.limit_in_bytes"));
let v2 = entries
.iter()
.find(|(controllers, _)| controllers.is_empty())
.map(|(_, group)| ("/sys/fs/cgroup", *group, "memory.max"));
let Some((root, group, file)) = v1.or(v2) else {
return Vec::new();
};
Path::new(group)
.ancestors()
.map(|dir| {
Path::new(root)
.join(dir.strip_prefix("/").unwrap_or(dir))
.join(file)
})
.collect()
}
fn mem_total(meminfo: &str) -> Option<u64> {
let line = meminfo.lines().find(|line| line.starts_with("MemTotal:"))?;
let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
Some(kib << 10)
}
/// cgroup v2 writes "max" for no limit; v1 writes a number near u64::MAX.
fn cgroup_limit(limit: &str) -> Option<u64> {
let bytes: u64 = limit.trim().parse().ok()?;
(bytes < 1 << 60).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_quarter_of_the_limit_split_two_four_one() {
let sizes = CacheSizes::for_limit(Some(28 << 30));
assert_eq!(sizes.read, 2 << 30);
assert_eq!(sizes.index, 4 << 30);
assert_eq!(sizes.metadata, 1 << 30);
}
#[test]
fn no_limit_keeps_the_former_defaults() {
let sizes = CacheSizes::for_limit(None);
assert_eq!(
(sizes.read, sizes.index, sizes.metadata),
(512 << 20, 1024 << 20, 256 << 20)
);
}
#[test]
fn looks_up_the_process_group_and_its_ancestors() {
let paths = |groups: &str| -> Vec<String> {
limit_files(groups)
.iter()
.map(|p| p.display().to_string().replace('\\', "/"))
.collect()
};
assert_eq!(
paths("0::/system.slice/weed-vector.service\n"),
[
"/sys/fs/cgroup/system.slice/weed-vector.service/memory.max",
"/sys/fs/cgroup/system.slice/memory.max",
"/sys/fs/cgroup/memory.max",
]
);
// A container's namespace shows its own group as the root.
assert_eq!(paths("0::/\n"), ["/sys/fs/cgroup/memory.max"]);
// On a hybrid host the memory controller is v1's.
assert_eq!(
paths("12:cpu,cpuacct:/a\n4:memory:/user.slice\n0::/user.slice\n"),
[
"/sys/fs/cgroup/memory/user.slice/memory.limit_in_bytes",
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
]
);
assert!(paths("").is_empty());
}
#[test]
fn reads_the_limits_the_kernel_writes() {
assert_eq!(
mem_total("MemTotal: 16384000 kB\nMemFree: 1 kB\n"),
Some(16_384_000 << 10)
);
assert_eq!(cgroup_limit("4294967296\n"), Some(4 << 30));
assert_eq!(cgroup_limit("max\n"), None);
assert_eq!(cgroup_limit("9223372036854771712\n"), None);
}
}
@@ -10,6 +10,10 @@ use tonic_health::{ServingStatus, server::HealthReporter};
use crate::read_cache::ReadCache;
/// The gRPC health service an engine reports serving when its writes derive
/// the indexed metadata key columns.
pub const METADATA_COLUMNS_CAPABILITY: &str = "weed.vector.capability.metadata_columns";
#[derive(Clone)]
pub struct Metrics {
pub registry: Registry,
@@ -120,6 +124,11 @@ impl Metrics {
health
.set_service_status("vector_pb.VectorService", status)
.await;
// A capability, not readiness: the admin refuses to index a
// metadata key while an engine without it could write the table.
health
.set_service_status(METADATA_COLUMNS_CAPABILITY, ServingStatus::Serving)
.await;
}
}
@@ -78,6 +78,33 @@ impl VectorService for ObservedService {
}
result
}
async fn metadata_keys(
&self,
request: Request<pb::MetadataKeysRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let mut in_flight = self.metrics.start("MetadataKeys");
let result = self.inner.metadata_keys(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn update_metadata_key(
&self,
request: Request<pb::UpdateMetadataKeyRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let mut in_flight = self.metrics.start("UpdateMetadataKey");
let result = self.inner.update_metadata_key(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn filter_stats(
&self,
request: Request<pb::FilterStatsRequest>,
) -> Result<Response<pb::FilterStatsResponse>, Status> {
let mut in_flight = self.metrics.start("FilterStats");
let result = self.inner.filter_stats(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
}
#[cfg(test)]
+296 -54
View File
@@ -19,7 +19,9 @@ use weed_lance_worker::catalog::TableDescription;
use weed_lance_worker::dataset;
use weed_lance_worker::direct_read::{DirectReads, Wrappers};
use weed_lance_worker::jobs::vector_index::is_vector_table;
use weed_lance_worker::metadata_index;
use weed_vector_core::index;
use weed_vector_core::indexed_filter;
use weed_vector_core::maintenance::SharedLeases;
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
@@ -167,14 +169,13 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
};
let vectors_array =
FixedSizeListArray::try_new(item_field.clone(), dimension as i32, values, None)?;
let metas = vectors
let json: Vec<Option<serde_json::Value>> = vectors
.iter()
.map(|v| {
v.metadata
.as_ref()
.map(|m| serde_json::to_string(&struct_to_json(m)))
.transpose()
})
.map(|v| v.metadata.as_ref().map(struct_to_json))
.collect();
let metas = json
.iter()
.map(|m| m.as_ref().map(serde_json::to_string).transpose())
.collect::<Result<Vec<_>, _>>()?;
// The stored column is lance's jsonb (LargeBinary) once the field carries
// the arrow.json extension; encode the strings, else keep the Utf8 batch.
@@ -187,11 +188,188 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
}
_ => Arc::new(StringArray::from(metas)),
};
RecordBatch::try_new(
schema,
vec![Arc::new(keys), Arc::new(vectors_array), metadata_array],
let (keys, vectors_array): (ArrayRef, ArrayRef) = (Arc::new(keys), Arc::new(vectors_array));
// An indexed metadata key's column is derived from the row's metadata,
// whatever the key's state.
let columns = schema
.fields()
.iter()
.map(|field| match field.name().as_str() {
KEY_COLUMN => Ok(keys.clone()),
VECTOR_COLUMN => Ok(vectors_array.clone()),
METADATA_COLUMN => Ok(metadata_array.clone()),
name => match metadata_index::indexed_key(field) {
Some(indexed) => Ok(metadata_index::column_from_json(
json.iter().map(Option::as_ref),
&indexed.key,
)),
None => bail!("the table has a column {name} that PutVectors cannot fill"),
},
})
.collect::<Result<Vec<_>>>()?;
RecordBatch::try_new(schema, columns).map_err(Into::into)
}
/// Upserts `vectors` by key into `dataset`, the version the request opened,
/// then fills the indexed-key columns a concurrent column add left empty.
pub(crate) async fn write_vectors(
dataset: Dataset,
vectors: &[pb::Vector],
) -> Result<Dataset, Status> {
let written = Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema()));
let dataset = merge_vectors(dataset, vectors).await?;
let keys: Vec<String> = vectors.iter().map(|v| v.key.clone()).collect();
heal_columns(dataset, &written, &keys)
.await
.map_err(internal)
}
/// The upsert itself, in the schema of the version `dataset` is at.
pub(crate) async fn merge_vectors(
dataset: Dataset,
vectors: &[pb::Vector],
) -> Result<Dataset, Status> {
let dimension = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN))
.map_err(invalid)?
.dimension;
let batch = batch_of(
vectors,
dimension,
Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema())),
)
.map_err(Into::into)
.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(Arc::unwrap_or_clone(dataset))
}
/// Attempts [`heal_columns`] makes against writes committing meanwhile.
const HEAL_ATTEMPTS: usize = 10;
/// Lance rebases a write onto a column add committed after the write opened
/// its version: the rows it inserted hold NULL in the new column and the
/// rows it updated keep the value derived from their old metadata. Derive
/// such columns again for the rows of `keys` from their stored metadata.
pub(crate) async fn heal_columns(
mut dataset: Dataset,
written: &Schema,
keys: &[String],
) -> Result<Dataset> {
for _ in 0..HEAL_ATTEMPTS {
let schema: Schema = dataset.schema().into();
let missing: Vec<metadata_index::IndexedKey> = metadata_index::indexed_keys(&schema)
.into_iter()
.filter(|k| written.field_with_name(&k.column).is_err())
.collect();
if missing.is_empty() || keys.is_empty() {
return Ok(dataset);
}
let mut scanner = dataset.scan();
scanner
.filter(&key_list(keys))?
.project(&[KEY_COLUMN, METADATA_COLUMN])?;
let rows: Vec<RecordBatch> = scanner.try_into_stream().await?.try_collect().await?;
let mut fields = vec![schema.field_with_name(KEY_COLUMN)?.clone()];
for k in &missing {
fields.push(schema.field_with_name(&k.column)?.clone());
}
let patch_schema = Arc::new(Schema::new(fields));
let mut patches = Vec::new();
for batch in rows.iter().filter(|b| b.num_rows() > 0) {
let (Some(keys), Some(metadata)) = (
batch.column_by_name(KEY_COLUMN),
batch.column_by_name(METADATA_COLUMN),
) else {
bail!("the scan did not return keys and metadata");
};
let mut columns = vec![keys.clone()];
for k in &missing {
columns.push(metadata_index::column_from_metadata(
metadata.as_ref(),
&k.key,
)?);
}
patches.push(RecordBatch::try_new(patch_schema.clone(), columns)?);
}
if patches.is_empty() {
return Ok(dataset);
}
// Lance's own retry would join these values onto rows a later write
// replaced; derive them again from the version that write left.
let mut builder =
MergeInsertBuilder::try_new(Arc::new(dataset.clone()), vec![KEY_COLUMN.to_string()])?;
builder
.when_matched(WhenMatched::UpdateAll)
.when_not_matched(WhenNotMatched::DoNothing)
.conflict_retries(0);
match builder.try_build()?.execute_batches(patches).await {
Ok((healed, _stats)) => {
tracing::info!(
rows = rows.iter().map(|b| b.num_rows()).sum::<usize>(),
"derived indexed metadata key columns a concurrent column add left stale"
);
return Ok(Arc::unwrap_or_clone(healed));
}
Err(lance::Error::TooMuchWriteContention { .. }) => dataset.checkout_latest().await?,
Err(e) => return Err(e.into()),
}
}
bail!("writes kept replacing the rows while their indexed key columns were derived")
}
/// The indexed metadata keys `dataset` records, requested ones first.
async fn metadata_keys(dataset: &Dataset) -> Result<pb::MetadataKeysResponse> {
let rows: u64 = dataset
.fragments()
.iter()
.map(|f| f.num_rows().unwrap_or(0) as u64)
.sum();
let mut keys: Vec<pb::MetadataKey> = metadata_index::requests(dataset)
.into_iter()
.map(|key| pb::MetadataKey {
key,
state: "requested".to_string(),
rows,
..Default::default()
})
.collect();
for key in metadata_index::keys_of(dataset) {
let segments = metadata_index::segments(dataset, &key.column).await?;
keys.push(pb::MetadataKey {
state: key.state.map_or("unknown", |s| s.as_str()).to_string(),
indexed_rows: segments.iter().map(|s| s.rows).sum(),
index_bytes: segments.iter().map(|s| s.bytes).sum(),
segments: segments.len() as u32,
rows,
key: key.key,
column: key.column,
});
}
let vector_index = match index::index_names(dataset, VECTOR_COLUMN).await?.first() {
Some(name) => {
weed_lance_worker::vector_index::index_settings(dataset, name)
.await?
.index_type
}
None => String::new(),
};
Ok(pb::MetadataKeysResponse {
keys,
version: dataset.version().version,
rows,
vector_index,
})
}
fn struct_to_json(s: &Struct) -> serde_json::Value {
@@ -230,7 +408,7 @@ fn json_to_value(v: serde_json::Value) -> Value {
Value { kind: Some(kind) }
}
fn json_to_struct(map: serde_json::Map<String, serde_json::Value>) -> Struct {
pub(crate) fn json_to_struct(map: serde_json::Map<String, serde_json::Value>) -> Struct {
Struct {
fields: map
.into_iter()
@@ -527,7 +705,8 @@ pub struct VectorServer {
pub(crate) handles: moka::sync::Cache<(String, bool), (u64, Dataset)>,
lance_cache_bytes: (usize, usize),
leases: SharedLeases,
nprobes: Option<usize>,
exact_match_limit: Option<usize>,
filter_stats: crate::filter_stats::FilterStats,
/// URI schemes a table's location may have.
schemes: &'static [&'static str],
}
@@ -550,7 +729,8 @@ impl VectorServer {
lance_cache_bytes: (DEFAULT_INDEX_CACHE_BYTES, DEFAULT_METADATA_CACHE_BYTES),
handles: moka::sync::Cache::new(MAX_HANDLES),
leases: SharedLeases::default(),
nprobes: None,
exact_match_limit: None,
filter_stats: Default::default(),
schemes: &["s3"],
}
}
@@ -562,9 +742,11 @@ impl VectorServer {
self
}
/// Partitions every query probes, instead of the index's own default.
pub fn with_nprobes(mut self, nprobes: Option<usize>) -> Self {
self.nprobes = nprobes;
/// Matches of a filter's indexed metadata keys scored exactly instead of
/// searched through the vector index, at most; None keeps the default.
#[cfg(test)]
pub(crate) fn with_exact_match_limit(mut self, limit: Option<usize>) -> Self {
self.exact_match_limit = limit;
self
}
@@ -740,7 +922,11 @@ impl VectorService for VectorServer {
)
.await;
let dataset = match dataset {
Ok(dataset) => dataset,
Ok(dataset) => {
self.filter_stats
.forget(&table.id.join("/"), table_id(&dataset));
dataset
}
Err(error) => match self.open(&table).await {
Ok(existing)
if matches_index_schema(
@@ -791,6 +977,7 @@ impl VectorService for VectorServer {
store.remove_dir_all(path).await.map_err(internal)?;
}
}
self.filter_stats.forget(&table.id.join("/"), "");
Ok(Response::new(pb::DropIndexResponse {}))
}
@@ -802,35 +989,37 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open(&table).await?;
if req.vectors.is_empty() {
return Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
}));
if table.version != 0 {
return Err(Status::invalid_argument("a write takes no table 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)?;
// A write commits within its deadline of opening the table or not
// at all: a key's column add waits longer than that before the key
// is ready, so a write that opened before the add has committed,
// and been derived again, before any query uses the key.
let merged = tokio::time::timeout(metadata_index::WRITE_DEADLINE, async {
let dataset = self.open(&table).await?;
if req.vectors.is_empty() {
return Ok::<_, Status>((dataset, None));
}
let written = Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema()));
Ok((merge_vectors(dataset, &req.vectors).await?, Some(written)))
})
.await
.map_err(|_| {
Status::deadline_exceeded(format!(
"PutVectors took longer than {:?} to commit",
metadata_index::WRITE_DEADLINE
))
})??;
let dataset = match merged {
(dataset, Some(written)) => {
let keys: Vec<String> = req.vectors.iter().map(|v| v.key.clone()).collect();
heal_columns(dataset, &written, &keys)
.await
.map_err(internal)?
}
(dataset, None) => dataset,
};
Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
}))
@@ -908,14 +1097,9 @@ impl VectorService for VectorServer {
0 => DEFAULT_PAGE,
n => n.min(MAX_PAGE),
};
// A purge keeps only the latest version, so lease the one this page reads.
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
if segments > 1 {
// Data and metadata come from a second read of this version, so
// lease it as get_vectors does.
let _lease = if columns.len() > 1 {
self.leases.try_pin(&dataset).await.map_err(internal)?
} else {
None
};
let (vectors, next) = list_segment(
&dataset,
&columns,
@@ -953,6 +1137,7 @@ impl VectorService for VectorServer {
&self,
request: Request<pb::QueryVectorsRequest>,
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
let started = std::time::Instant::now();
let req = request.into_inner();
let table = req
.table
@@ -962,6 +1147,11 @@ impl VectorService for VectorServer {
// while this query runs against it.
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
let filter_keys = if req.filter.is_empty() {
Default::default()
} else {
indexed_filter::filter_keys(&dataset, &req.filter).unwrap_or_default()
};
if req.query_vector.len() != resolved.dimension {
return Err(Status::invalid_argument(format!(
"query vector carries {} floats, the index dimension is {}",
@@ -983,9 +1173,10 @@ impl VectorService for VectorServer {
},
postfilter: req.postfilter,
distance,
nprobes: self.nprobes,
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: self.exact_match_limit,
};
let hits = query::ann(&dataset, &resolved, &query)
.await
@@ -1061,8 +1252,59 @@ impl VectorService for VectorServer {
data: data_map.remove(&hit.key).unwrap_or_default(),
});
}
let index = table.id.join("/");
self.filter_stats
.record(&index, table_id(&dataset), &filter_keys, started.elapsed());
Ok(Response::new(pb::QueryVectorsResponse { vectors }))
}
async fn metadata_keys(
&self,
request: Request<pb::MetadataKeysRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let table = request
.into_inner()
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open_to_read(&table).await?;
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
Ok(Response::new(
metadata_keys(&dataset).await.map_err(internal)?,
))
}
async fn update_metadata_key(
&self,
request: Request<pb::UpdateMetadataKeyRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, 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?;
let updated = if req.remove {
metadata_index::request_removal(&mut dataset, &req.key).await
} else {
metadata_index::request(&mut dataset, &req.key).await
};
updated.map_err(|e| Status::failed_precondition(format!("{e:#}")))?;
Ok(Response::new(
metadata_keys(&dataset).await.map_err(internal)?,
))
}
async fn filter_stats(
&self,
request: Request<pb::FilterStatsRequest>,
) -> Result<Response<pb::FilterStatsResponse>, Status> {
let table = request
.into_inner()
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
Ok(Response::new(
self.filter_stats.snapshot(&table.id.join("/")),
))
}
}
#[cfg(test)]
+2 -2
View File
@@ -3195,9 +3195,9 @@ dependencies = [
[[package]]
name = "redb"
version = "4.2.0"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de6c3b63e007e90ce536ec2ae4690826136a20ec8dbbbb400daef1bb999d2e36"
checksum = "096b1dd5ec053c9c2a5a26a93aafeadf73ebcb710ea54dc3151f17a8e20535ef"
dependencies = [
"libc",
]
-3
View File
@@ -19,9 +19,6 @@ path = "src/main.rs"
# Disable with --no-default-features for 4-byte offsets (32GB max volume size).
default = ["5bytes"]
5bytes = []
# Unstable redb cursor bulk-load for full_rebuild. Off in production.
# Pulls redb's experimental_cursor (and therefore experimental-api-5).
redb-experimental-cursor = ["redb/experimental_cursor"]
[lints.clippy]
# Protobuf message literals keep `..Default::default()` on purpose: it is
+3
View File
@@ -234,6 +234,8 @@ message KeepConnectedRequest {
// it is not enabled. Advertised so the admin server can scrape it without
// exposing metrics on the client-facing service port.
uint32 metrics_port = 9;
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
uint32 lance_port = 10;
}
message VolumeLocation {
@@ -559,6 +561,7 @@ message ListClusterNodesResponse {
string address = 1;
string version = 2;
int64 created_at_ns = 4;
uint32 lance_port = 7;
string data_center = 5;
string rack = 6;
}
+2
View File
@@ -147,6 +147,7 @@ service VolumeServer {
message BatchDeleteRequest {
repeated string file_ids = 1;
bool skip_cookie_check = 2;
bool fsync = 3;
}
message BatchDeleteResponse {
@@ -481,6 +482,7 @@ message VolumeEcShardsCopyRequest {
bool copy_vif_file = 7;
uint32 disk_id = 8; // Target disk ID for storing EC shards
bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
string disk_type = 11; // with disk_id 0, pick only among disks of this type; empty means any
}
message VolumeEcShardsCopyResponse {
}
+63 -1
View File
@@ -138,7 +138,8 @@ pub struct Cli {
#[arg(long = "concurrentUploadLimitMB", default_value_t = 0)]
pub concurrent_upload_limit_mb: u32,
/// Limit total concurrent download size in MB, 0 means unlimited.
/// Limit total concurrent download size in MB, 0 means unlimited; reads over
/// the limit are sent to a replica unless readMode is local.
#[arg(long = "concurrentDownloadLimitMB", default_value_t = 0)]
pub concurrent_download_limit_mb: u32,
@@ -305,6 +306,8 @@ pub struct VolumeServerConfig {
pub ui_enabled: bool,
pub jwt_signing_key: Vec<u8>,
pub jwt_signing_expires_seconds: i64,
pub jwt_previous_signing_key: Vec<u8>,
pub jwt_previous_read_signing_key: Vec<u8>,
pub jwt_read_signing_key: Vec<u8>,
pub jwt_read_signing_expires_seconds: i64,
pub https_cert_file: String,
@@ -998,6 +1001,8 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
ui_enabled: sec.jwt_signing_key.is_empty() || sec.access_ui,
jwt_signing_key: sec.jwt_signing_key,
jwt_signing_expires_seconds: sec.jwt_signing_expires,
jwt_previous_signing_key: sec.jwt_previous_signing_key,
jwt_previous_read_signing_key: sec.jwt_previous_read_signing_key,
jwt_read_signing_key: sec.jwt_read_signing_key,
jwt_read_signing_expires_seconds: sec.jwt_read_signing_expires,
https_cert_file: sec.https_cert_file,
@@ -1029,6 +1034,8 @@ fn default_volume_dir() -> String {
pub struct SecurityConfig {
pub jwt_signing_key: Vec<u8>,
pub jwt_signing_expires: i64,
pub jwt_previous_signing_key: Vec<u8>,
pub jwt_previous_read_signing_key: Vec<u8>,
pub jwt_read_signing_key: Vec<u8>,
pub jwt_read_signing_expires: i64,
pub https_cert_file: String,
@@ -1047,6 +1054,8 @@ pub struct SecurityConfig {
pub grpc_volume_allowed_common_names: Vec<String>,
pub tls_policy: TlsPolicy,
pub access_ui: bool,
/// The file was read; otherwise only defaults and WEED_ overrides are set.
pub file_read: bool,
/// IPs from [guard] white_list in security.toml
pub guard_white_list: Vec<String>,
}
@@ -1179,6 +1188,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
match section {
Section::JwtSigningRead => match key {
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_read_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_read_signing_expires = value.parse().unwrap_or(60)
}
@@ -1186,6 +1196,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
},
Section::JwtSigning => match key {
"key" => cfg.jwt_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_signing_expires = value.parse().unwrap_or(10)
}
@@ -1261,6 +1272,7 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
// prefix WEED_, uppercase, replace . with _).
// e.g. WEED_JWT_SIGNING_KEY overrides [jwt.signing] key
apply_env_overrides(&mut cfg, env);
cfg.file_read = true;
cfg
}
@@ -1299,6 +1311,12 @@ fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_EXPIRES_AFTER_SECONDS") {
cfg.jwt_signing_expires = v.parse().unwrap_or(cfg.jwt_signing_expires);
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_PREVIOUS_KEY") {
cfg.jwt_previous_signing_key = v.into_bytes();
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_READ_PREVIOUS_KEY") {
cfg.jwt_previous_read_signing_key = v.into_bytes();
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_READ_KEY") {
cfg.jwt_read_signing_key = v.into_bytes();
}
@@ -2176,6 +2194,50 @@ cipher_suites = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_previous_signing_keys_from_file_and_env() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "write-new"
previous_key = "write-old"
[jwt.signing.read]
key = "read-new"
previous_key = "read-old"
"#,
)
.unwrap();
let path = tmp.path().to_str().unwrap();
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.jwt_previous_signing_key, b"write-old");
assert_eq!(cfg.jwt_previous_read_signing_key, b"read-old");
let env = fake_env(&[
("WEED_JWT_SIGNING_PREVIOUS_KEY", "env-write-old"),
("WEED_JWT_SIGNING_READ_PREVIOUS_KEY", "env-read-old"),
]);
let cfg = parse_security_config_with_env(path, &env);
assert_eq!(cfg.jwt_previous_signing_key, b"env-write-old");
assert_eq!(cfg.jwt_previous_read_signing_key, b"env-read-old");
}
#[test]
fn test_security_config_file_read() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
let path = tmp.path().to_str().unwrap().to_string();
assert!(parse_security_config_with_env(&path, &fake_env(&[])).file_read);
drop(tmp);
let env = fake_env(&[("WEED_JWT_SIGNING_KEY", "env-secret")]);
let cfg = parse_security_config_with_env(&path, &env);
assert!(!cfg.file_read);
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_env_override_takes_precedence_over_file() {
let tmp = tempfile::NamedTempFile::new().unwrap();
+12 -2
View File
@@ -340,7 +340,7 @@ async fn run(
store.set_volume_load_guard(volume_copies_in_flight.clone());
// Build shared state
let guard = Guard::new(
let mut guard = Guard::new(
&config.white_list,
SigningKey(config.jwt_signing_key.clone()),
config.jwt_signing_expires_seconds,
@@ -358,6 +358,8 @@ async fn run(
let security_file = config.security_file.clone();
let cli_white_list = config.white_list.clone();
guard.previous_signing_key = SigningKey(config.jwt_previous_signing_key.clone());
guard.previous_read_signing_key = SigningKey(config.jwt_previous_read_signing_key.clone());
let state = Arc::new(VolumeServerState {
store: RwLock::new(store),
@@ -416,6 +418,7 @@ async fn run(
.to_string_lossy()
.into_owned()
},
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight,
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
@@ -450,6 +453,7 @@ async fn run(
{
let mut store = state.store.write().unwrap();
store.store_dirs = config.folders.clone();
for (i, dir) in config.folders.iter().enumerate() {
let idx_dir = if config.idx_folder.is_empty() {
dir.as_str()
@@ -617,9 +621,13 @@ async fn run(
}
// 2. Reload security config (Go's Reload)
{
'security: {
info!("Reloading security config...");
let sec = config::parse_security_config(&state_reload.security_file);
if !sec.file_read {
warn!("SIGHUP: security config cannot be read, keeping the keys in effect");
break 'security;
}
let mut whitelist = state_reload.cli_white_list.clone();
whitelist.extend(sec.guard_white_list.iter().cloned());
let mut guard = state_reload.guard.write().unwrap();
@@ -629,6 +637,8 @@ async fn run(
sec.jwt_signing_expires,
SigningKey(sec.jwt_read_signing_key),
sec.jwt_read_signing_expires,
SigningKey(sec.jwt_previous_signing_key),
SigningKey(sec.jwt_previous_read_signing_key),
);
}
+14
View File
@@ -85,6 +85,19 @@ pub static VACUUMING_COMMIT_COUNTER: LazyLock<IntCounterVec> = LazyLock::new(||
.expect("metric can be created")
});
/// Live needles vacuum dropped because their data could not be read back
/// intact, with label `collection`.
pub static VACUUMING_DROPPED_NEEDLES_COUNTER: LazyLock<IntCounterVec> = LazyLock::new(|| {
IntCounterVec::new(
Opts::new(
"SeaweedFS_volumeServer_vacuuming_dropped_needles",
"Counter of live needles dropped by vacuum because their data could not be read back intact.",
),
&["collection"],
)
.expect("metric can be created")
});
/// Vacuuming duration histogram with label `type` (compact/commit).
pub static VACUUMING_HISTOGRAM: LazyLock<HistogramVec> = LazyLock::new(|| {
HistogramVec::new(
@@ -402,6 +415,7 @@ pub fn register_metrics() {
Box::new(VACUUMING_COMPACT_COUNTER.clone()),
Box::new(VACUUMING_COMMIT_COUNTER.clone()),
Box::new(VACUUMING_HISTOGRAM.clone()),
Box::new(VACUUMING_DROPPED_NEEDLES_COUNTER.clone()),
Box::new(VOLUME_GAUGE.clone()),
Box::new(READ_ONLY_VOLUME_GAUGE.clone()),
Box::new(MAX_VOLUMES.clone()),
+207 -23
View File
@@ -83,7 +83,13 @@ pub fn gen_jwt(
}
/// Decode and validate a JWT token.
pub fn decode_jwt(signing_key: &SigningKey, token: &str) -> Result<FileIdClaims, JwtError> {
/// A token whose signature does not match `signing_key` is checked against
/// each non-empty `previous_keys` entry, like Go's `security.DecodeJwt`.
pub fn decode_jwt(
signing_key: &SigningKey,
token: &str,
previous_keys: &[&SigningKey],
) -> Result<FileIdClaims, JwtError> {
if signing_key.is_empty() {
return Err(JwtError::NoSigningKey);
}
@@ -97,13 +103,64 @@ pub fn decode_jwt(signing_key: &SigningKey, token: &str) -> Result<FileIdClaims,
validation.validate_nbf = true;
validation.leeway = 0;
let data = decode::<FileIdClaims>(
let mut result = decode::<FileIdClaims>(
token,
&DecodingKey::from_secret(&signing_key.0),
&validation,
)?;
);
for previous in previous_keys {
let bad_signature = matches!(&result, Err(e)
if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::InvalidSignature));
if !bad_signature {
break;
}
if previous.is_empty() || previous.0 == signing_key.0 {
continue;
}
result = decode::<FileIdClaims>(token, &DecodingKey::from_secret(&previous.0), &validation);
}
Ok(data.claims)
Ok(result?.claims)
}
/// Reports a signed, fid-bound write token whose only failure is expiry. It
/// never authorizes a request. Mirrors Go's `security.IsExpiredVolumeJwt`.
pub fn is_expired_volume_jwt(
signing_key: &SigningKey,
token: &str,
expected_fid: &str,
previous_keys: &[&SigningKey],
) -> bool {
match decode_jwt(signing_key, token, previous_keys) {
Err(JwtError::Jwt(e))
if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::ExpiredSignature) => {}
_ => return false,
}
#[derive(Deserialize)]
struct ExpiredClaims {
fid: Option<String>,
iat: Option<u64>,
}
let mut validation = Validation::new(Algorithm::HS256);
validation.required_spec_claims.clear();
validation.validate_exp = false;
validation.validate_nbf = true;
validation.leeway = 0;
let Some(data) = std::iter::once(signing_key)
.chain(previous_keys.iter().copied())
.filter(|key| !key.is_empty())
.find_map(|key| {
decode::<ExpiredClaims>(token, &DecodingKey::from_secret(&key.0), &validation).ok()
})
else {
return false;
};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
data.claims.fid.as_deref() == Some(expected_fid) && data.claims.iat.is_none_or(|iat| iat <= now)
}
// ============================================================================
@@ -118,6 +175,9 @@ pub struct Guard {
pub expires_after_sec: i64,
pub read_signing_key: SigningKey,
pub read_expires_after_sec: i64,
/// Accepted when verifying, never used to sign.
pub previous_signing_key: SigningKey,
pub previous_read_signing_key: SigningKey,
/// Combined flag: true when whitelist is non-empty OR signing key is present.
/// Matches Go's `isWriteActive = !isEmptyWhiteList || len(SigningKey) != 0`.
is_write_active: bool,
@@ -138,6 +198,8 @@ impl Guard {
expires_after_sec,
read_signing_key,
read_expires_after_sec,
previous_signing_key: SigningKey(vec![]),
previous_read_signing_key: SigningKey(vec![]),
is_write_active: false,
};
guard.update_whitelist(whitelist);
@@ -182,11 +244,15 @@ impl Guard {
expires_after_sec: i64,
read_signing_key: SigningKey,
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) {
self.signing_key = signing_key;
self.expires_after_sec = expires_after_sec;
self.read_signing_key = read_signing_key;
self.read_expires_after_sec = read_expires_after_sec;
self.previous_signing_key = previous_signing_key;
self.previous_read_signing_key = previous_read_signing_key;
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
@@ -229,6 +295,16 @@ impl Guard {
false
}
/// The write (or read) signing key and the previous key still accepted for
/// it. Mirrors Go's `Guard.VerificationKeys`.
pub fn verification_keys(&self, is_write: bool) -> (&SigningKey, &SigningKey) {
if is_write {
(&self.signing_key, &self.previous_signing_key)
} else {
(&self.read_signing_key, &self.previous_read_signing_key)
}
}
/// Check if a read signing key is configured.
pub fn has_read_signing_key(&self) -> bool {
!self.read_signing_key.is_empty()
@@ -238,18 +314,14 @@ impl Guard {
/// `is_write` determines which signing key to use.
/// Returns Ok(()) if valid, or if security is disabled.
pub fn check_jwt(&self, token: Option<&str>, is_write: bool) -> Result<(), JwtError> {
let key = if is_write {
&self.signing_key
} else {
&self.read_signing_key
};
let (key, previous) = self.verification_keys(is_write);
if key.is_empty() {
return Ok(()); // Security disabled for this operation type
}
let token = token.ok_or(JwtError::MissingToken)?;
decode_jwt(key, token)?;
decode_jwt(key, token, &[previous])?;
Ok(())
}
@@ -260,18 +332,14 @@ impl Guard {
expected_fid: &str,
is_write: bool,
) -> Result<(), JwtError> {
let key = if is_write {
&self.signing_key
} else {
&self.read_signing_key
};
let (key, previous) = self.verification_keys(is_write);
if key.is_empty() {
return Ok(());
}
let token = token.ok_or(JwtError::MissingToken)?;
let claims = decode_jwt(key, token)?;
let claims = decode_jwt(key, token, &[previous])?;
match claims.fid {
None => {
@@ -385,7 +453,7 @@ mod tests {
fn test_jwt_round_trip() {
let key = SigningKey::from_string("test-secret-key");
let token = gen_jwt(&key, 3600, "3,01637037d6").unwrap();
let claims = decode_jwt(&key, &token).unwrap();
let claims = decode_jwt(&key, &token, &[]).unwrap();
assert_eq!(claims.fid, Some("3,01637037d6".to_string()));
}
@@ -398,7 +466,7 @@ mod tests {
#[test]
fn test_jwt_invalid_token() {
let key = SigningKey::from_string("secret");
let result = decode_jwt(&key, "invalid.token.here");
let result = decode_jwt(&key, "invalid.token.here", &[]);
assert!(result.is_err());
}
@@ -407,7 +475,60 @@ mod tests {
let key1 = SigningKey::from_string("secret1");
let key2 = SigningKey::from_string("secret2");
let token = gen_jwt(&key1, 3600, "1,abc").unwrap();
assert!(decode_jwt(&key2, &token).is_err());
assert!(decode_jwt(&key2, &token, &[]).is_err());
}
#[test]
fn test_is_expired_volume_jwt_classifies_expiry_only() {
let key = SigningKey::from_string("write-key");
let fid = "3,01637037d6";
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let sign = |claims: serde_json::Value, key: &SigningKey| {
encode(
&Header::new(Algorithm::HS256),
&claims,
&EncodingKey::from_secret(&key.0),
)
.unwrap()
};
let expired = sign(serde_json::json!({"fid": fid, "exp": now - 10}), &key);
assert!(is_expired_volume_jwt(&key, &expired, fid, &[]));
assert!(!is_expired_volume_jwt(&key, &expired, "3,01637037d7", &[]));
assert!(!is_expired_volume_jwt(
&SigningKey::from_string("other-key"),
&expired,
fid,
&[]
));
assert!(!is_expired_volume_jwt(
&SigningKey(vec![]),
&expired,
fid,
&[]
));
let immature = sign(
serde_json::json!({"fid": fid, "exp": now - 10, "nbf": now + 60}),
&key,
);
assert!(!is_expired_volume_jwt(&key, &immature, fid, &[]));
let future_issued = sign(
serde_json::json!({"fid": fid, "exp": now - 10, "iat": now + 60}),
&key,
);
assert!(!is_expired_volume_jwt(&key, &future_issued, fid, &[]));
let live = sign(serde_json::json!({"fid": fid, "exp": now + 60}), &key);
assert!(!is_expired_volume_jwt(&key, &live, fid, &[]));
let unsigned = format!(
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.{}.",
base64::Engine::encode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
serde_json::json!({"fid": fid, "exp": now - 10}).to_string()
)
);
assert!(!is_expired_volume_jwt(&key, &unsigned, fid, &[]));
}
#[test]
@@ -507,25 +628,88 @@ mod tests {
11,
SigningKey::from_string("new-read"),
61,
SigningKey(vec![]),
SigningKey(vec![]),
);
let token = gen_jwt(&guard.signing_key, 60, "3,01637037d6").unwrap();
// Validates with the rotated key, not the old one.
assert!(decode_jwt(&guard.signing_key, &token).is_ok());
assert!(decode_jwt(&SigningKey::from_string("old-write"), &token).is_err());
assert!(decode_jwt(&guard.signing_key, &token, &[]).is_ok());
assert!(decode_jwt(&SigningKey::from_string("old-write"), &token, &[]).is_err());
assert_eq!(guard.expires_after_sec, 11);
assert_eq!(guard.read_expires_after_sec, 61);
}
#[test]
fn test_previous_signing_key_is_accepted() {
let fid = "3,01637037d6";
let accepts = |guard: &Guard, key: &str, is_write: bool| {
let token = gen_jwt(&SigningKey::from_string(key), 60, fid).unwrap();
guard
.check_jwt_for_file(Some(&token), fid, is_write)
.is_ok()
};
let mut guard = Guard::new(
&[],
SigningKey::from_string("write-new"),
10,
SigningKey::from_string("read-new"),
60,
);
guard.previous_signing_key = SigningKey::from_string("write-old");
guard.previous_read_signing_key = SigningKey::from_string("read-old");
assert!(accepts(&guard, "write-new", true));
assert!(accepts(&guard, "write-old", true));
assert!(accepts(&guard, "read-old", false));
assert!(!accepts(&guard, "other", true));
assert!(!accepts(&guard, "read-old", true));
let expired = encode(
&Header::new(Algorithm::HS256),
&serde_json::json!({"fid": fid, "exp": 1}),
&EncodingKey::from_secret(b"write-old"),
)
.unwrap();
let (key, previous) = guard.verification_keys(true);
assert!(is_expired_volume_jwt(key, &expired, fid, &[previous]));
assert!(!is_expired_volume_jwt(key, &expired, fid, &[]));
guard.update_signing_keys(
SigningKey::from_string("write-new"),
10,
SigningKey::from_string("read-new"),
60,
SigningKey(vec![]),
SigningKey(vec![]),
);
assert!(!accepts(&guard, "write-old", true));
assert!(!accepts(&guard, "read-old", false));
}
#[test]
fn test_update_signing_keys_toggles_write_active() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(guard.check_jwt(None, true).is_ok());
guard.update_signing_keys(SigningKey::from_string("write"), 10, SigningKey(vec![]), 0);
guard.update_signing_keys(
SigningKey::from_string("write"),
10,
SigningKey(vec![]),
0,
SigningKey(vec![]),
SigningKey(vec![]),
);
assert!(guard.is_write_active);
guard.update_signing_keys(SigningKey(vec![]), 0, SigningKey(vec![]), 0);
guard.update_signing_keys(
SigningKey(vec![]),
0,
SigningKey(vec![]),
0,
SigningKey(vec![]),
SigningKey(vec![]),
);
assert!(!guard.is_write_active);
}
+15 -2
View File
@@ -110,6 +110,17 @@ pub fn load_outgoing_grpc_tls(
}))
}
#[cfg(test)]
impl OutgoingGrpcTlsConfig {
pub(crate) fn self_signed_for_test() -> Self {
Self {
cert_pem: tests::TEST_CERT_PEM.to_string(),
key_pem: tests::TEST_KEY_PEM.to_string(),
ca_pem: tests::TEST_CERT_PEM.to_string(),
}
}
}
pub fn grpc_endpoint_uri(grpc_host_port: &str, tls: Option<&OutgoingGrpcTlsConfig>) -> String {
let scheme = if tls.is_some() { "https" } else { "http" };
format!("{}://{}", scheme, grpc_host_port)
@@ -360,8 +371,8 @@ mod tests {
use std::sync::{Arc, Mutex};
use std::time::Duration;
const TEST_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBPDCB76ADAgECAhRuRPQgeAu43BT/M7EfAWSdapVdYDAFBgMrZXAwFDESMBAG\nA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNTE2MTUyOVoXDTM2MDcwMjE2MTUyOVow\nFDESMBAGA1UEAwwJbG9jYWxob3N0MCowBQYDK2VwAyEAr/3bNIFI+8V32oCiY6y+\nXRFmZpdNQ2g//VtRkT+nQg+jUzBRMB0GA1UdDgQWBBTsy9tLf1zPiXCQfgci6zNi\ndEzRSjAfBgNVHSMEGDAWgBTsy9tLf1zPiXCQfgci6zNidEzRSjAPBgNVHRMBAf8E\nBTADAQH/MAUGAytlcANBAIvsdw0IbvOBBkb9cd7BfMJfIP9pQQrAL03pCRWJFnFh\nSysaLVgFXI4T078IiaM874oO+iB+5vNbWEpc7CkGow4=\n-----END CERTIFICATE-----\n";
const TEST_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIHbyn71Kk+Y7KT3sBctit7uZpErpoH6qDbFj6P8qGaZH\n-----END PRIVATE KEY-----\n";
pub(super) const TEST_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBPDCB76ADAgECAhRuRPQgeAu43BT/M7EfAWSdapVdYDAFBgMrZXAwFDESMBAG\nA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNTE2MTUyOVoXDTM2MDcwMjE2MTUyOVow\nFDESMBAGA1UEAwwJbG9jYWxob3N0MCowBQYDK2VwAyEAr/3bNIFI+8V32oCiY6y+\nXRFmZpdNQ2g//VtRkT+nQg+jUzBRMB0GA1UdDgQWBBTsy9tLf1zPiXCQfgci6zNi\ndEzRSjAfBgNVHSMEGDAWgBTsy9tLf1zPiXCQfgci6zNidEzRSjAPBgNVHRMBAf8E\nBTADAQH/MAUGAytlcANBAIvsdw0IbvOBBkb9cd7BfMJfIP9pQQrAL03pCRWJFnFh\nSysaLVgFXI4T078IiaM874oO+iB+5vNbWEpc7CkGow4=\n-----END CERTIFICATE-----\n";
pub(super) const TEST_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIHbyn71Kk+Y7KT3sBctit7uZpErpoH6qDbFj6P8qGaZH\n-----END PRIVATE KEY-----\n";
#[test]
fn test_build_grpc_endpoint_with_tls_resolves_crypto_provider() {
@@ -425,6 +436,8 @@ mod tests {
ui_enabled: false,
jwt_signing_key: vec![],
jwt_signing_expires_seconds: 0,
jwt_previous_signing_key: vec![],
jwt_previous_read_signing_key: vec![],
jwt_read_signing_key: vec![],
jwt_read_signing_expires_seconds: 0,
https_cert_file: String::new(),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -1698,6 +1698,7 @@ mod tests {
security_file: String::new(),
cli_white_list: vec![],
state_file_path: String::new(),
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
+2
View File
@@ -156,6 +156,8 @@ mod tests {
ui_enabled: false,
jwt_signing_key: vec![],
jwt_signing_expires_seconds: 0,
jwt_previous_signing_key: vec![],
jwt_previous_read_signing_key: vec![],
jwt_read_signing_key: vec![],
jwt_read_signing_expires_seconds: 0,
https_cert_file: String::new(),
+347 -108
View File
@@ -158,7 +158,7 @@ pub async fn read_ec_shard_needle_or_miss(
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
// A complete reply merges into the cache; an incomplete one
// (< data_shards) is left unwritten — keep the prior cache.
// (< data_shards) only puts the holders it names first.
match write_back_shard_locations(
state,
vid,
@@ -167,8 +167,6 @@ pub async fn read_ec_shard_needle_or_miss(
snapshot.encode_ts_ns,
) {
Some(merged) => shard_locations = merged,
// An incomplete reply leaves the cache unwritten and its refresh
// time unadvanced, so the mark this refresh consumed goes back.
None => mark_shard_locations_stale(state, vid),
}
}
@@ -443,6 +441,95 @@ pub async fn delete_ec_shard_needle_distributed(
)))
}
/// A delete whose read found the needle deleted, best effort. A holder's read
/// checks one disk's deletion set, and a delete that failed part way can leave
/// its other disks live, so the delete goes to the primary shard holders whose
/// read answers deleted, which skip the disks already recording it. Normal
/// routing could stop at another copy instead; it is used only when no holder
/// answers deleted. `forwardEcDeleteOfDeletedNeedle` in Go.
pub async fn forward_ec_delete_of_deleted_needle(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) {
if let Err(e) = forward_ec_delete_to_holders_reading_deleted(state, vid, needle_id).await {
tracing::debug!(
"re-forward delete of deleted ec needle {}.{}: {}",
vid.0,
needle_id,
e
);
}
}
async fn forward_ec_delete_to_holders_reading_deleted(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) -> io::Result<()> {
let (probe, holders, collection, version) = {
let store = state.store.read().unwrap();
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} not mounted", vid.0),
)
})?;
let (_, _, intervals) = ecv.locate_needle(needle_id)?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("needle {} not in ec volume {}", needle_id, vid.0),
)
})?;
let (shard_id, shard_offset) = intervals
.first()
.map(|i| ecv.interval_to_shard_id_and_offset(i))
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no intervals for needle"))?;
let (locations, _) = ecv.shard_locations_snapshot();
(
EcInterval {
vid,
needle_id,
shard_id,
shard_offset,
size: 1,
expected_encode_ts_ns: ecv.encode_ts_ns,
},
locations.get(&shard_id).cloned().unwrap_or_default(),
ecv.collection.clone(),
ecv.version,
)
};
let target = EcDeleteTarget {
vid,
collection: &collection,
version,
needle_id,
};
let mut reported = false;
let mut last_err = None;
for addr in &holders {
if !matches!(
tokio::time::timeout(
EC_READ_HINT_TIMEOUT,
do_read_remote_ec_shard_interval(state, addr, probe),
)
.await,
Ok(Ok((_, true)))
) {
continue;
}
reported = true;
if let Err(e) = delete_on_remote_ec_shard(state, addr, &target).await {
last_err = Some(e);
}
}
if !reported {
return delete_ec_shard_needle_distributed(state, vid, needle_id).await;
}
last_err.map_or(Ok(()), Err)
}
/// `doDeleteNeedleFromRemoteEcShardServers` in Go. `Ok(false)` is the
/// shard-missing signal — no live holder anywhere — that triggers the
/// caller's fallback walk over the remaining shards.
@@ -461,12 +548,12 @@ async fn delete_on_ec_shard_holders(
let mut last_err = None;
if local_shards.contains(&shard_id) {
// A decode in its publishing tail must not miss this delete. The
// tail membership is verified again under the store write lock
// inside journal_delete_local — WouldBlock means the decode claimed
// it in the gap after this wait — so wait and retry.
// tail membership is verified again under the journal lock inside
// journal_delete_local — WouldBlock means the decode claimed it in
// the gap after this wait — so wait and retry.
loop {
crate::server::grpc_server::wait_ec_decode_tail(state, target.vid).await;
match journal_delete_local(state, target.vid, target.needle_id) {
match journal_delete_local(state, target.vid, target.needle_id).await {
Ok(()) => return Ok(true),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
// Nothing was committed — the volume unmounted or remounted
@@ -533,38 +620,52 @@ async fn delete_on_remote_ec_shard(
/// no-op: `journal_delete` would accept it silently, but here it means the
/// volume remounted as a different generation mid-delete and the tombstone
/// should go to a replica that still has the needle.
fn journal_delete_local(
pub(crate) async fn journal_delete_local(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) -> io::Result<()> {
let mut store = state.store.write().unwrap();
// Membership is read under the write lock: a decode can claim the
// publishing tail while this call waited for the decoder's read lock,
// so a check taken earlier would be stale by commit time.
if crate::server::grpc_server::ec_decode_tail_contains(state, vid) {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
format!("ec volume {} is in decode publishing tail", vid.0),
));
}
let ecv = store.find_ec_volume_mut(vid).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} unmounted", vid.0),
)
})?;
match ecv.find_needle_from_ecx(needle_id)? {
None => {
// Every local runtime records the delete, the first last, as in the
// VolumeEcBlobDelete handler.
let appenders = {
let store = state.store.read().unwrap();
let ec_vols = store.find_all_ec_volumes(vid);
if ec_vols.is_empty() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("needle {} not in local ecx", needle_id),
format!("ec volume {} unmounted", vid.0),
));
}
Some((_, size)) if size.is_deleted() => return Ok(()),
Some(_) => {}
}
ecv.journal_delete(needle_id)
let mut appenders = Vec::new();
for (i, ecv) in ec_vols.into_iter().enumerate() {
match ecv.find_needle_from_ecx(needle_id)? {
None if i > 0 => continue,
None => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("needle {} not in local ecx", needle_id),
));
}
Some((_, size)) if size.is_deleted() => continue,
Some(_) => {}
}
appenders.push(ecv.journal_appender());
}
appenders
};
// Membership is read under the journal lock: a decode claims the
// publishing tail before it takes that lock for its catch-up, so a check
// taken earlier would be stale by commit time.
let state = state.clone();
tokio::task::spawn_blocking(move || {
appenders.iter().rev().try_for_each(|appender| {
appender.journal_delete(needle_id, || {
crate::server::grpc_server::ec_decode_tail_contains(&state, vid)
})
})
})
.await
.map_err(io::Error::other)?
}
fn local_shard_ids(ecv: &crate::storage::erasure_coding::EcVolume) -> HashSet<ShardId> {
@@ -710,8 +811,10 @@ pub async fn scrub_ec_volume_distributed(
) {
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
let partial = located_shard_count(&fresh) < data_shards;
if write_back_shard_locations(state, vid, fresh, data_shards, expected_encode_ts_ns)
.is_none()
|| partial
{
mark_shard_locations_stale(state, vid);
return (
@@ -1228,35 +1331,44 @@ async fn cached_lookup_ec_shard_locations(
.lookup_ec_volume(Request::new(LookupEcVolumeRequest { volume_id: vid.0 }))
.await
.map_err(|e| io::Error::other(format!("lookup_ec_volume: {}", e)))?;
let resp = resp.into_inner();
Ok(shard_locations_from_reply(resp.into_inner()))
}
/// The shard slots of a `LookupEcVolume` reply. The master answers every slot
/// it tracks, so a shard whose holders are all down comes back with no
/// addresses: it does not count toward the reply's completeness, and a complete
/// reply drops it from the cache, as Go's `cachedLookupEcShardLocations` does.
fn shard_locations_from_reply(
resp: master_pb::LookupEcVolumeResponse,
) -> HashMap<ShardId, Vec<String>> {
let mut out = HashMap::new();
for entry in resp.shard_id_locations {
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
continue;
};
let addrs: Vec<String> = entry
.locations
.iter()
.map(format_location_as_server_address)
.collect();
// Defensive: skip out-of-range shard ids from the master instead of
// truncating (256 would alias 0). Valid replies are unaffected.
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
continue;
};
out.insert(sid, addrs);
}
Ok(out)
out
}
fn located_shard_count(locations: &HashMap<ShardId, Vec<String>>) -> usize {
locations.values().filter(|addrs| !addrs.is_empty()).count()
}
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
/// cache. Returns the merged map on success, or `None` when the reply is
/// incomplete (and was therefore NOT written) or the volume is gone.
/// cache. Returns the resulting map, or `None` when the volume is gone.
///
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
/// partial, not ground truth — Go aborts the lookup with a retryable error and
/// leaves the cache + refresh time untouched. Returning `None` without writing
/// does the same, so a previously-complete cache is never clobbered with a
/// partial map. On a complete reply the write is a per-shard MERGE (see
/// partial, not ground truth. It only puts the holders it names ahead of the
/// cached ones, and leaves the refresh time unadvanced with the map marked
/// stale, so a previously-complete cache is never clobbered with a partial map.
/// On a complete reply the write is a per-shard MERGE (see
/// `merge_shard_locations`), not a full replace.
fn write_back_shard_locations(
state: &Arc<VolumeServerState>,
@@ -1265,11 +1377,11 @@ fn write_back_shard_locations(
data_shards: usize,
expected_encode_ts_ns: i64,
) -> Option<HashMap<ShardId, Vec<String>>> {
if locations.len() < data_shards {
return None;
}
let store = state.store.read().unwrap();
let ecv = find_ec_volume_for_scrub(&store, vid, expected_encode_ts_ns)?;
if located_shard_count(&locations) < data_shards {
return Some(ecv.merge_partial_shard_locations(locations));
}
Some(ecv.merge_shard_locations(locations))
}
@@ -1332,6 +1444,11 @@ struct EcShardMap<'a> {
parity_shards: usize,
}
/// Bounds a one-byte probe of a holder that may have stopped answering: a
/// delisted holder before the read reconstructs the shard, or a holder a
/// delete retry asks (Go's `ecReadHintTimeout`).
const EC_READ_HINT_TIMEOUT: Duration = Duration::from_secs(5);
/// Try direct peer read; on failure, reconstruct via Reed-Solomon
/// from the other shards. Mirrors `readOneEcShardInterval`'s tail.
async fn fetch_one_interval(
@@ -1340,6 +1457,12 @@ async fn fetch_one_interval(
map: EcShardMap<'_>,
) -> io::Result<(Vec<u8>, bool)> {
let EcInterval { vid, shard_id, .. } = iv;
if map.locations.get(&shard_id).is_none_or(Vec::is_empty)
&& let Some((hints, revision)) = shard_read_hints(state, vid, shard_id)
&& ask_ec_shard_read_hints(state, iv, &hints, revision).await
{
return Ok((Vec::new(), true));
}
// Direct peer read against the cached locations for this shard.
if let Some(sources) = map.locations.get(&shard_id)
&& !sources.is_empty()
@@ -1517,7 +1640,8 @@ async fn do_read_remote_ec_shard_interval(
}
/// Reads one `VolumeEcShardRead` reply into the interval's bytes, or the
/// holder's deleted answer, which stands even if the stream fails after it.
/// holder's deleted answer, taken as soon as it arrives so a stream that fails
/// or stalls after it cannot lose it.
async fn collect_ec_shard_read(
mut stream: tonic::Streaming<VolumeEcShardReadResponse>,
source: &str,
@@ -1531,12 +1655,11 @@ async fn collect_ec_shard_read(
..
} = iv;
let mut out = Vec::with_capacity(size);
let mut is_deleted = false;
// A deleted answer stands even if the stream fails after it.
while let Some(msg) = match stream.message().await {
Err(_) if is_deleted => None,
msg => msg.map_err(|e| io::Error::other(format!("recv: {}", e)))?,
} {
while let Some(msg) = stream
.message()
.await
.map_err(|e| io::Error::other(format!("recv: {}", e)))?
{
// Validate the served shard's identity client-side, so the guard holds even
// against a pre-upgrade server that ignored the request field (returns 0).
// A mismatch fails the read; the caller recovers from parity.
@@ -1546,23 +1669,20 @@ async fn collect_ec_shard_read(
vid.0, shard_id, source, expected_encode_ts_ns, msg.encode_ts_ns
)));
}
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
// at read time and answers is_deleted with no payload. Signal the deletion to
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
// into Reed-Solomon. Exempt from the short-read guard below.
if msg.is_deleted {
is_deleted = true;
return Ok((Vec::new(), true));
}
if !msg.data.is_empty() {
out.extend_from_slice(&msg.data);
}
}
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
// at read time and answers is_deleted with no payload. Signal the deletion to
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
// into Reed-Solomon. Exempt from the short-read guard below.
if is_deleted {
return Ok((Vec::new(), true));
}
if out.len() < size {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
@@ -1824,6 +1944,62 @@ async fn recover_one_remote_ec_shard_interval(
}
}
/// Reports whether a delisted holder of the shard journaled the needle's
/// delete (Go's `askEcShardReadHints`). Each holder is asked, since any one of
/// them may hold the delete; only a deleted answer is taken, so one byte is
/// enough. Holders that failed are forgotten, even when a later one answers
/// deleted, unless a lookup changed the hints meanwhile.
async fn ask_ec_shard_read_hints(
state: &Arc<VolumeServerState>,
iv: EcInterval,
hints: &[String],
revision: u64,
) -> bool {
let probe = EcInterval { size: 1, ..iv };
let mut failed = Vec::new();
let mut deleted = false;
for hint in hints {
let err = match tokio::time::timeout(
EC_READ_HINT_TIMEOUT,
do_read_remote_ec_shard_interval(state, hint, probe),
)
.await
{
Ok(Ok((_, true))) => {
deleted = true;
break;
}
Ok(Ok(_)) => continue,
Ok(Err(e)) => e.to_string(),
Err(_) => "timed out".to_string(),
};
tracing::debug!(
"read ec shard {}.{} from delisted holder {} failed: {}",
iv.vid.0,
iv.shard_id,
hint,
err
);
failed.push(hint.clone());
}
if !failed.is_empty() {
let store = state.store.read().unwrap();
if let Some(ecv) = store.find_ec_volume(iv.vid) {
ecv.forget_shard_read_hints(iv.shard_id, revision, &failed);
}
}
deleted
}
fn shard_read_hints(
state: &Arc<VolumeServerState>,
vid: VolumeId,
shard_id: ShardId,
) -> Option<(Vec<String>, u64)> {
let store = state.store.read().unwrap();
store.find_ec_volume(vid)?.shard_read_hints(shard_id)
}
/// Drop a confirmed-corrupt shard's cached location so later reads go straight
/// to reconstruction — Go's `forgetShardId` reached through the volume.
fn forget_shard_location(state: &Arc<VolumeServerState>, vid: VolumeId, shard_id: ShardId) {
@@ -2384,23 +2560,45 @@ pub(crate) async fn recover_missing_ec_indexes(
"cannot look up peers to recover missing .ecx: {}",
e
);
continue;
Vec::new()
}
};
if peers.is_empty() {
tracing::warn!(
volume_id = m.vid.0,
"shards present locally but .ecx missing and no peer holds it; leaving shards unloaded"
);
continue;
// Under the volume's lifecycle lock, so an in-flight VolumeEcShardsCopy
// of it, which may unlink the shards it renamed in, never has them
// mounted from under it.
let _lifecycle = state.ec_lifecycle_lock(m.vid).lock_owned().await;
let current = state
.store
.read()
.unwrap()
.collect_ec_volumes_missing_index_only(Some(m.vid))
.into_iter()
.find(|x| x.vid == m.vid && x.collection == m.collection);
// A copy holding the lock may have installed the index meanwhile: skip
// the fetch, but its shards still need the mount.
if let Some(current) = &current {
if peers.is_empty() {
tracing::warn!(
volume_id = m.vid.0,
"shards present locally but .ecx missing and no peer holds it; leaving shards unloaded"
);
continue;
}
if !fetch_ec_index_from_peers(state, current, &peers).await {
continue;
}
}
if fetch_ec_index_from_peers(state, m, &peers).await {
state
.store
.write()
.unwrap()
.mount_recovered_ec_shards_only(Some(m.vid));
if current.is_some() {
recovered += 1;
}
}
if recovered > 0 {
state.store.write().unwrap().mount_recovered_ec_shards();
tracing::info!(
"recovered missing EC index for {} volume(s) from peers and mounted their shards",
recovered
@@ -2756,6 +2954,38 @@ mod tests {
assert!(search(&shards, &metas, &n, dat_offset).is_none());
}
// The master answers all 32 shard slots, located or not. While 7 of a 10+4
// volume's shards have a holder up, the reply must count as 7 shards, short
// of the data shards.
#[test]
fn a_lookup_reply_counts_only_located_shards() {
use master_pb::lookup_ec_volume_response::EcShardIdLocation;
let located = [0u32, 3, 4, 6, 7, 9, 12];
let reply = master_pb::LookupEcVolumeResponse {
volume_id: 136,
shard_id_locations: (0..32u32)
.map(|sid| EcShardIdLocation {
shard_id: sid,
locations: if located.contains(&sid) {
vec![master_pb::Location {
url: "10.0.0.5:8180".to_string(),
grpc_port: 18180,
..Default::default()
}]
} else {
Vec::new()
},
..Default::default()
})
.collect(),
};
let got = shard_locations_from_reply(reply);
assert_eq!(got.len(), 32);
assert_eq!(located_shard_count(&got), 7);
assert!(got[&1].is_empty());
assert_eq!(got[&3], vec!["10.0.0.5:8180.18180".to_string()]);
}
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
(0..count)
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
@@ -2782,9 +3012,10 @@ mod tests {
assert!(needs_refresh(&locations(0), None, false, 10, 14));
}
struct FailAfterFrame(Option<bytes::Bytes>);
/// Serves one frame, then fails the stream or, with `stall`, never ends it.
struct AfterFrame(Option<bytes::Bytes>, bool);
impl http_body::Body for FailAfterFrame {
impl http_body::Body for AfterFrame {
type Data = bytes::Bytes;
type Error = tonic::Status;
@@ -2793,46 +3024,54 @@ mod tests {
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>>
{
std::task::Poll::Ready(Some(match self.0.take() {
Some(frame) => Ok(http_body::Frame::data(frame)),
None => Err(tonic::Status::unavailable(
match self.0.take() {
Some(frame) => std::task::Poll::Ready(Some(Ok(http_body::Frame::data(frame)))),
None if self.1 => std::task::Poll::Pending,
None => std::task::Poll::Ready(Some(Err(tonic::Status::unavailable(
"stream failed after the deleted answer",
)),
}))
)))),
}
}
}
/// A holder's deleted answer stands even when its stream fails afterwards,
/// so a later source or the quarantined shard cannot answer for the needle.
/// A holder's deleted answer stands even when its stream fails or stalls
/// afterwards, so a later source or the quarantined shard cannot answer for
/// the needle.
#[tokio::test]
async fn test_collect_ec_shard_read_keeps_deletion_when_the_stream_fails() {
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
is_deleted: true,
..Default::default()
});
let mut frame = vec![0u8];
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
frame.extend_from_slice(&message);
let stream = tonic::Streaming::new_response(
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
FailAfterFrame(Some(frame.into())),
tonic::codegen::http::StatusCode::OK,
None,
None,
);
let iv = EcInterval {
vid: VolumeId(7),
needle_id: NeedleId(42),
shard_id: 0,
shard_offset: 0,
size: 64,
expected_encode_ts_ns: 0,
};
for stall in [false, true] {
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
is_deleted: true,
..Default::default()
});
let mut frame = vec![0u8];
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
frame.extend_from_slice(&message);
let stream = tonic::Streaming::new_response(
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
AfterFrame(Some(frame.into()), stall),
tonic::codegen::http::StatusCode::OK,
None,
None,
);
let iv = EcInterval {
vid: VolumeId(7),
needle_id: NeedleId(42),
shard_id: 0,
shard_offset: 0,
size: 64,
expected_encode_ts_ns: 0,
};
let (buf, is_deleted) = collect_ec_shard_read(stream, "peer:18080", iv)
let (buf, is_deleted) = tokio::time::timeout(
Duration::from_secs(5),
collect_ec_shard_read(stream, "peer:18080", iv),
)
.await
.expect("the deleted answer waited for the stream to end")
.unwrap();
assert!(is_deleted);
assert!(buf.is_empty());
assert!(is_deleted, "stall={stall}");
assert!(buf.is_empty());
}
}
}
@@ -125,6 +125,11 @@ pub struct VolumeServerState {
pub cli_white_list: Vec<String>,
/// Path to state.pb file for persisting VolumeServerState across restarts.
pub state_file_path: String,
/// Per-vid EC lifecycle lock, serializing EC ops that install or remove a
/// vid's files. A tokio Mutex so the guard survives the copy's `.await` IO.
pub ec_lifecycle_locks: std::sync::Mutex<
std::collections::HashMap<crate::storage::types::VolumeId, Arc<tokio::sync::Mutex<()>>>,
>,
/// Volumes with an EC decode in flight. A dropped request leaves the
/// blocking job running; this keeps a retry from racing it on the
/// same volume files.
@@ -151,6 +156,20 @@ pub struct VolumeServerState {
}
impl VolumeServerState {
/// Return the per-vid EC lifecycle lock, creating it on first use. Entries
/// are never reaped.
pub fn ec_lifecycle_lock(
&self,
vid: crate::storage::types::VolumeId,
) -> Arc<tokio::sync::Mutex<()>> {
self.ec_lifecycle_locks
.lock()
.unwrap()
.entry(vid)
.or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
.clone()
}
/// The master lookups should go to: the leader the heartbeat confirmed,
/// or empty while none is known, in its announced `host:port[.grpcPort]`
/// form. Mirrors Go's `vs.getCurrentMaster()`.
+1
View File
@@ -467,6 +467,7 @@ mod tests {
security_file: String::new(),
cli_white_list: vec![],
state_file_path: String::new(),
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
+57 -4
View File
@@ -58,6 +58,8 @@ pub struct DiskLocation {
/// skips a claimed vid outright and claims any other through its load,
/// so a VolumeCopy's .note sweep cannot unlink files it still writes.
pub(crate) load_guard: Option<Arc<Mutex<HashSet<VolumeId>>>>,
/// The data directory of every disk on this server.
pub(crate) store_dirs: Vec<String>,
}
/// Keeps `vid` in the copy-claim set through one scan load so a VolumeCopy
@@ -123,6 +125,7 @@ impl DiskLocation {
disk_free_bytes: AtomicU64::new(0),
min_free_space,
load_guard: None,
store_dirs: Vec::new(),
})
}
@@ -486,8 +489,20 @@ impl DiskLocation {
// Custom ratio comes from the volume's own .vif; the server holds no
// cluster EC config in memory.
let data_shards =
ec_data_shards_from_vif(&self.directory, &self.idx_directory, collection, vid);
let data_shards = ec_data_shards_from_vif(
&self.directory,
&self.idx_directory,
&self.store_dirs,
collection,
vid,
);
if data_shards == 0 {
warn!(
volume_id = vid.0,
"sibling .vif files disagree on the encode; keeping EC shards"
);
return true;
}
// On-disk .dat: an empty <= superblock one is a stub; a transient stat
// error keeps the shards rather than deleting.
@@ -814,6 +829,24 @@ impl DiskLocation {
self.volumes.len()
}
/// Number of local volumes of `collection` that still take writes: not
/// read-only and, when `volume_size_limit` is known (non zero), with a .dat
/// below it. The .dat size is what the master compares with the limit to
/// stop writes. Mirrors Go's WritableCollectionVolumesLen.
pub fn writable_collection_volumes_len(
&self,
collection: &str,
volume_size_limit: u64,
) -> usize {
self.volumes
.values()
.filter(|v| v.collection == collection && !v.has_remote_file() && !v.is_read_only())
.filter(|v| {
volume_size_limit == 0 || v.dat_file_size().unwrap_or(0) < volume_size_limit
})
.count()
}
/// Get all volume IDs, sorted.
pub fn volume_ids(&self) -> Vec<VolumeId> {
let mut ids: Vec<VolumeId> = self.volumes.keys().copied().collect();
@@ -1020,7 +1053,9 @@ impl DiskLocation {
// propagate the error to the caller.
let created = !self.ec_volumes.contains_key(&vid);
if created {
let ec_vol = EcVolume::new(&dir, idx_dir, collection, vid).map_err(VolumeError::Io)?;
let ec_vol =
EcVolume::new_with_vif_dirs(&dir, idx_dir, &self.store_dirs, collection, vid)
.map_err(VolumeError::Io)?;
self.ec_volumes.insert(vid, ec_vol);
}
let ec_vol = self.ec_volumes.get_mut(&vid).expect("just inserted above");
@@ -1441,6 +1476,7 @@ fn rm_if_present(path: String) -> io::Result<()> {
fn ec_data_shards_from_vif(
directory: &str,
idx_directory: &str,
store_dirs: &[String],
collection: &str,
vid: VolumeId,
) -> usize {
@@ -1459,6 +1495,23 @@ fn ec_data_shards_from_vif(
break;
}
}
match crate::storage::erasure_coding::ec_volume::sibling_ec_config_vif(
directory,
idx_directory,
store_dirs,
collection,
vid,
) {
Err(()) => return 0,
Ok(Some(vi)) => {
if let Some(ds) = vi.ec_shard_config.map(|c| c.data_shards as usize)
&& ds > 0
{
return ds;
}
}
Ok(None) => {}
}
DATA_SHARDS_COUNT
}
@@ -1542,7 +1595,7 @@ pub(crate) fn vif_references_remote_file(vif_path: &str) -> bool {
/// True when a `.vif` records an EC shard config, i.e. the volume was
/// erasure-coded. Such a volume keeps no local `.dat`, so an empty `.dat`
/// alongside it is a leftover stub safe to remove.
fn vif_is_ec_volume(vif_path: &str) -> bool {
pub(crate) fn vif_is_ec_volume(vif_path: &str) -> bool {
fs::read_to_string(vif_path)
.ok()
.and_then(|s| serde_json::from_str::<VifVolumeInfo>(&s).ok())
File diff suppressed because it is too large. Load diff
@@ -32,7 +32,7 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Condvar, LazyLock, Mutex, MutexGuard};
use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard};
#[derive(Default)]
struct PathState {
@@ -42,6 +42,10 @@ struct PathState {
/// Writers that have started on the path. Lives as long as the entry,
/// which a registered holder keeps.
write_gen: u64,
/// Serializes appends through every holder's handle with anything that
/// reads or replaces the file under a holder, as one disk's journal lock
/// covers only its own handle.
append_lock: Arc<Mutex<()>>,
}
impl PathState {
@@ -69,7 +73,7 @@ fn lock() -> MutexGuard<'static, HashMap<PathBuf, PathState>> {
/// Canonical key for `path`: its resolved parent directory joined with the
/// file name. The file itself may not exist yet (a copy creates it), so only
/// the directory is resolved.
fn key_for(path: &str) -> PathBuf {
pub(crate) fn key_for(path: &str) -> PathBuf {
let p = Path::new(path);
let (Some(parent), Some(name)) = (p.parent(), p.file_name()) else {
return std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
@@ -118,6 +122,7 @@ pub(crate) struct EcjHold {
/// so they cover every write the load might have missed.
write_gen: u64,
writer_at_start: bool,
append_lock: Arc<Mutex<()>>,
}
impl EcjHold {
@@ -125,17 +130,23 @@ impl EcjHold {
/// progress so the handle opened afterwards is on the final inode.
pub(crate) fn acquire(ecj_path: &str) -> Self {
let key = key_for(ecj_path);
let (write_gen, writer_at_start) = update_when_not_compacting(&key, |s| {
let (write_gen, writer_at_start, append_lock) = update_when_not_compacting(&key, |s| {
s.holders += 1;
(s.write_gen, s.writers > 0)
(s.write_gen, s.writers > 0, s.append_lock.clone())
});
EcjHold {
key,
write_gen,
writer_at_start,
append_lock,
}
}
/// The path's append lock, shared by every holder of the path.
pub(crate) fn append_lock(&self) -> Arc<Mutex<()>> {
self.append_lock.clone()
}
/// Reserve the path for a compaction, or `None` when another holder or an
/// active writer could still reach the current inode, or when a writer
/// has run on the path since the hold was taken, so the journal may no
+370 -49
View File
@@ -13,7 +13,6 @@ use std::io::{self, Read, Seek, Write};
use std::path::Path;
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
#[cfg(feature = "redb-experimental-cursor")]
use std::ops::Bound;
mod compact_map;
@@ -485,6 +484,38 @@ const NEEDLE_TABLE: TableDefinition<u64, &[u8]> = TableDefinition::new("needles"
const META_TABLE: TableDefinition<&str, u64> = TableDefinition::new("meta");
const META_IDX_SIZE: &str = "idx_size";
/// redb 4.6 starts a new file at 72 KiB: 64 KiB of pages plus the header
/// and the region tracker.
const REDB_SMALL_FILE_BYTES: u64 = 72 * 1024;
/// redb 4.2 started at 1 MiB of pages plus that same 8 KiB.
const REDB_OLD_FLOOR_BYTES: u64 = 1024 * 1024 + 8 * 1024;
/// Meta value `1` means a compact of a file in the old-floor band already finished.
const META_FLOOR_COMPACT: &str = "floor_compact";
/// True when a reused `.rdb` is still inside the old 4.2 starting size.
/// A file one byte past it has grown.
fn should_compact_old_floor(len: u64) -> bool {
len > REDB_SMALL_FILE_BYTES && len <= REDB_OLD_FLOOR_BYTES
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CompactFollowUp {
/// Drop the `Database` and open the same path once. Do not compact again.
ReopenSkipCompact,
/// The handle can still begin a write. Do not record `floor_compact`.
KeepHandle,
}
fn compact_follow_up(err: &redb::CompactionError) -> CompactFollowUp {
match err {
redb::CompactionError::Storage(_) => CompactFollowUp::ReopenSkipCompact,
redb::CompactionError::TransactionInProgress
| redb::CompactionError::PersistentSavepointExists
| redb::CompactionError::EphemeralSavepointExists => CompactFollowUp::KeepHandle,
_ => CompactFollowUp::KeepHandle,
}
}
/// Writes between two durable redb checkpoints. Every non-durable commit
/// leaves an entry in redb's transaction tracker and pins the pages that
/// were on disk at the last durable commit; only a durable commit clears
@@ -648,9 +679,6 @@ impl RedbNeedleMap {
let meta = txn
.open_table(META_TABLE)
.map_err(|e| io::Error::other(format!("redb open meta: {}", e)))?;
// experimental-api-5 drops inherent ReadOnlyTable::get ('static guard).
// ReadableTable::get guard borrows `meta`; edition 2024 drops the tail
// expression's temporaries before `meta`, so no extra binding is needed.
match meta.get(META_IDX_SIZE) {
Ok(Some(guard)) => Ok(Some(guard.value())),
Ok(None) => Ok(None),
@@ -658,6 +686,118 @@ impl RedbNeedleMap {
}
}
fn rdb_file_len(&self) -> io::Result<u64> {
Ok(std::fs::metadata(&self.rdb_path)?.len())
}
fn read_floor_compact(&self) -> io::Result<Option<u64>> {
let txn = self
.db_or_err()?
.begin_read()
.map_err(|e| io::Error::other(format!("redb begin_read: {}", e)))?;
let meta = txn
.open_table(META_TABLE)
.map_err(|e| io::Error::other(format!("redb open meta: {}", e)))?;
match meta.get(META_FLOOR_COMPACT) {
Ok(Some(guard)) => Ok(Some(guard.value())),
Ok(None) => Ok(None),
Err(e) => Err(io::Error::other(format!("redb get meta: {}", e))),
}
}
fn save_floor_compact(&self) -> io::Result<()> {
let txn = Self::begin_write_no_fsync(self.db_or_err()?)?;
{
let mut meta = txn
.open_table(META_TABLE)
.map_err(|e| io::Error::other(format!("redb open meta: {}", e)))?;
meta.insert(META_FLOOR_COMPACT, 1u64)
.map_err(|e| io::Error::other(format!("redb insert meta: {}", e)))?;
}
txn.commit()
.map_err(|e| io::Error::other(format!("redb commit meta: {}", e)))?;
Ok(())
}
/// Drop the exclusive lock and open the same file. Does not compact.
fn reopen_database(&mut self) -> io::Result<()> {
self.db.take();
let db = Database::builder()
.set_cache_size(self.cache_bytes)
.open(&self.rdb_path)
.map_err(|e| io::Error::other(format!("redb reopen after compact: {}", e)))?;
self.db = Some(db);
Ok(())
}
fn record_floor_compact_if_still_in_band(&self) -> io::Result<()> {
let len = match self.rdb_file_len() {
Ok(len) => len,
Err(e) => {
tracing::warn!("redb floor compact flag skipped, metadata failed: {}", e);
return Ok(());
}
};
if should_compact_old_floor(len) {
self.save_floor_compact()?;
}
Ok(())
}
/// Compact a reused file that is still the 4.2 starting allocation.
///
/// Called only from `try_reuse_rdb`, after the replay transaction has
/// committed. `new` and `full_rebuild` already create a 72 KiB file.
///
/// An empty durable commit publishes a `Durability::None` tail before
/// `compact`. A storage error inside `compact` would otherwise drop that
/// tail when the handle is reopened. `checkpoint` is not used: during
/// reuse `idx_file` is `None` and `idx_file_offset` is 0.
fn shrink_old_floor(&mut self) -> io::Result<()> {
let len = match self.rdb_file_len() {
Ok(len) => len,
Err(e) => {
tracing::warn!("redb floor compact skipped, metadata failed: {}", e);
return Ok(());
}
};
// The flag is irrelevant outside the band. A meta read error there
// must not make `load_from_idx` rebuild a larger index.
if !should_compact_old_floor(len) {
return Ok(());
}
if self.read_floor_compact()? == Some(1) {
return Ok(());
}
// Failure returns Err so `load_from_idx` full-rebuilds. Do not reopen
// over a tail that this commit did not publish.
let mut txn = self
.db_or_err()?
.begin_write()
.map_err(|e| io::Error::other(format!("redb begin_write: {}", e)))?;
txn.set_quick_repair(true);
txn.commit()
.map_err(|e| io::Error::other(format!("redb commit: {}", e)))?;
let compact_result = self
.db
.as_mut()
.ok_or_else(|| io::Error::other("redb database is closed"))?
.compact();
match compact_result {
Ok(_) => self.record_floor_compact_if_still_in_band(),
Err(e) => match compact_follow_up(&e) {
CompactFollowUp::ReopenSkipCompact => {
tracing::warn!("redb floor compact storage error, reopening: {}", e);
self.reopen_database()
}
CompactFollowUp::KeepHandle => {
tracing::warn!("redb floor compact skipped: {}", e);
Ok(())
}
},
}
}
/// Test-only read of META `idx_size` through the live handle. See
/// [`test_support::live_meta_idx_size`] for why durability tests use
/// this instead of copying the open `.rdb`.
@@ -666,6 +806,11 @@ impl RedbNeedleMap {
self.read_idx_size_meta().unwrap()
}
#[cfg(test)]
fn live_floor_compact(&self) -> Option<u64> {
self.read_floor_compact().unwrap()
}
/// Load from an .idx file, reusing an existing .rdb if it is consistent.
///
/// Strategy:
@@ -774,6 +919,7 @@ impl RedbNeedleMap {
nm.save_idx_size_meta(idx_size)?;
}
nm.shrink_old_floor()?;
Ok(nm)
}
@@ -796,8 +942,8 @@ impl RedbNeedleMap {
/// `Database::create` opens an existing file (`truncate(false)`). Unlink
/// is best-effort: if it fails (sticky bit, foreign owner) but the path is
/// still writable, clear the leftover needles table before inserting.
/// Live keys come from a `BTreeMap` so inserts are in needle-id order and
/// redb 4.2.0 packs leaves, without a second Vec + sort scratch.
/// Live keys come from a `BTreeMap` so `insert_before` walks them in
/// needle-id order and packs leaves, without a second Vec + sort scratch.
fn full_rebuild<R: Read + Seek>(
db_path: &str,
reader: &mut R,
@@ -849,43 +995,26 @@ impl RedbNeedleMap {
.map_err(|e| io::Error::other(format!("redb retain: {}", e)))?;
}
#[cfg(not(feature = "redb-experimental-cursor"))]
{
for (key, nv) in &entries {
let key_u64: u64 = (*key).into();
let packed = pack_needle_value(nv);
table
.insert(key_u64, packed.as_slice())
.map_err(|e| io::Error::other(format!("redb insert: {}", e)))?;
}
}
#[cfg(feature = "redb-experimental-cursor")]
{
let mut cursor =
table
.upper_bound_mut(Bound::<u64>::Unbounded)
.map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("redb upper_bound_mut: {}", e),
)
})?;
for (key, nv) in &entries {
let key_u64: u64 = (*key).into();
let packed = pack_needle_value(nv);
cursor
.insert_before(key_u64, packed.as_slice())
.map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("redb insert_before: {}", e),
)
})?;
}
cursor.close().map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("redb cursor close: {}", e))
let mut cursor = table
.upper_bound_mut(Bound::<u64>::Unbounded)
.map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("redb upper_bound_mut: {}", e))
})?;
for (key, nv) in &entries {
let key_u64: u64 = (*key).into();
let packed = pack_needle_value(nv);
cursor
.insert_before(key_u64, packed.as_slice())
.map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("redb insert_before: {}", e),
)
})?;
}
cursor.close().map_err(|e| {
io::Error::new(io::ErrorKind::Other, format!("redb cursor close: {}", e))
})?;
}
txn.commit()
.map_err(|e| io::Error::other(format!("redb commit: {}", e)))?;
@@ -1048,9 +1177,6 @@ impl RedbNeedleMap {
let table = txn
.open_table(NEEDLE_TABLE)
.map_err(|e| io::Error::other(format!("redb open_table: {}", e)))?;
// experimental-api-5 drops inherent ReadOnlyTable::get ('static guard).
// ReadableTable::get guard borrows `table`; edition 2024 drops the tail
// expression's temporaries before `table`, so no extra binding is needed.
match table.get(key_u64) {
Ok(Some(guard)) => Ok(packed_to_needle_value(guard.value())),
Ok(None) => Ok(None),
@@ -1181,7 +1307,7 @@ impl RedbNeedleMap {
/// Reopen the database from `.idx` after a non-`TransactionPoisoned`
/// commit error.
///
/// redb 4.2.0 can make a `Durability::None` commit visible *before*
/// redb can make a `Durability::None` commit visible *before*
/// returning `Err(CommitError::Storage(..))`. In that state the database
/// refuses further write transactions, so the map cannot be used as-is.
/// The `.idx` row that triggered the commit is **not** truncated — the
@@ -1603,9 +1729,10 @@ pub(crate) mod test_support {
/// every `put`/`delete` also commits non-durably, so before the first
/// checkpoint this is the load-time value (`Some(0)` for a fresh map) —
/// NOT the crash-durable `None` a copy of the open `.rdb` would show.
/// A live read is the only portable observation: redb 4.2.0 takes an
/// exclusive whole-file lock, which is advisory on Unix but mandatory
/// on Windows, so copying the open `.rdb` fails there with OS error 33.
/// A live read is the only portable observation: redb's default
/// `ExclusiveWriter` takes an exclusive whole-file lock, which is
/// advisory on Unix but mandatory on Windows, so copying the open
/// `.rdb` fails there with OS error 33.
///
/// It still pins the property under test: the only *durable* META
/// writer is `checkpoint`, so any value other than the load-time one
@@ -1763,6 +1890,41 @@ mod tests {
NeedleMapKind::Redb.redb_cache_bytes()
}
#[test]
fn test_redb_new_file_is_at_most_72kib() {
let dir = tempfile::tempdir().unwrap();
let db_path = dir.path().join("fresh.rdb");
let nm = RedbNeedleMap::new(db_path.to_str().unwrap(), redb_test_cache()).unwrap();
let len = std::fs::metadata(&db_path).unwrap().len();
assert!(
len <= REDB_SMALL_FILE_BYTES,
"fresh redb file is {len} bytes, above the 72 KiB start"
);
drop(nm);
}
#[test]
fn test_should_compact_old_floor_bounds() {
let small = REDB_SMALL_FILE_BYTES;
let floor = REDB_OLD_FLOOR_BYTES;
assert!(!should_compact_old_floor(small));
assert!(should_compact_old_floor(small + 1));
assert!(should_compact_old_floor(floor));
assert!(!should_compact_old_floor(floor + 1));
assert!(!should_compact_old_floor(0));
}
fn reload_redb(db_path: &std::path::Path, idx_path: &std::path::Path) -> RedbNeedleMap {
let mut idx = std::fs::File::open(idx_path).unwrap();
RedbNeedleMap::load_from_idx(
db_path.to_str().unwrap(),
&mut idx,
Version::current(),
redb_test_cache(),
)
.unwrap()
}
/// Open a redb map on an empty .idx with an append writer attached, the
/// way `Volume::load_index_redb` opens a writable volume.
fn open_writable_redb(
@@ -1895,7 +2057,6 @@ mod tests {
);
}
#[cfg(feature = "redb-experimental-cursor")]
#[test]
fn test_redb_full_rebuild_insert_before_reads_back_thousands_of_shuffled_keys() {
// Enough keys to split leaves. insert_before vs table.insert only
@@ -2474,4 +2635,164 @@ mod tests {
);
}
}
#[test]
fn test_redb_fresh_reuse_does_not_record_floor_compact() {
let dir = tempfile::tempdir().unwrap();
let (mut nm, db_path, idx_path) = open_writable_redb(dir.path());
let len = std::fs::metadata(&db_path).unwrap().len();
assert!(len <= REDB_SMALL_FILE_BYTES, "fresh file is {len} bytes");
nm.close();
drop(nm);
let loaded = reload_redb(&db_path, &idx_path);
assert_eq!(loaded.live_floor_compact(), None);
assert!(loaded.get(NeedleId(1)).unwrap().is_none());
}
#[test]
fn test_redb_in_band_file_is_compacted_once() {
let dir = tempfile::tempdir().unwrap();
let (mut nm, db_path, idx_path) = open_writable_redb(dir.path());
let mut n = 0u64;
loop {
n += 1;
nm.put(
NeedleId(n),
Offset::from_actual_offset((n as i64).saturating_mul(8)),
Size(8),
)
.unwrap();
let len = std::fs::metadata(&db_path).unwrap().len();
if should_compact_old_floor(len) {
break;
}
assert!(
n < 2_000_000,
"file grew to {len} bytes without entering the old-floor band"
);
}
nm.checkpoint(true).unwrap();
nm.close();
drop(nm);
let mut loaded = reload_redb(&db_path, &idx_path);
let len = std::fs::metadata(&db_path).unwrap().len();
let flag = loaded.live_floor_compact();
if should_compact_old_floor(len) {
assert_eq!(flag, Some(1));
} else {
assert!(len <= REDB_SMALL_FILE_BYTES, "compacted file is {len} bytes");
assert_eq!(flag, None);
}
let first = loaded.get(NeedleId(1)).unwrap();
assert!(first.is_some());
let last = loaded.get(NeedleId(n)).unwrap();
assert!(last.is_some());
// close checkpoints the non-durable floor_compact flag, then drop
// releases the exclusive lock before the second open.
loaded.close();
drop(loaded);
let again = reload_redb(&db_path, &idx_path);
assert_eq!(std::fs::metadata(&db_path).unwrap().len(), len);
assert_eq!(again.live_floor_compact(), flag);
}
#[test]
fn test_redb_sparse_old_floor_shrinks_on_reuse() {
let dir = tempfile::tempdir().unwrap();
let (mut nm, db_path, idx_path) = open_writable_redb(dir.path());
let mut n = 0u64;
loop {
n += 1;
nm.put(
NeedleId(n),
Offset::from_actual_offset((n as i64).saturating_mul(8)),
Size(8),
)
.unwrap();
let len = std::fs::metadata(&db_path).unwrap().len();
if should_compact_old_floor(len) {
break;
}
assert!(n < 2_000_000, "file is {len} bytes and never entered the band");
}
assert!(n > 32, "band was reached with only {n} keys");
nm.checkpoint(true).unwrap();
nm.close();
drop(nm);
let keep = 32u64;
let idx = std::fs::OpenOptions::new().write(true).open(&idx_path).unwrap();
idx.set_len(keep * NEEDLE_MAP_ENTRY_SIZE as u64).unwrap();
drop(idx);
let db = redb::Database::builder()
.set_cache_size(redb_test_cache())
.open(db_path.to_str().unwrap())
.unwrap();
let txn = db.begin_write().unwrap();
{
let mut table = txn.open_table(NEEDLE_TABLE).unwrap();
for key in (keep + 1)..=n {
table.remove(key).unwrap();
}
}
{
let mut meta = txn.open_table(META_TABLE).unwrap();
meta.insert(META_IDX_SIZE, keep * NEEDLE_MAP_ENTRY_SIZE as u64)
.unwrap();
}
txn.commit().unwrap();
drop(db);
let before = std::fs::metadata(&db_path).unwrap().len();
let loaded = reload_redb(&db_path, &idx_path);
let after = std::fs::metadata(&db_path).unwrap().len();
assert!(after < before, "reuse left the file at {after} bytes, was {before}");
assert!(
after <= REDB_SMALL_FILE_BYTES,
"32 live keys still occupy {after} bytes"
);
assert!(loaded.get(NeedleId(1)).unwrap().is_some());
assert!(loaded.get(NeedleId(keep)).unwrap().is_some());
assert!(loaded.get(NeedleId(keep + 1)).unwrap().is_none());
}
#[test]
fn test_compact_follow_up_reopens_only_on_storage_error() {
use redb::{CompactionError, StorageError};
let storage = CompactionError::Storage(StorageError::Io(std::io::Error::other("sync")));
assert_eq!(
compact_follow_up(&storage),
CompactFollowUp::ReopenSkipCompact
);
assert_eq!(
compact_follow_up(&CompactionError::TransactionInProgress),
CompactFollowUp::KeepHandle
);
assert_eq!(
compact_follow_up(&CompactionError::PersistentSavepointExists),
CompactFollowUp::KeepHandle
);
assert_eq!(
compact_follow_up(&CompactionError::EphemeralSavepointExists),
CompactFollowUp::KeepHandle
);
}
#[test]
fn test_redb_reopen_database_reads_committed_key() {
let dir = tempfile::tempdir().unwrap();
let (mut nm, _db_path, _idx_path) = open_writable_redb(dir.path());
nm.put(NeedleId(7), Offset::from_actual_offset(64), Size(9))
.unwrap();
nm.reopen_database().unwrap();
let nv = nm.get(NeedleId(7)).unwrap().unwrap();
assert_eq!(nv.size, Size(9));
nm.put(NeedleId(8), Offset::from_actual_offset(128), Size(10))
.unwrap();
let nv = nm.get(NeedleId(8)).unwrap().unwrap();
assert_eq!(nv.size, Size(10));
}
}
+214 -28
View File
@@ -122,6 +122,9 @@ pub struct Store {
/// The copy-claim set installed on every location by
/// set_volume_load_guard, kept here so a later add_location gets it too.
load_guard: Option<Arc<Mutex<HashSet<VolumeId>>>>,
/// The data directory of every disk this server loads, set before the
/// first `add_location` so a disk's EC mounts can see its siblings.
pub store_dirs: Vec<String>,
}
impl Store {
@@ -148,6 +151,7 @@ impl Store {
disk_stats_of: super::disk_location::get_disk_stats,
load_guard: None,
preallocate_supported: PREALLOCATE_SUPPORTED,
store_dirs: Vec::new(),
}
}
@@ -170,6 +174,7 @@ impl Store {
tags,
)?;
loc.load_guard = self.load_guard.clone();
loc.store_dirs = self.store_dirs.clone();
loc.load_existing_volumes(self.needle_map_kind)?;
// Check for duplicate volume IDs across existing locations
@@ -287,12 +292,20 @@ impl Store {
// ---- Volume lifecycle ----
/// 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, preallocate: u64) -> Option<usize> {
/// Find the location with the fewest writable volumes of `collection`, so
/// they do not share one disk's write bandwidth, then the most free slots
/// (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,
collection: &str,
preallocate: u64,
) -> Option<usize> {
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let mut best: Option<(usize, i64)> = None; // (index, effective_free)
let volume_size_limit = self.volume_size_limit.load(Ordering::Relaxed);
let mut best: Option<(usize, usize, i64)> = None; // (index, writable, effective_free)
for (i, loc) in self.locations.iter().enumerate() {
if &loc.disk_type != disk_type {
continue;
@@ -322,11 +335,14 @@ impl Store {
) {
continue;
}
if best.is_none() || effective_free > best.unwrap().1 {
best = Some((i, effective_free));
let writable = loc.writable_collection_volumes_len(collection, volume_size_limit);
if best.is_none_or(|(_, min_writable, max_free)| {
writable < min_writable || (writable == min_writable && effective_free > max_free)
}) {
best = Some((i, writable, effective_free));
}
}
best.map(|(i, _)| i)
best.map(|(i, _, _)| i)
}
/// Find a free location matching a predicate.
@@ -462,6 +478,10 @@ impl Store {
/// their index files across disks of the same node and lose them at
/// startup. See seaweedfs/seaweedfs#9212.
///
/// A non-empty `required_disk_type` limits every step to disks of that
/// type, so a copy meant for one medium never lands beside the volume's
/// copy on another.
///
/// `data_shard_count` is taken as a parameter rather than read from
/// `DATA_SHARDS_COUNT` so custom-ratio builds can swap the default
/// without touching this helper.
@@ -475,6 +495,7 @@ impl Store {
collection: &str,
vid: VolumeId,
data_shard_count: u32,
required_disk_type: &str,
shard_ids: &[ShardId],
) -> Option<usize> {
const TIER_ANY_DISK: u8 = 1;
@@ -483,14 +504,21 @@ impl Store {
const TIER_MOUNTED: u8 = 4;
const TIER_OWNS_SHARD: u8 = 5;
let required =
(!required_disk_type.is_empty()).then(|| DiskType::from_string(required_disk_type));
// (index, tier, owned shard count, free shard slots)
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 {
if loc.read_only_mount || required.as_ref().is_some_and(|t| loc.disk_type != *t) {
// An owner that cannot take the copy still owns the shard:
// placing another copy on a sibling would register it on two disks.
// A typed copy also yields to an unmounted file of the shard there,
// which a later mount would pick ahead of the copy.
if owned > 0
|| (required.is_some()
&& has_ec_shard_file_on_disk(loc, collection, vid, shard_ids))
{
return None;
}
continue;
@@ -596,7 +624,7 @@ impl Store {
return Err(VolumeError::AlreadyExists);
}
let loc_idx = self
.find_free_location(&disk_type, spec.preallocate)
.find_free_location(&disk_type, spec.collection, spec.preallocate)
.ok_or_else(|| {
VolumeError::Io(io::Error::other(format!(
"no free location for disk type {:?}",
@@ -1037,13 +1065,18 @@ 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,
fsync: bool,
) -> 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() {
return Err(VolumeError::ReadOnly(vid));
}
vol.delete_needle(n)
vol.delete_needle(n, fsync)
}
// ---- Collection operations ----
@@ -1342,6 +1375,19 @@ impl Store {
None
}
/// Takes the journal lock of every runtime of `vid`, in disk order, so no
/// delete append is in flight while the caller reads the journals.
pub(crate) fn lock_ec_journals(
&self,
vid: VolumeId,
) -> Vec<std::sync::MutexGuard<'_, crate::storage::erasure_coding::ec_volume::EcJournal>> {
self.locations
.iter()
.filter_map(|loc| loc.find_ec_volume(vid))
.map(|ecv| ecv.journal())
.collect()
}
/// Find an EC volume across all locations (mutable).
/// Every per-disk `EcVolume` this store maps for `vid`. A vid can mount on
/// N disks as N distinct runtimes, and the first-match `find_ec_volume_mut`
@@ -2066,6 +2112,19 @@ fn ec_free_shard_count(loc: &DiskLocation, data_shard_count: u32) -> i64 {
free
}
/// Whether `loc` holds a file for one of `shard_ids` of `vid`, mounted or not.
fn has_ec_shard_file_on_disk(
loc: &DiskLocation,
collection: &str,
vid: VolumeId,
shard_ids: &[ShardId],
) -> bool {
let base = crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
shard_ids
.iter()
.any(|shard_id| std::path::Path::new(&format!("{}.ec{:02}", base, shard_id)).exists())
}
/// Reports how many of `shard_ids` this disk already claims for `vid`, per
/// the in-memory registration the read path and heartbeats use.
///
@@ -2918,7 +2977,9 @@ mod tests {
cookie: Cookie(0xaa),
..Needle::default()
};
let deleted = store.delete_volume_needle(VolumeId(1), &mut del_n).unwrap();
let deleted = store
.delete_volume_needle(VolumeId(1), &mut del_n, false)
.unwrap();
assert!(deleted.0 > 0);
}
@@ -3027,6 +3088,87 @@ mod tests {
assert_eq!(store.locations[1].volumes_len(), 1);
}
fn add_spread_test_volume(store: &mut Store, vid: u32, collection: &str) {
let spec = VolumeSpec {
collection,
..VolumeSpec::default()
};
store
.add_volume(VolumeId(vid), DiskType::HardDrive, &spec)
.unwrap();
}
fn location_of(store: &Store, vid: u32) -> Option<usize> {
store
.locations
.iter()
.position(|loc| loc.find_volume(VolumeId(vid)).is_some())
}
// Mirrors Go's TestAddVolumeSpreadsCollectionOverDisks.
#[test]
fn test_add_volume_spreads_collection_over_disks() {
let tmp1 = TempDir::new().unwrap();
let tmp2 = TempDir::new().unwrap();
let mut store =
make_test_store(&[tmp1.path().to_str().unwrap(), tmp2.path().to_str().unwrap()]);
add_spread_test_volume(&mut store, 1, "other");
add_spread_test_volume(&mut store, 2, "other");
add_spread_test_volume(&mut store, 3, "spread");
let first = location_of(&store, 3);
// Leave the disk with the "spread" volume holding fewer volumes overall.
let other_on_first = if first == Some(1) { 2 } else { 1 };
store
.delete_volume(VolumeId(other_on_first), false, false, false)
.unwrap();
add_spread_test_volume(&mut store, 4, "spread");
assert_ne!(location_of(&store, 4), first);
}
// Mirrors Go's TestAddVolumeIgnoresFullVolumesOfCollection.
#[test]
fn test_add_volume_ignores_full_volumes_of_collection() {
let tmp1 = TempDir::new().unwrap();
let tmp2 = TempDir::new().unwrap();
let mut store =
make_test_store(&[tmp1.path().to_str().unwrap(), tmp2.path().to_str().unwrap()]);
// Every .dat holds at least its superblock, so all volumes are full.
store.volume_size_limit.store(1, Ordering::Relaxed);
add_spread_test_volume(&mut store, 1, "spread");
let full_disk = location_of(&store, 1);
add_spread_test_volume(&mut store, 2, "other");
add_spread_test_volume(&mut store, 3, "spread");
assert_eq!(location_of(&store, 3), full_disk);
}
// Mirrors Go's TestAddVolumeIgnoresReadOnlyVolumesOfCollection.
#[test]
fn test_add_volume_ignores_read_only_volumes_of_collection() {
let tmp1 = TempDir::new().unwrap();
let tmp2 = TempDir::new().unwrap();
let mut store =
make_test_store(&[tmp1.path().to_str().unwrap(), tmp2.path().to_str().unwrap()]);
add_spread_test_volume(&mut store, 1, "spread");
let writable_disk = location_of(&store, 1);
add_spread_test_volume(&mut store, 2, "other");
add_spread_test_volume(&mut store, 3, "spread");
assert_ne!(location_of(&store, 3), writable_disk);
store
.find_volume(VolumeId(3))
.unwrap()
.1
.set_read_only()
.unwrap();
// The other disk holds more volumes, but its "spread" volume is read-only.
add_spread_test_volume(&mut store, 4, "spread");
assert_ne!(location_of(&store, 4), writable_disk);
}
#[test]
fn test_store_delete_collection() {
let tmp = TempDir::new().unwrap();
@@ -3395,7 +3537,7 @@ mod tests {
cookie: Cookie(2),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del).unwrap();
store.delete_volume_needle(vid, &mut del, false).unwrap();
let size_before = store.find_volume(vid).unwrap().1.dat_file_size().unwrap();
@@ -3719,7 +3861,7 @@ mod tests {
cookie: Cookie(2),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del).unwrap();
store.delete_volume_needle(vid, &mut del, false).unwrap();
let revision = {
let (_, v) = store.find_volume(vid).unwrap();
v.super_block().compaction_revision
@@ -3744,7 +3886,7 @@ mod tests {
cookie: Cookie(4),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del).unwrap();
store.delete_volume_needle(vid, &mut del, false).unwrap();
drop(release_tx);
copy.join().unwrap().unwrap();
@@ -3817,7 +3959,7 @@ mod tests {
let base = volume_file_name(&store.locations[2].idx_directory, collection, vid);
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
let got = store.find_ec_shard_target_location(collection, vid, 10, &[]);
let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]);
assert_eq!(
got,
Some(2),
@@ -4027,7 +4169,7 @@ mod tests {
let base = volume_file_name(&store.locations[2].idx_directory, collection, vid);
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
let got = store.find_ec_shard_target_location(collection, vid, 10, &[]);
let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]);
assert_eq!(
got,
Some(1),
@@ -4041,7 +4183,7 @@ mod tests {
#[test]
fn test_find_ec_shard_target_location_falls_through_to_hdd_when_nothing_matches() {
let (store, _tmp) = make_ec_target_test_store(2);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(3333), 10, &[]);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(3333), 10, "", &[]);
assert!(got.is_some(), "expected an HDD fallback");
assert_eq!(store.locations[got.unwrap()].disk_type, DiskType::HardDrive);
}
@@ -4057,7 +4199,7 @@ mod tests {
.max_volume_count
.store(0, Ordering::Relaxed);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(4444), 10, &[]);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(4444), 10, "", &[]);
assert_eq!(
got,
Some(0),
@@ -4106,7 +4248,7 @@ mod tests {
.mount_ec_shards(vid, collection, &[0], "")
.unwrap();
let got = store.find_ec_shard_target_location(collection, vid, 10, &[]);
let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]);
assert_eq!(
got,
Some(1),
@@ -4148,24 +4290,68 @@ mod tests {
.unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, &[0]),
store.find_ec_shard_target_location(collection, vid, 10, "", &[0]),
Some(0),
"a copy of shard 0 left its owning disk",
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, &[2]),
store.find_ec_shard_target_location(collection, vid, 10, "", &[2]),
Some(1),
"a copy of shard 2 left its owning disk",
);
// A shard no disk owns yet is placed by the unchanged waterfall: both
// disks have it mounted, so the emptier one wins.
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, &[7]),
store.find_ec_shard_target_location(collection, vid, 10, "", &[7]),
Some(1),
"placement of an unclaimed shard changed",
);
}
/// A copy that names a disk type skips the other medium even when that
/// disk has the EC volume mounted, and refuses rather than split a shard
/// another medium already owns.
#[test]
fn test_find_ec_shard_target_location_required_disk_type() {
let (mut store, _tmp) = make_ec_target_test_store(2);
store.locations[0].disk_type = DiskType::Ssd;
store.locations[1].disk_type = DiskType::from_string("hdd_ht");
let collection = "grafana-loki";
let vid = VolumeId(5555);
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
std::fs::write(format!("{}.ec01", base0), b"x").unwrap();
std::fs::write(format!("{}.ecx", base0), vec![0u8; 20]).unwrap();
store.locations[0]
.mount_ec_shards(vid, collection, &[0, 1], "")
.unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[2]),
Some(0)
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[2]),
Some(1),
"a hdd_ht copy landed off the hdd_ht disk",
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[1]),
None,
"a shard the ssd disk owns must not get a second claim on hdd_ht",
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd", &[2]),
None
);
std::fs::write(format!("{}.ec03", base0), b"x").unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[3]),
None,
"an unmounted shard file on ssd would be mounted ahead of a hdd_ht copy",
);
}
/// The second half of the invariant: a disk with no free shard slots
/// still wins for a shard it already owns. Re-copying that shard
/// overwrites bytes the disk is already accounted for, while routing to a
@@ -4200,13 +4386,13 @@ mod tests {
.unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, &[0]),
store.find_ec_shard_target_location(collection, vid, 10, "", &[0]),
Some(0),
"a copy of shard 0 left its owning disk when the disk was full",
);
// A shard it does not own still respects the space filter.
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, &[7]),
store.find_ec_shard_target_location(collection, vid, 10, "", &[7]),
Some(1),
"an unclaimed shard should go to the disk with free slots",
);
+270 -12
View File
@@ -8,7 +8,9 @@ use std::path::Path;
use tracing::{info, warn};
use crate::storage::disk_location::{DiskLocation, parse_collection_volume_id_pub};
use crate::storage::disk_location::{
DiskLocation, parse_collection_volume_id_pub, vif_is_ec_volume,
};
use crate::storage::store::Store;
use crate::storage::types::VolumeId;
@@ -34,10 +36,14 @@ impl Store {
/// `reconcile_ec_shards_across_disks` so the orphan pass can
/// prefer the local idx_directory.
pub fn mirror_ec_metadata_to_shard_disks(&mut self) {
self.mirror_ec_metadata_to_shard_disks_only(None)
}
pub(crate) fn mirror_ec_metadata_to_shard_disks_only(&mut self, only: Option<VolumeId>) {
if self.locations.len() < 2 {
return;
}
let owners = self.index_ecx_owners_for_mirror();
let owners = self.index_ecx_owners_for_mirror(only);
if owners.is_empty() {
return;
}
@@ -52,7 +58,7 @@ impl Store {
}
let mut mirrors: Vec<Mirror> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let orphans = collect_shard_disk_volumes(loc);
let orphans = collect_shard_disk_volumes(loc, only);
for (key, _shards) in orphans {
let Some(owner) = owners.get(&key) else {
continue;
@@ -111,7 +117,7 @@ impl Store {
// Records both idx_dir (where .ecx was found) and data_dir, so
// the mirror can resolve .vif from data_dir even when .ecx lives
// in idx_directory.
fn index_ecx_owners_for_mirror(&self) -> HashMap<EcKey, EcxOwner> {
fn index_ecx_owners_for_mirror(&self, only: Option<VolumeId>) -> HashMap<EcKey, EcxOwner> {
let mut owners: HashMap<EcKey, EcxOwner> = HashMap::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let mut seen: Vec<&str> = Vec::with_capacity(2);
@@ -131,15 +137,18 @@ impl Store {
let Some(base) = name.strip_suffix(".ecx") else {
continue;
};
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
// A 0-byte .ecx is a corrupt stub from a failed copy, not a
// credible owner — skip it so the scan keeps looking for a
// real index on a sibling disk (Go's indexEcxOwners).
if !ent.metadata().is_ok_and(|m| m.len() > 0) {
continue;
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
owners
.entry(EcKey { collection, vid })
.or_insert_with(|| EcxOwner {
@@ -207,6 +216,33 @@ fn mirror_sidecars_for_volume(
collection: &str,
vid: VolumeId,
) -> io::Result<usize> {
// A local .vif with no EC config (a source volume's own) would shadow the
// owner's once the index is copied next to it; keep mounting across disks.
let dst_vif = sidecar_dest_path(dst_data_dir, dst_idx_dir, collection, vid, ".vif");
if path_is_regular_file(&dst_vif)
&& !vif_is_ec_volume(&dst_vif)
&& (vif_is_ec_volume(&sidecar_dest_path(
src_data_dir,
src_idx_dir,
collection,
vid,
".vif",
)) || vif_is_ec_volume(&sidecar_dest_path(
src_idx_dir,
src_data_dir,
collection,
vid,
".vif",
)))
{
info!(
volume_id = vid.0,
collection = %collection,
vif = %dst_vif,
"local .vif records no EC config; not mirroring EC sidecars",
);
return Ok(0);
}
let mut copied = 0usize;
for ext in EC_MIRRORED_SIDECARS {
let dst = sidecar_dest_path(dst_data_dir, dst_idx_dir, collection, vid, ext);
@@ -268,7 +304,10 @@ fn copy_sidecar_atomic(src: &Path, dst: &Path) -> io::Result<()> {
Ok(())
}
fn collect_shard_disk_volumes(loc: &DiskLocation) -> HashMap<EcKey, Vec<String>> {
fn collect_shard_disk_volumes(
loc: &DiskLocation,
only: Option<VolumeId>,
) -> HashMap<EcKey, Vec<String>> {
let mut out: HashMap<EcKey, Vec<String>> = HashMap::new();
let Ok(read) = fs::read_dir(&loc.directory) else {
return out;
@@ -285,13 +324,16 @@ fn collect_shard_disk_volumes(loc: &DiskLocation) -> HashMap<EcKey, Vec<String>>
if crate::storage::disk_location::is_ec_shard_extension(ext).is_none() {
continue;
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
match ent.metadata() {
Ok(meta) if meta.len() > 0 => {}
_ => continue,
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
out.entry(EcKey { collection, vid }).or_default().push(name);
}
out
@@ -391,6 +433,222 @@ mod tests {
assert_eq!(ecj_dst, ecj, ".ecj mirrored bytes differ from source");
}
/// Shards on a disk that still holds the source volume's config-free
/// `.vif` must mount with the owner's encode identity: mirroring the index
/// next to that `.vif` would make the disk mount through it.
#[test]
fn mirror_skips_disk_with_config_free_vif() {
let tmp = TempDir::new().unwrap();
let dir0 = tmp.path().join("data0");
let dir1 = tmp.path().join("data1");
fs::create_dir_all(&dir0).unwrap();
fs::create_dir_all(&dir1).unwrap();
let collection = "c";
let vid = 4122u32;
plant_shard(&dir0, collection, vid, 2);
plant_shard(&dir1, collection, vid, 0);
fs::write(
dir0.join(format!("{}_{}.vif", collection, vid)),
r#"{"version":3,"readOnly":true}"#,
)
.unwrap();
plant_ecx(&dir1, collection, vid, &[0xA1u8; 20]);
let vif = VifVolumeInfo {
version: 3,
ec_shard_config: Some(VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
encode_ts_ns: 1_700_000_000_000_000_042,
..Default::default()
}),
..Default::default()
};
fs::write(
dir1.join(format!("{}_{}.vif", collection, vid)),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
add_loc(&mut store, &dir0);
add_loc(&mut store, &dir1);
assert!(
!dir0.join(format!("{}_{}.ecx", collection, vid)).exists(),
".ecx mirrored next to the config-free .vif"
);
let ec_vol = store.locations[0]
.find_ec_volume(VolumeId(vid))
.expect("dir0 ec volume mounted");
assert_eq!(ec_vol.encode_ts_ns, 1_700_000_000_000_000_042);
}
/// With a shared `-dir.idx` every disk sees the `.ecx`, and only the disk
/// that received it holds the encode's `.vif`. A disk loaded first that
/// still holds the source volume's config-free `.vif` must take that
/// identity from its sibling.
#[test]
fn shared_index_disk_takes_sibling_vif_on_startup() {
let tmp = TempDir::new().unwrap();
let dir0 = tmp.path().join("data0");
let dir1 = tmp.path().join("data1");
let idx = tmp.path().join("idx");
for d in [&dir0, &dir1, &idx] {
fs::create_dir_all(d).unwrap();
}
let collection = "c";
let vid = 4123u32;
plant_shard(&dir0, collection, vid, 2);
plant_shard(&dir1, collection, vid, 0);
fs::write(
dir0.join(format!("{}_{}.vif", collection, vid)),
r#"{"version":3,"readOnly":true}"#,
)
.unwrap();
plant_ecx(&idx, collection, vid, &[0xA1u8; 20]);
let vif = VifVolumeInfo {
version: 3,
ec_shard_config: Some(VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
encode_ts_ns: 1_700_000_000_000_000_043,
..Default::default()
}),
..Default::default()
};
fs::write(
dir1.join(format!("{}_{}.vif", collection, vid)),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
let mut store = Store::new(NeedleMapKind::InMemory);
store.store_dirs = vec![
dir0.to_str().unwrap().to_string(),
dir1.to_str().unwrap().to_string(),
];
for dir in [&dir0, &dir1] {
store
.add_location(
dir.to_str().unwrap(),
idx.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
for loc in &store.locations {
let ec_vol = loc
.find_ec_volume(VolumeId(vid))
.unwrap_or_else(|| panic!("{} ec volume mounted", loc.directory));
assert_eq!(
ec_vol.encode_ts_ns, 1_700_000_000_000_000_043,
"{}",
loc.directory
);
}
}
/// Starts a store whose first disk still holds the source `.dat`, its
/// config-free `.vif` and one 12+4 shard, with the `.ecx` in a shared
/// index dir and one sibling encode `.vif` per entry of `sibling_runs`.
/// Asserts the source `.dat`, the shard and the `.ecx` survive startup.
fn start_with_sibling_encode_vifs(sibling_runs: &[i64]) -> Store {
let tmp = TempDir::new().unwrap();
let dirs: Vec<_> = (0..=sibling_runs.len())
.map(|i| tmp.path().join(format!("data{}", i)))
.collect();
let idx = tmp.path().join("idx");
for d in dirs.iter().chain([&idx]) {
fs::create_dir_all(d).unwrap();
}
let collection = "c";
let vid = 4124u32;
let base0 = dirs[0].join(format!("{}_{}", collection, vid));
let dat = format!("{}.dat", base0.display());
let shard = format!("{}.ec02", base0.display());
fs::File::create(&dat)
.unwrap()
.set_len(11 * 1024 * 1024)
.unwrap();
fs::File::create(&shard)
.unwrap()
.set_len(1024 * 1024)
.unwrap();
fs::write(
format!("{}.vif", base0.display()),
r#"{"version":3,"readOnly":true}"#,
)
.unwrap();
plant_ecx(&idx, collection, vid, &[0xA1u8; 20]);
for (dir, run) in dirs[1..].iter().zip(sibling_runs) {
let vif = VifVolumeInfo {
version: 3,
ec_shard_config: Some(VifEcShardConfig {
data_shards: 12,
parity_shards: 4,
encode_ts_ns: *run,
..Default::default()
}),
..Default::default()
};
fs::write(
dir.join(format!("{}_{}.vif", collection, vid)),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
}
let mut store = Store::new(NeedleMapKind::InMemory);
store.store_dirs = dirs
.iter()
.map(|d| d.to_str().unwrap().to_string())
.collect();
for dir in &dirs {
store
.add_location(
dir.to_str().unwrap(),
idx.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
let ecx = idx.join(format!("{}_{}.ecx", collection, vid));
for path in [dat.as_str(), shard.as_str(), ecx.to_str().unwrap()] {
assert!(Path::new(path).exists(), "{} removed at startup", path);
}
store
}
/// A disk still holding the source `.dat` sizes its shards by the
/// sibling's encode `.vif` before the startup check decides whether they
/// are leftovers of an interrupted encode.
#[test]
fn shared_index_startup_validation_uses_sibling_vif_ratio() {
let store = start_with_sibling_encode_vifs(&[1_700_000_000_000_000_044]);
let ec_vol = store.locations[0]
.find_ec_volume(VolumeId(4124))
.expect("dir0 ec volume mounted");
assert!(ec_vol.has_shard(2), "shard 2 not mounted on dir0");
}
/// Sibling `.vif` files naming different encode runs leave the ratio
/// unknown, so the startup check keeps the shards.
#[test]
fn shared_index_startup_validation_keeps_shards_on_disagreeing_siblings() {
start_with_sibling_encode_vifs(&[1_700_000_000_000_000_044, 1_700_000_000_000_000_045]);
}
#[test]
fn mirror_preserves_existing_destination_sidecars() {
let tmp = TempDir::new().unwrap();
@@ -443,7 +701,7 @@ mod tests {
add_loc(&mut store, &dir0);
add_loc(&mut store, &dir1);
let owners = store.index_ecx_owners_for_mirror();
let owners = store.index_ecx_owners_for_mirror(None);
let owner = owners
.get(&EcKey {
collection: collection.to_string(),
+115 -18
View File
@@ -92,11 +92,15 @@ impl Store {
///
/// Mirrors `Store.reconcileEcShardsAcrossDisks` in Go.
pub fn reconcile_ec_shards_across_disks(&mut self) {
self.reconcile_ec_shards_across_disks_only(None)
}
pub(crate) fn reconcile_ec_shards_across_disks_only(&mut self, only: Option<VolumeId>) {
if self.locations.len() < 2 {
return;
}
let owners = self.index_ecx_owners();
let owners = self.index_ecx_owners(only);
if owners.is_empty() {
return;
}
@@ -106,7 +110,7 @@ impl Store {
// loc.idx_directory instead of the owner disk.
let mut to_load: Vec<OrphanShardLoad> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let orphans = collect_orphan_ec_shards(loc, loc_idx);
let orphans = collect_orphan_ec_shards(loc, loc_idx, only);
for (key, shards) in orphans {
let Some(owner) = owners.get(&key) else {
warn!(
@@ -402,7 +406,7 @@ impl Store {
/// matched so downstream loaders point `EcVolume::new` at the
/// directory that really has the file. The first owner found wins;
/// duplicates across disks are unusual but tolerated.
fn index_ecx_owners(&self) -> HashMap<EcKey, EcxOwnerInfo> {
fn index_ecx_owners(&self, only: Option<VolumeId>) -> HashMap<EcKey, EcxOwnerInfo> {
let mut owners: HashMap<EcKey, EcxOwnerInfo> = HashMap::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let mut seen: Vec<&str> = Vec::with_capacity(2);
@@ -422,15 +426,18 @@ impl Store {
let Some(base) = name.strip_suffix(".ecx") else {
continue;
};
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
// A 0-byte .ecx is a corrupt stub from a failed copy, not a
// credible owner — skip it so the scan keeps looking for a
// real index on a sibling disk (Go's indexEcxOwners).
if !ent.metadata().is_ok_and(|m| m.len() > 0) {
continue;
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
let key = EcKey { collection, vid };
owners.entry(key).or_insert(EcxOwnerInfo {
location: loc_idx,
@@ -450,11 +457,18 @@ impl Store {
///
/// Mirrors `Store.CollectEcVolumesMissingIndex` in Go.
pub(crate) fn collect_ec_volumes_missing_index(&self) -> Vec<EcVolumeMissingIndex> {
let owners = self.index_ecx_owners();
self.collect_ec_volumes_missing_index_only(None)
}
pub(crate) fn collect_ec_volumes_missing_index_only(
&self,
only: Option<VolumeId>,
) -> Vec<EcVolumeMissingIndex> {
let owners = self.index_ecx_owners(only);
let mut seen: HashSet<EcKey> = HashSet::new();
let mut missing = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
for (key, _shards) in collect_orphan_ec_shards(loc, loc_idx) {
for (key, _shards) in collect_orphan_ec_shards(loc, loc_idx, only) {
if owners.contains_key(&key) || !seen.insert(key.clone()) {
continue;
}
@@ -474,18 +488,24 @@ impl Store {
/// the disks that now have a local index, then fall back to the cross-disk
/// virtual mount. Mirrors `Store.MountRecoveredEcShards` in Go.
pub(crate) fn mount_recovered_ec_shards(&mut self) {
self.mirror_ec_metadata_to_shard_disks();
self.load_orphan_ec_shards_with_local_index();
self.reconcile_ec_shards_across_disks();
self.mount_recovered_ec_shards_only(None)
}
/// `mount_recovered_ec_shards` restricted to one volume's shards when
/// `only` names it.
pub(crate) fn mount_recovered_ec_shards_only(&mut self, only: Option<VolumeId>) {
self.mirror_ec_metadata_to_shard_disks_only(only);
self.load_orphan_ec_shards_with_local_index(only);
self.reconcile_ec_shards_across_disks_only(only);
}
/// Mount on-disk EC shards whose `.ecx` index is now present on the same disk.
/// Unlike `reconcile_ec_shards_across_disks` it needs no sibling disk, so a
/// single-disk store recovers once its index has been fetched from a peer.
fn load_orphan_ec_shards_with_local_index(&mut self) {
fn load_orphan_ec_shards_with_local_index(&mut self, only: Option<VolumeId>) {
let mut work: Vec<(usize, EcKey, Vec<ShardId>)> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
for (key, shards) in collect_orphan_ec_shards(loc, loc_idx) {
for (key, shards) in collect_orphan_ec_shards(loc, loc_idx, only) {
if !loc.has_ecx_file_on_disk(&key.collection, key.vid) {
continue;
}
@@ -516,6 +536,7 @@ impl Store {
fn collect_orphan_ec_shards(
loc: &crate::storage::disk_location::DiskLocation,
_loc_idx: usize,
only: Option<VolumeId>,
) -> HashMap<EcKey, Vec<(String, ShardId)>> {
let mut orphans: HashMap<EcKey, Vec<(String, ShardId)>> = HashMap::new();
let Ok(read) = fs::read_dir(&loc.directory) else {
@@ -533,6 +554,12 @@ fn collect_orphan_ec_shards(
let Some(shard_id) = is_ec_shard_extension(ext) else {
continue;
};
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
// Ignore zero-byte shards. Use the DirEntry's metadata so we
// don't pay a second stat syscall per file beyond what
// read_dir already returned.
@@ -540,9 +567,6 @@ fn collect_orphan_ec_shards(
Ok(meta) if meta.len() > 0 => {}
_ => continue,
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
// Skip shards that are already registered to an EcVolume.
if let Some(ecv) = loc.find_ec_volume(vid)
&& ecv.has_shard(shard_id)
@@ -655,7 +679,7 @@ mod tests {
std::fs::write(ec_local_ecx_path(&d0, "pics", VolumeId(7)), b"").unwrap();
write_index_files(&d1, "pics", 7, 10, 4);
let owners = store.index_ecx_owners();
let owners = store.index_ecx_owners(None);
let owner = owners
.get(&EcKey {
collection: "pics".to_string(),
@@ -667,7 +691,7 @@ mod tests {
// A stub with no real index anywhere owns nothing.
std::fs::write(ec_local_ecx_path(&d0, "pics", VolumeId(8)), b"").unwrap();
assert!(!store.index_ecx_owners().contains_key(&EcKey {
assert!(!store.index_ecx_owners(None).contains_key(&EcKey {
collection: "pics".to_string(),
vid: VolumeId(8),
}));
@@ -1240,6 +1264,79 @@ mod tests {
);
}
#[test]
fn test_mount_recovered_ec_shards_only_named_volume() {
// Recovering one volume mounts only its shards. Another volume's orphan
// shards, such as ones an in-flight copy just renamed in, stay unmounted
// even when an index for them is already on disk. Mirrors Go
// TestMountRecoveredEcShards_OnlyNamedVolume.
let tmp = TempDir::new().unwrap();
let dir0 = tmp.path().join("data0");
let dir1 = tmp.path().join("data1");
std::fs::create_dir_all(&dir0).unwrap();
std::fs::create_dir_all(&dir1).unwrap();
let collection = "col";
let (recovered_vid, other_vid) = (71u32, 72u32);
let mut store = Store::new(NeedleMapKind::InMemory);
for d in [&dir0, &dir1] {
store
.add_location(
d.to_str().unwrap(),
d.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
for vid in [recovered_vid, other_vid] {
write_shard(dir0.to_str().unwrap(), collection, vid, 0);
write_shard(dir1.to_str().unwrap(), collection, vid, 1);
}
write_index_files(dir0.to_str().unwrap(), collection, other_vid, 10, 4);
let missing = store.collect_ec_volumes_missing_index();
let m = missing
.iter()
.find(|m| m.vid == VolumeId(recovered_vid))
.expect("recovered volume not reported as missing its index");
write_index_files(&m.idx_dir, collection, recovered_vid, 10, 4);
store.mount_recovered_ec_shards_only(Some(VolumeId(recovered_vid)));
for (i, loc) in store.locations.iter().enumerate() {
let ev = loc
.find_ec_volume(VolumeId(recovered_vid))
.unwrap_or_else(|| panic!("volume {} not mounted on disk{}", recovered_vid, i));
assert!(
ev.has_shard(i as u8),
"shard {}.{} not mounted",
recovered_vid,
i
);
assert!(
loc.find_ec_volume(VolumeId(other_vid)).is_none(),
"volume {} mounted on disk{} by the recovery of volume {}",
other_vid,
i,
recovered_vid,
);
}
let mirrored = format!(
"{}/{}_{}.ecx",
dir1.to_str().unwrap(),
collection,
other_vid
);
assert!(
!std::path::Path::new(&mirrored).exists(),
"volume {} index mirrored to disk1 by the recovery of volume {}",
other_vid,
recovered_vid,
);
}
#[test]
fn test_collect_missing_index_excludes_cross_disk_orphan() {
// A .ecx merely on a sibling disk is the same-server case the reconcile
File diff suppressed because it is too large. Load diff
@@ -188,7 +188,7 @@ mod tests {
for id in 1..=3 {
v.write_needle(&mut needle(id), true, false).unwrap();
}
v.delete_needle(&mut needle(2)).unwrap();
v.delete_needle(&mut needle(2), false).unwrap();
v.sync_to_disk().unwrap();
let (want_count, want_deleted) = (v.file_count(), v.deleted_count());
drop(v);
@@ -382,10 +382,13 @@ pub(crate) mod tests {
write_test_volume(dir, 6);
let v = open_volume(dir);
v.delete_needle(&mut Needle {
id: NeedleId(3),
..Needle::default()
})
v.delete_needle(
&mut Needle {
id: NeedleId(3),
..Needle::default()
},
false,
)
.unwrap();
drop(v);
@@ -417,10 +420,13 @@ pub(crate) mod tests {
write_test_volume(dir, 8);
let v = open_volume(dir);
v.delete_needle(&mut Needle {
id: NeedleId(2),
..Needle::default()
})
v.delete_needle(
&mut Needle {
id: NeedleId(2),
..Needle::default()
},
false,
)
.unwrap();
drop(v);
Loaded 100 of 847 files, more files were not shown because too many files have changed in this diff. Show more