Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 d49fae4ab1 codespell: skip the imported seaweed-block module
The block module keeps its own text checks; its NVMe and test
vocabulary (AER, nd, readds) trips codespell's dictionary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:32:42 -08:00
Chris LuandClaude Opus 5.5 e9b51cb242 mount: stop the filer walk at a live filer's "not found" (#13357)
* mount: stop the filer walk at a live filer's "not found"

With several filers listed and some of them down, a lookup that the live
filer answered with "not found" went on to the dead filers. Their dial
error replaced the answer, so the walk retried it as a transient failure:
the mount failed to start when filer.conf did not exist, and looking up a
missing file or creating a new one failed with an I/O error after about
40 seconds. Stop at a missing entry the way a filer verdict already stops
the walk, and keep the walk on the filer that answered.

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

* mount: test a live filer's "not found" next to dead filers

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:13:59 -08:00
c46567084f sftp: read downloads as the file's logical content (#13355)
* sftp: read downloads as the file's logical content

Downloads read through filer.NewFileReader, which stops at the last stored
byte: holes between chunks, a tail no chunk stores and the zeros after
partial inline content came back missing, so sparse files downloaded short
or with later bytes shifted.

Read chunked files through filer.ChunkReadAt with one shared ReaderCache,
set up as WebDAV's: it serves FileSize bytes, zero-fills what no chunk
stores, resolves manifests, prefetches and re-looks-up moved volumes.
Closing a handle only releases its stream, as S3 does. Inline content is
read up to the file's size, then zeros. This replaces sftpd's own block
cache, whose LRU helper is now unused.

* sftp: read large downloads in sections, as the FUSE mount does

ChunkReadAt walks the file's chunk views from the start on every read, so
a sequential download of a file with many chunks costs time quadratic in
its chunk count. Read through filer.ChunkGroup instead, the reader of a
mount's file handle: it keeps chunks in 64 MiB sections, returns EOF at
the file size for any offset, and holds every open file's buffers to one
shared budget (the mount's default 256 MiB).

* sftp: cache remote-only content on open instead of refusing it

A file whose content only a remote store holds is copied into the cluster
with CacheRemoteObjectToLocalCluster when it is opened for reading, as a
mount's read and the filer's HTTP read do, and then read from the cached
chunks. It is still refused when the remote store cannot be read.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:13:40 -08:00
9290e6d69e sftp: honor the CREATE, EXCL and APPEND open flags (#13354)
* sftp: honor the CREATE, EXCL and APPEND open flags

An upload open ignored three of its flags:

- Without CREATE, opening a missing file created it on close. It now fails
  with NO_SUCH_FILE, as OpenSSH's sftp-server and SFTPGo do.
- CREATE|EXCL on an existing file succeeded and overwrote it. The open now
  creates the empty file with an exclusive filer create, so it fails when
  the name is taken, also while another exclusive upload of it buffers.
- APPEND wrote at the client's offset, usually 0, over the start of the
  file. A write below the size the file had at open is now refused, as
  SFTPGo does. Writes keep their offsets rather than going to the current
  end, because pkg/sftp may run a client's pipelined writes in any order.

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

* sftp: leave a file alone when an open of it changes nothing

An APPEND open whose writes were all refused still uploaded the copied
bytes on close, which rewrote the file and handed it to the session's
user. Any open that copied the existing file now uploads only once the
handle writes or sets attributes, not only read-write opens.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 11:12:02 -08:00
7c4b39bee1 s3api: list object metadata with ListObjectsV2 metadata=true (#13351)
* s3api: list object metadata with ListObjectsV2 metadata=true

A client that needs the type or user metadata of the objects it lists has
to HEAD each key. MinIO answers ListObjectsV2 with metadata=true by adding
each object's metadata to the page as <UserMetadata>, one element per
field, and its clients ask for it: minio-go ListObjectsOptions.WithMetadata,
minio-java ListObjectsArgs.includeUserMetadata, minio-py
list_objects(include_user_meta=True), and mc find --metadata.

With metadata=true each listed object carries the Content-Type and the
x-amz-meta-* fields GET and HEAD send for it, keyed as MinIO keys them
(content-type, X-Amz-Meta-Name). A symlink made through a mount lists with
inode/symlink and X-Amz-Meta-Seaweedfs-Symlink-Target, so links can be told
apart in a listing without a HEAD per key. As in MinIO, a key's metadata is
listed only for a caller allowed to read that key, through the per-key
check CopyObject uses for its source, so a List grant alone shows no more
than before and an anonymous caller gets none. Without the parameter, and
on ListObjects V1, nothing changes. HEAD and the listing share one
Content-Type rule.

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

* s3api: hide listed metadata a tag-conditioned policy denies

GET decides the bucket policy again on the object's entry, so a Deny on
s3:ExistingObjectTag refuses the read. The metadata=true listing only ran
the key check, which sees no tags, and listed the metadata of an object
GET refuses. Decide it on the listed entry too.

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

* s3api: keep setResponseHeaders' doc comment on it

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

* s3api: list a versioned object's metadata from its version file

The pointer cached on a .versions folder keeps an object's size, mtime,
ETag, owner and storage class, but not its type, user metadata or tags.
A metadata=true listing built from it showed a content type guessed from
the name and no x-amz-meta-* fields, and decided tag-conditioned policies
without the version's tags. Such a listing now reads the current
version's file, as GET and HEAD do; other listings keep using the pointer.

Reading the file also needed its path fixed: the fallback looked for it
under "<key>/.versions/", while versions live in "<key>.versions/", so a
pointer without the cached fields dropped the object from a listing or
failed it.

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

* s3api: fold latestVersionEntryFromDirectoryEntry into getLatestVersionEntryFromDirectoryEntry

Every caller passes useCached, so the flag goes on the existing name
rather than a second function beside it.

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

* s3api: fail a listing on a version file that cannot be read

With metadata=true every versioned key reads its version file in the
walk's .versions branch, which skipped the key on any error. A failed
read then answered a page that silently lacked the key, and a client
paging on could step past it. Skip only a version file that is gone, as
settlePendingNull and the version resolution do, and fail the listing on
any other error so the client retries it. The fallback now wraps the
lookup error with %w, so a removed version file still reads as not found
there.

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

* s3api: list the remaining version when the pointer names a removed file

A .versions pointer can name a version file that has since been removed,
as when a delete lands while a listing reads it; with metadata=true every
versioned key reads its file. GET rescans .versions/ and self-heals the
pointer, but the listing skipped the key, which left a null object listed
just before its .versions sibling as the key's current version even when
a newer version remains. The listing now recovers read-only by the
rescan it already uses for a missing pointer: it lists the version that
remains, or the null object when that is newer. When nothing current
remains, it retracts a null object listed just before the folder, as
settlePendingNull does.

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

* s3api: fail a listing when the null object cannot be read

The listing's .versions rescan treated any failed read of the base-path
null object as its absence. When that read failed for a moment and the
scan found no versions, the walk retracted the null object it had just
listed and answered success, paging past a key that still exists. The
rescan now returns such a read error, which fails the listing as an
unreadable version file already does; only a genuine not-found counts
as no null object.

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

* s3api: keep a directory from standing in for the null object in a listing rescan

The listing's .versions rescan read the base path and took whatever it
found as the null object. When the base path is a bare directory that
holds child keys, a directory newer than the remaining version replaced
it, and the listing dropped the key although GET answers that version.
The rescan now admits the base entry only when isNullVersionObject
accepts it, as GET's recoverLatestVersionWithoutPointer 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-12-03 11:11:30 -08:00
Chris LuandClaude Opus 5.5 4a0bc7fe83 mount/page_writer: count only uploads that park after the test starts waiting (#13352)
An earlier test can leave an upload parked on its read that goes on only
after the next test has counted it. The count of parked uploads then never
grows by the ones the next test parks, and it fails after 5s. Track the
parked uploads by goroutine id and wait for new ones instead.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:09:48 -08:00
Chris LuandClaude Opus 5.5 874bc97814 s3api: answer 400, not 500, for list prefixes and markers that are not valid UTF-8 (#13350)
* s3api: refuse list prefixes and markers that are not valid UTF-8

A prefix, start-after, marker or continuation token holding bytes that are
not valid UTF-8 reached the filer's listing request, which cannot carry
them, and the failure answered 500 InternalError. ListObjects and
ListObjectsV2 now answer 400 InvalidArgument for such a prefix or marker,
and the "continuation token provided is incorrect" InvalidArgument for such
a token, before listing.

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

* s3api: refuse version list prefixes and key markers that are not valid UTF-8

ListObjectVersions sent the prefix and key-marker to the filer as well, so
bytes that are not valid UTF-8 there also answered 500. They now answer
400 InvalidArgument.

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

* s3api: test listings with parameters that are not valid UTF-8

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:09:04 -08:00
Tiago PosseandClaude Opus 5.5 dc500b2cde kms/local: create on-demand keys only for new data keys (#13346)
With enableOnDemandCreate, every lookup of a missing key created it, so a
Decrypt or DescribeKey naming a key that didn't exist got a new key
instead of an error. Only GenerateDataKey creates keys now, since no other
request can succeed with a key that didn't exist before it. An alias gets
a key with a generated ID, as it would in AWS, instead of a key whose ID
is the alias, and a key ARN spelling an alias, which names no key,
creates none.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:08:15 -08:00
2c48e8a014 worker: dir_usage keeps the sizes of buckets and their large directories (#13345)
* shell: fs.du walks with a shared treewalk.Walker

The walker fs.du used moves to a new package, filer/treewalk, so that the
dir_usage job proposed in #13257 walks the same way. fs.du adds up what
its visitor is told; what it prints and how it fails stay the same. A page
now also carries the snapshot the filer listed it at, and when it was
listed.

treewalktest serves a tree from memory and logs an event for each change,
for the tests of walks and of what follows.

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

* filer/treewalk: Seed adds up a walk and the events logged while it runs

Seed walks a directory tree while it follows the metadata log below it,
and reconciles the two, so that the result is the tree as of one log
position:

- an event at or before the snapshot of the page that lists its name
  shows in that page, and so does an event in a directory not listed yet;
- an event after the page's snapshot replaces what the page counted for
  the name, since the page may or may not show it;
- once a page is older than a margin, a minute by default since a rename
  logs its events after the move, an event changes the entry from its old
  to its new entry.

A directory missing from its parent's page counts from its events if it
was created after that page's snapshot, and not at all otherwise. This is
how the mount's metadata cache builds a directory from a listing and the
events around it, with a replace per name in place of the cache's
overwrite, which a running total cannot do.

Follow reads the events of a range of the log. The lookup of where the
log starts moves here from filer_ttl as LogStartTsNs.

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

* worker: dir_usage keeps the sizes of buckets and their large directories

A plugin worker job, off by default, that keeps what fs.du adds up of each
bucket and each top-level directory outside the buckets folder, and of
each directory in it holding at least 1% of its bytes, down to 10 levels.
Directories at one depth do not overlap, so a bucket has at most 1,000
such records, whatever the shape of its tree. They are one JSON file per
bucket under /etc/seaweedfs/dir_usage/<store signature>/.

The buckets without a record are seeded in one treewalk.Seed walk of the
buckets folder, and the top-level directories in one of /. After that,
each run replays the events since the last run, up to a minute before
now, applies each to the directories with a record above the entry,
writes the files that changed, and saves a cursor that meta_log_purge
keeps the log for. A record the log no longer reaches is seeded again,
and so is every record when no log is kept and the cursor is older than
the purge honors.

A tracked directory that moves keeps its record, which the events of the
entries it took along fill again. One deleted with totals left had
entries that went without events, as when a store drops a whole bucket,
and the rest comes off the directories above it. A bucket created since
the last run is seeded by the next.

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

* shell: fs.du -report prints what the dir_usage job keeps

fs.du -report [-depth=N] path prints the totals the dir_usage job keeps of
path and of the directories below it with a record, down to N levels, the
way fs.du prints a walk, and how old they are: as old as the job's cursor
for a record the last replay did not change. Nothing is walked. For / and
the buckets folder, the buckets and top-level directories add up.

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

* treewalk, dir_usage: wait for the filer's own position, stop waits on cancel

A subscription with an end stops once it has read everything the filer has
logged, without waiting for the end to come. So the seed's catch-up now
waits until the filer's listing snapshot reaches the seed's end, and a
replay ends at the snapshot the filer gives when it starts, both on the
filer's clock rather than this process's.

- A walk waiting for its pages to free names stops when its context ends.
- A seed reports the listing that failed, not the cancellation it caused.
- A walk canceled while the last page's subdirectories start fails.
- LogStartTsNs passes over a day a purge that stopped midway left empty.
- A bucket dropped while the buckets folder is seeded gets no record; the
  next run seeds it if it is made again.
- Detection keys a store's job by its signature, so no two runs share a
  store whichever filer each starts from.
- The buckets folder is taken without a trailing slash.
- fs.du -report names the buckets and top-level directories it leaves out
  for want of a record, and no longer says why a directory has no total of
  its own.
- treewalktest.Filer replays a quiet drop with what was below it, and can
  refuse a listing.

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

* treewalk: list a page again after a transient failure

A seed walks every bucket without a record in one walk, which on a large
store runs for hours. One page that failed because the filer restarted or a
connection dropped failed the whole walk, and the next run started it over.
A page that fails with a transient error is now asked for again, with
backoff, for up to a minute. Other failures still end the listing at once.

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

* dir_usage: keep the other seeded records when one fails to save

A save that failed after a seed returned at once, so the records of the
batch not saved yet were lost, and the top-level directories were not
seeded at all when it was the buckets' batch that failed. The next run
walked them all again, which on a large store takes hours. A failed save
is now reported and the run goes on; the next run seeds only that root.

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

* treewalk: measure how far the filer's clock runs ahead in a seed

A page's end is on this host's clock and the events it is compared to
are on the filer's, so a filer clock ahead by more than the margin
expired pages before the events they show arrived, and set the seed's
end before positions the filer had already logged. The seed now learns
a lower bound of the filer's lead from the page snapshots and the event
stamps, and adds it to page expiry and to the end.

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

* mini: expect the dir_usage handler among the default job types

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-12-03 11:05:56 -08:00
Chris LuandClaude Opus 5.5 18ba10b535 s3api: answer KeyTooLongError when the filer refuses an object's name (#13349)
* s3api: answer KeyTooLongError when the routed PUT's name is refused

The filer checks an entry's name length before its first mutation stores
anything, so a routed PUT refused with ENTRY_NAME_TOO_LONG on mutation 0
is a definite refusal, not an ambiguous outcome. Treating it as ambiguous
sent a zero-byte PUT, which has no chunks to verify, to 503.

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

* s3api: test a routed PUT refused for its name length

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

* s3api: keep the filer's error code when a routed mkfile is refused

routedMkFile flattened the transaction's error into a string, so callers
could not tell a refused name from an internal failure, and a CopyObject to
a name the filer refuses answered 500. Wrap the code's sentinel, as
CreateEntry does, so the existing error mapping answers KeyTooLongError.

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

* s3api: test a routed mkfile keeps the filer's error code

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

* s3api: answer KeyTooLongError when a multipart completion's name is refused

Completing an upload whose last key segment the filer refuses answered
500 InternalError. The refused create stores nothing, so answer
KeyTooLongError as PutObject does.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:00:33 -08:00
4f6c138beb sftp: report file owners in stat and listings (#13340)
Stat, lstat and directory listings always showed uid 0 and gid 0,
although the filer stores the uploader's Uid and Gid. pkg/sftp only
sends the owner when the os.FileInfo implements its FileInfoUidGid
interface (Uid() and Gid()). EnhancedFileInfo exposed the owner through
an Owner() method and a custom Sys() struct instead, which pkg/sftp
never reads.

Implement Uid() and Gid() on EnhancedFileInfo and drop the unused
Owner(), Sys() and FileStat. Add a test that serves a session over
in-memory pipes and checks the owner returned by Stat and ReadDir.

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:40:49 -08:00
Yip LeoandClaude Opus 5.5 71b1911e44 mount: answer statfs from the stats at hand, refresh them in the background (#13337)
StatFs asked the filer for Statistics whenever its stats were older than
20 s and waited for the answer, up to the 20 s filer RPC timeout, so a
slow filer or master held statfs for that long. A node agent that probes
mounts with a bounded statfs, as the CSI driver's health monitor does
with 5 s, took such a mount for hung and restarted it, on every node at
once when the filer was slow for all of them. Every concurrent statfs
also sent its own request while the stats were stale.

StatFs now answers from the stats it has and starts a refresh in the
background when they are older than 20 s, one at a time. Only the first
statfs waits, for the first refresh. A refresh the filer does not answer
keeps the last known stats, as before, and the next one starts 20 s after
it.

The stats are now read and written under a lock: the refresh and the
quota check write them while statfs and the quota check read them.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:39:23 -08:00
333c32d610 sftp: keep a folder a folder when its mode is changed (#13341)
chmod on a folder over SFTP failed with "existing entry is a directory".
SETSTAT copied the client's mode into the entry as-is. A client sends
only the permission bits, so the directory bit was dropped and the filer
refused an update that would turn the folder into a file. Files lost
their stored type bits the same way, just without an error.

Keep the stored type bits and take only the permission, setuid, setgid
and sticky bits from the client.

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:38:33 -08:00
4cef7c1f41 sftp: refuse to read a folder instead of returning no data (#13339)
* sftp: refuse to read a folder instead of returning no data

Opening a folder for reading succeeded and every read returned EOF, so a
client that downloads without checking the type first saved an empty file.
readFile now refuses a directory, which reaches the client as
SSH_FX_FAILURE, as the read(2) of a directory does on OpenSSH's sftp-server.

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

* sftp: refuse to read a symlink instead of returning no data

A symlink entry, as weed mount creates it, keeps its target in
SymlinkTarget and stores no content, and readFile does not follow it,
so a download of one also came back as an empty file. Refuse it with
OP_UNSUPPORTED.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 10:37:50 -08:00
65d082e788 sftp: answer unsupported requests with OP_UNSUPPORTED (#13342)
* sftp: answer unsupported requests with OP_UNSUPPORTED

SYMLINK and the hardlink@openssh.com extension were answered with
SSH_FX_FAILURE ("unsupported: Symlink"). Clients such as OpenSSH sftp and
rclone use SSH_FX_OP_UNSUPPORTED to fall back; FAILURE reads as an attempt
that broke. Return sftp.ErrSSHFxOpUnsupported instead, before path
resolution, since a symlink's Filepath is the raw link target.

The version reply also used pkg/sftp's default extension list, which
advertises hardlink@openssh.com and statvfs@openssh.com. Weed implements
neither, so advertise only posix-rename@openssh.com.

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

* sftp: check the OP_UNSUPPORTED status a client receives for a symlink

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

* sftp: answer READLINK with OP_UNSUPPORTED

Without a Readlink handler pkg/sftp sends READLINK to Filelist with
Method "Readlink", and listDir listed the path: a folder answered with
its first child's name as the link target, and a file or symlink with
NO_SUCH_FILE. Answer it, and any other method Filelist does not serve,
with OP_UNSUPPORTED like SYMLINK and hardlink.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 10:36:56 -08:00
7c41ed0635 kms: swap a reload's providers in as a whole, after S3 parses its identities (#13344)
* kms: build every provider before a reload swaps them in

A reload replaced the providers one at a time, closing each old instance
as its replacement went in, and kept the providers and bucket mappings
the config no longer listed. Between closing the old default instance and
setting the new global provider, S3 could get the closed instance. A
reload now builds every provider first and swaps the whole set in at
once, along with the default, the bucket mappings and the global
provider. The default provider failing still fails the reload, and then
nothing changes. Any other provider that fails keeps its previous
instance. Providers the config no longer lists are dropped, and a bucket
mapped to one falls back to the default. A manager other than the global
one no longer sets the global provider. The manager no longer keeps the
provider configurations, which nothing read. Each load health-checks
every provider once, after the swap, for filer.toml as for the identities
file.

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

* s3api: parse the identities before loading KMS

Loading the S3 config loaded KMS before parsing the identities, so a file
whose identities didn't parse still replaced the KMS providers. A file
without a kms block left the previous providers in place, and one with a
number out of float64 range, which protojson accepts, skipped KMS without
an error.

The identities are now parsed first, and a file that fails there changes
neither. A file without a kms block drops the providers, so a reload that
took the block out turns SSE-KMS off. A file encoding/json can't read
fails the KMS load with an error that doesn't quote it, as it could quote
key material. A KMS load that fails is logged as an error, not a warning.

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

* kms: skip a bucket mapping with an empty bucket name

SetBucketKMSProvider refused an empty bucket name, which the rebuilt
mappings no longer went through.

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

* kms: check a rejected load leaves the installed provider open

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-12-03 10:34:45 -08:00
Chris LuandClaude Opus 5.5 f1562aa130 filer: keep a child's chunks in a recursive delete when its rule retains them (#13338)
* filer: keep a child's chunks in a recursive delete when its rule retains them

A recursive delete batched each child file's chunks and checked only the
deleted directory's disableChunkDeletion, so a file under a more specific
rule lost chunks that deleting it alone keeps. Check the child's own rule,
the one that already decides its fsync.

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

* filer: assert which chunk a recursive delete queues under a retaining child rule

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:34:03 -08:00
1858665311 util/http, operation, topology: give the DELETE helpers a deadline (#13333)
* util/http, operation, topology: give the DELETE helpers a deadline

Delete and DeleteProxied made their request without a context and read
the whole answer. Only the shared client's 30 s response header timeout
bounded them, and nothing bounded an answer whose body never ends.

- The cleanup after a failed chunk upload (deleteChunkFromHolders, used
  by PutObject and every chunked upload) asks the holder that just
  failed the write, often the one that stalls. A holder that did not
  answer held the upload for 30 s per holder and attempt, with the
  chunk's buffer. One that sent its headers and stalled held it for
  good, and the holders after it were never asked. Each delete is now
  bounded by cleanupDeleteTimeout (10 s), as the copy path's cleanup is
  by copyCleanupTimeout (#13297). A delete that runs out is logged and
  leaves the needle, as a failed delete did before.
- A delete forwarded to a replica that does not answer held the
  primary's DELETE for 30 s, while a forwarded write fails at
  replicaRequestTimeout. The delete forward now has the same bound, as
  the Rust volume server's replica_request already gives deletes. Its
  timeout is counted as a timeout, through replicaDeadlineError, which
  the write forward uses as well.

Delete and DeleteProxied take a context. benchmark and the unmaintained
repeated_vacuum pass context.Background().

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

* topology: let a replica's failure leave the other replica deletes running

DistributedOperation cancels its context when the first replica fails, and
the delete deadline was derived from it, so a sibling's failure could cut
the deletes to the other replicas short. The old context-free Delete kept
them going, and they must: the needle is gone on this server already, so
a replica that is not asked keeps its copy. Each delete now takes its
deadline from context.Background().

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

* topology: read the replica delete bound once, before the fan-out

A replica delete that outlives ReplicatedDelete read the package bound
again after its answer, racing a later caller that changes 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-12-03 10:33:02 -08:00
370fd46ed9 filer/elastic: report a failed read as an error, not as a missing entry (#13334)
* filer/elastic: report a failed read as an error, not as a missing entry

FindEntry returned filer_pb.ErrNotFound for any error from Elasticsearch
other than not-found, so a lookup that timed out or met an unavailable
cluster answered that an existing entry was gone. It now returns the
error, as #13287 and #13289 made the TiKV, MongoDB, ArangoDB and RocksDB
stores do.

KvGet reported a value it could not decode as missing. It now returns the
decode error.

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

* filer/elastic: keep a top-level directory whose lookup failed

DeleteEntry looked up a top-level entry to decide whether to drop its
index, and treated a failed lookup like a file: it deleted the entry and
left the directory's index behind. Return the lookup error instead, so the
delete fails and a retry drops the index.

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-12-03 10:32:34 -08:00
5dafe56a63 mount: let SEEK_DATA and SEEK_HOLE see data that is not in the chunks (#13335)
* mount: let SEEK_DATA and SEEK_HOLE see data that is not in the chunks

Lseek searched only the file's uploaded chunks. Writes not uploaded yet,
inline content and the data of a remote file that is not cached are not
in them, so for such a file SEEK_DATA answered ENXIO and SEEK_HOLE found
a hole at the offset. A program that copies by data ranges, such as
qemu-img, takes the data for a hole and writes zeros in its place.

A file whose data is not all in its chunks is now answered as one data
range without holes, as lseek(2) allows: SEEK_DATA returns the offset and
SEEK_HOLE the end of the file. The upload pipeline attaches a chunk
before it counts the upload as done, and writes hold the handle lock
that lseek shares, so a file with no pending upload has all its written
data in its chunks.

Lseek also read the file size without the entry lock, while upload
workers append chunks under it. It now holds the lock for that read.

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

* mount: answer lseek from the chunks of a cached remote file

A remote file keeps its RemoteEntry once cached, so checking only for
RemoteEntry reported every such file as one data range. Use
IsInRemoteOnly, as Read does, so the holes of a cached file are found.

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

* mount: trim the lseek comments

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-12-03 10:31:58 -08:00
Yip LeoandClaude Opus 5.5 34d36e599a mount: drop a directory's listing when the cache refuses an entry update (#13336)
* mount: drop a directory's listing when the cache refuses an entry update

UpdateEntry and UpdateEntryChecked returned the store's error and left
the entry in the local store as it was. The mount uses them to refresh
the other names of a hard-linked file after a link or an unlink
(syncHardLinkSiblings), which only logged the error at V(4). With a full
cache disk the siblings kept their old link count and ctime until their
directory was read again.

A refused update now drops the listing of the entry's directory, as
dropListingsOf does for an event the store cannot take (#13141), so the
next lookup there goes to the filer. The listing is dropped after the
cache lock is released, as dropListingsOf does.

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

* mount: shut the meta caches of the refused update test down

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:30:23 -08:00
5e4b2fc42f docker: one FIPS mode for the Go processes and the Rust binaries (#13296)
* docker: one FIPS mode for the Go processes and the Rust binaries

In the image, Go processes ran with fips140=on by default (#7590) while the
Rust binaries, which take their mode from fips.mode alone, ran with
unrestricted TLS; and WEED_FIPS_MODE=off or strict made every Go process
refuse to start, since the entrypoint's fips140=on did not match.

The entrypoint now states the image's mode once, as
WEED_FIPS_MODE_DEFAULT=on, and gives Go processes the fips140 GODEBUG that
matches WEED_FIPS_MODE, else that default. The Rust binaries use the
default when neither WEED_FIPS_MODE nor fips.mode sets a mode; Go processes
check their GODEBUG against it and refuse to start on a mismatch, naming
WEED_FIPS_MODE as the way to pick another mode. Setting
WEED_FIPS_MODE_DEFAULT empty leaves every process in its own default, as
outside the image.

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

* docker: take the image's FIPS mode from a fips140 the caller sets

GODEBUG=fips140=off, the entrypoint's advice since #7590, made every Go
process exit once the Rust binaries joined the image's mode. The entrypoint
now maps the caller's fips140 to WEED_FIPS_MODE_DEFAULT, so Go and Rust run
in that mode and the old advice keeps working.

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

* docker: say fips.mode alone cannot change the image's FIPS mode

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

* docker: read an empty fips140 as off and debug as on, as Go does

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

* docker: warn when GODEBUG fips140 picks the image's FIPS mode

The entrypoint keeps translating a caller's fips140 into the mode for the
Rust binaries, so existing docker run setups keep starting, but logs that
WEED_FIPS_MODE is the setting that also covers launches without the
entrypoint.

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

* docker: set the FIPS mode after dropping privileges

Running as root, the entrypoint re-runs itself through su-exec, and the
second pass took the fips140 the first pass had exported for the caller's
own, warning on default starts and prepending fips140 twice.

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-12-03 10:29:05 -08:00
D.Maier 8afef5166b sftp: serve reads on read-write opens instead of writing zeros (#13343) 2026-12-03 07:59:06 -08:00
0daa7558e2 filer: propagate HBase and remote child deletion errors (#13328)
* test/s3: FsMkdir no longer fails on its own in the rclone fstests

expected_failures.txt listed the test itself because DeleteBucket answered
BucketNotEmpty at the end of the run. Since #13311 a null delete marker can
be deleted, the bucket ends up empty, and the check has failed on master and
on every pull request the workflow runs for:

  TestIntegration/FsMkdir: now fails only through its subtests, remove it
  from expected_failures.txt

* filer/hbase: propagate errors when deleting directory children

* filer: reclaim HBase chunks after each confirmed row deletion

* filer: return a child's remote delete error from a recursive delete

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

* filer: drop the per-row folder delete store capability

Keep the HBase scan and row-delete errors reaching the caller without a
new FilerStore capability. A store that fails partway through
DeleteFolderChildren leaves already-removed rows' chunks to volume.fsck,
as every non-transactional store already does.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-03 01:15:42 -08:00
f4290b5ec2 kms/local: resolve key and alias ARNs (#13331)
* kms/local: resolve key and alias ARNs

AWS KMS takes a key's or an alias's ARN wherever it takes a key ID or an
alias, and the local provider hands out ARNs in DescribeKey, but it looked
them up as plain names, so an ARN named no key. A local ARN now resolves to
the key or alias it names, in requests, in the keys list's key_id and
aliases, and in CreateKey's aliases. An ARN with an empty key ID names no
key.

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

* kms/local: register a key created by ARN under its key ID

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

* kms/local: refuse a key ARN listed as an alias

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

* kms/local: refuse a key ID that is an ARN of an ARN

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

* kms/local: resolve a key ARN only to the key with that ID

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

* kms/local: create an on-demand key under the ID its ARN names

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

* kms/local: decrypt keeps the key ARN a ciphertext was wrapped under

A key configured by its ARN had that ARN as its ID before key ARNs
resolved, and S3 stored it with each object and compares it with the
ID Decrypt returns.

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-12-03 01:12:44 -08:00
63e15ce1ea kms: take the default provider from the config being loaded (#13332)
* kms: take the default provider from the config being loaded

S3 wraps and unwraps data keys with the default provider alone. Without
default_provider, the loader made the first provider the manager listed
the global one, and the manager still holds the providers earlier loads
listed, so a reload could leave S3 on a provider the config dropped. The
manager's own default, which buckets without a mapping use, was left
unset. The default is now the first provider by name in the config being
loaded, for both. A default_provider that isn't listed under providers
fails the load before any provider changes, where before it could name a
provider left over from an earlier load. With more than one provider and
no default_provider the load logs a warning, as adding a provider whose
name sorts first would switch S3 to it.

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

* kms: load the default provider first and fail the load if it can't be loaded

A load whose default provider failed replaced and closed the other providers first, so S3
could be left on a closed instance of one of them as the global provider.

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-12-03 00:48:29 -08:00
Chris LuandClaude Opus 5.5 a7c1cc32ec s3api: fail closed when the directory marker lock check cannot read the marker (#13326)
* s3api: refuse a directory marker PUT when the existing marker cannot be read

Only a missing marker skips the Object Lock check. Any other lookup
error now fails the request instead of letting mkdir replace a marker
that may be under retention or legal hold.

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

* s3api: create the Extended map before applying upload ACL metadata

A directory extracted from a zip without an owner header reached
applyPutObjectACL with a nil Extended map and panicked.

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

* s3api: refuse extracting over a marker that cannot be read

The zip extract mkdir path had the same fail-open lookup as the
directory marker PUT; a failed read now reports InternalError for the
member.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:51:58 -08:00
Chris LuandClaude Opus 5.5 d6d5e99f9b s3api: limit service account keys to their stored actions (#13325)
* s3api: limit service account keys to their stored actions

A service account created with an action subset authenticated as its
parent and was authorized with the parent's full permissions. Map each
restricted service account key to a copy of the parent that carries the
subset as a boundary, and check it in the S3, bucket listing and IAM
authorization paths. An empty action list still inherits the parent.

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

* s3api: drop restricted service account keys with their removed parent

RemoveIdentity only dropped keys that mapped to the parent itself, so a
restricted service account key, which maps to its own bounded copy, kept
authenticating after the parent was deleted.

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

* sts: keep restricted service account keys out of their parent's roles

A named role is admitted by its trust policy alone, so a service account
key limited to Read could assume any role trusting its parent and use the
role's permissions. Require the key's action subset to allow
sts:AssumeRole.

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

* s3api: let a service account's scoped upload listing grant pass its boundary

The upload and part listing routes are authorized as Read, and the
legacy path falls back to the listing grant. The boundary check now does
the same, so a service account limited to ListBucketMultipartUploads can
still list uploads without being allowed object reads.

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

* sts: refuse self sessions for restricted service account keys

AssumeRole without a RoleArn and GetFederationToken issue sessions that
carry the caller's own policies, which for a service account are its
parent's. A restricted key would shed its action subset that way, so
refuse both for it.

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

* sts: give the restricted service account role test its own role

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

* s3api: check a restricted key's parent grants apart from its boundary

The boundary is checked against the request first, so the legacy action
check only has to cover the parent's grants. Checking the boundary there
again without the request denied a Read parent's upload listing to a key
limited to ListBucketMultipartUploads.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:50:44 -08:00
Chris LuandClaude Opus 5.5 515b905011 s3notification: lose the test lock on the fetch of the records' partition (#13324)
TestALeadThatLostItsLockDoesNotSend dropped the forwarder lock on the
first fetch of any partition, then waited for a fetch of partition 0.
When another partition's goroutine fetched first, the lead stopped before
partition 0 was fetched and the wait timed out (seen on the 32-bit job).
The hook now gets the request and drops the lock on partition 0's fetch.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:47:50 -08:00
1606fe4f39 operation: resend an upload that hits a broken pipe on a stale connection (#13322)
* operation: resend an upload that hits a broken pipe on a stale connection

A pooled connection the server has closed fails an upload in one of three
ways, depending on when the close reaches the client. Two of them, a reset
and a closed connection, already get the request resent once with its body
rewound. A broken pipe did not.

A volume server closes a connection idle for 30 seconds and the client keeps
idle ones for 90, so a request that reuses a connection as it turns 30 seconds
old races with the close. The forward of a write to a replica makes a single
attempt: there the write failed with a 500, and the needle already stored on
the primary stayed on that one replica.

* seaweed-volume: resend a replica forward that hits a reset on a stale connection

The Rust replica forward made one attempt, so a pooled connection the peer
closed at its idle timeout failed the write with a broken pipe or a reset,
as the Go forward did before. Resend it once on a new connection, as Go's
upload_content does.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 23:47:12 -08:00
Chris LuandClaude Opus 5.5 2f300c2969 s3api: keep the in-flight upload counters 64-bit aligned on 32-bit (#13321)
The recursiveListDeclined sync.Map placed ahead of inFlightDataSize and
inFlightUploads moved them off 8-byte alignment on 386, so the first
throttled upload panicked with "unaligned 64-bit atomic operation".
atomic.Int64 is aligned wherever it sits in the struct.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:46:20 -08:00
006885232e master: start file ids past the ones a previous master may have handed out (#13320)
* master: start file ids past the ones a previous master may have handed out

The file id sequence lives in memory. A master that starts, or takes over
as leader, continues it from what the volume servers report: the largest
needle id each of them holds. That is the largest id written, not the
largest one handed out, so the ids of uploads that had not landed when the
previous master was lost are handed out a second time.

Two uploads then hold one needle id in one volume with different cookies.
The one that lands second is refused, and deleting its file id, which goes
by needle id, removes the needle of the other: a file the filer had
answered 201 for lost its chunk on every replica that way.

A volume server's first report to a master now sets the sequence past its
largest needle id by a margin instead of right after it. Later reports
count as before, and a server that holds nothing adds no margin.

* master: shorten the unwritten file id margin comments

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

* master: record the file ids handed out through raft

Starting a margin past a volume server's first report does not hold for
two masters lost in a row: with nothing written in between, the second one
gets the same report and hands out the same id.

The master now records through raft how far it may hand file ids out
before it does (MaxVolumeIdCommand.FileIdCeiling, a step of 2^20 ids at a
time), and every master moves its sequence past what another one recorded,
from the log or from a snapshot. An id goes out only when it was drawn
under a ceiling this master recorded itself: recording one applies what
the masters before recorded first, so an id drawn after that is past all
of theirs, and one drawn before it is dropped.

A master that does not know the field ignores it. Snowflake ids are made
from the clock and are left alone.

* master: leave room for a file id draw larger than the ceiling step

A draw of more ids than fileIdCeilingStep never fit under the ceiling
recorded after it, so the assignment kept recording ceilings through raft.
The record now covers the dropped draw and the next one, and a count past
2^32 is refused before the additions can wrap.

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

* master: tell a recorded file id ceiling apart from another master's

A master that took over could propose the same ceiling the one before it
recorded and it had not applied yet. Applying that entry then looked like
applying its own, so its sequence stayed below ids the other master had
handed out. Each record now carries an id of the master process, and only
an entry with that id and value leaves the sequence where it is.

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

* master: charge assigned bytes only once the file id is recorded

An assignment that failed to record its file ids kept the bytes charged to
the volume, which could mark a volume near its limit full for an upload
that never came.

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

* master: move the sequence before publishing a file id ceiling

An assignment that loaded a ceiling another master recorded, before the
sequence had moved past it, could draw an id below it when this master had
proposed the same value.

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

* master: test that a failed file id record charges the volume nothing

The order c40e01786 set. Before it, an assignment that could not record its
file ids left the volume charged for them: 1 MB for an id never handed out.

* sequence: stop the memory sequencer at the largest file id instead of wrapping

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

* master: refuse a file id draw whose ceiling would wrap past the largest id

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 23:45:31 -08:00
217795e34c Continue prefix listings on unordered filer stores (#13330)
* filer: continue prefix listings on unordered stores

* test/s3: FsMkdir no longer fails on its own in the rclone fstests

expected_failures.txt listed the test itself because DeleteBucket answered
BucketNotEmpty at the end of the run. Since #13311 a null delete marker can
be deleted, the bucket ends up empty, and the check has failed on master and
on every pull request the workflow runs for:

  TestIntegration/FsMkdir: now fails only through its subtests, remove it
  from expected_failures.txt

(cherry picked from commit b248167800)

* filer: read unordered stores in full pages when filtering a prefix

An unordered store can have to be read to its end for a prefix, and
reading it in pages of the caller's limit (max-keys + 2 for S3) turned
one listing into a store query per few entries.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 23:31:01 -08:00
MapleWhiteZZZandMapleWhiteZZZ 390c5acc00 test/s3: FsMkdir no longer fails on its own in the rclone fstests (#13323)
expected_failures.txt listed the test itself because DeleteBucket answered
BucketNotEmpty at the end of the run. Since #13311 a null delete marker can
be deleted, the bucket ends up empty, and the check has failed on master and
on every pull request the workflow runs for:

  TestIntegration/FsMkdir: now fails only through its subtests, remove it
  from expected_failures.txt

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
2026-12-02 23:29:28 -08:00
github-actions[bot] 605b5f7f79 docs: regenerate star history chart 2026-12-03 01:53:42 +00:00
Chris LuandClaude Opus 5.5 3c9bdaca86 sftp: create uploaded files 0644, keep modes on overwrite, and support put -p (#13319)
* sftp: create uploaded files with mode 0644

The upload writer carried a 0644 mode that never reached the filer, so the
PUT fell back to the filer default of 0660. Pass the mode on the PUT, as
OpenSSH's sftp-server creates new files 0666 minus a 022 umask.

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

* sftp: keep an existing file's mode when an upload overwrites it

An overwrite went through the same PUT as a new file, so a 0600 file came
back with the default mode. Send the stored mode instead, as open(2) on an
existing file keeps it.

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

* sftp: apply an fsetstat sent while an upload is still buffering

"put -p" sets the mode and times on the open handle before closing it, but
the upload only reaches the filer on close, so the setstat found no entry and
the client failed with "No such file or directory". Keep such attributes on
the open upload: a size cuts the buffered bytes, the mode goes on the PUT,
and the rest is set once the file is stored.

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

* sftp: clear the sub-second part of an mtime a setstat replaces

SFTP times are whole seconds, but the stored nanoseconds of the old mtime
stayed, so a touched or "put -p" file showed a time the client never set.

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

* sftp: set the attributes queued on an upload in its post-upload update

A new file can be under its bucket's default retention as soon as the PUT
stores it, and a setstat after that is refused, so "put -p" into such a
bucket stored the file and then failed the close. Apply the queued
attributes in the update that already sets the owner after the upload.

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

* sftp: leave a setstat alone when two uploads share its path

A setstat carries only the path, so with two uploads of one path open in a
session it went to whichever opened last, and a size cut the other upload's
bytes. Route it to an upload only when that upload is the only one open.

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

* sftp: fail the close when an upload's queued attributes are not stored

The setstat already answered success, so a failed post-upload update was
only logged and "put -p" lost the times without the client knowing.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:56:45 -08:00
5038508fd9 shell: volume.fsck says how many chunks its cutoff left out of the missing-chunk check (#13318)
* shell: volume.fsck says how many chunks its cutoff left out of the missing-chunk check

volume.fsck -findMissingChunksInFiler leaves out every filer chunk written
within -cutoffTimeAgo, five hours by default, and did not say so. Run after
volume servers lost power, it found nothing missing for exactly the files
at risk: the ones written last.

The check now counts the chunks it leaves out for the cutoff and ends with
one line that gives the number and points at -cutoffTimeAgo. The default
cutoff stays, and the orphan check is not touched.

* shell: volume.fsck counts only the chunks its run would have checked

The walk reads the whole filer, so a recent chunk on a volume that
-volumeId or -collection left out of the run was counted too, and the
report said a shorter cutoff would check it. Count a chunk only when its
volume is one of the run's, or one the master does not list and -volumeId
does not leave out, which is what the check itself looks at.

* shell: volume.fsck applies -modifyTimeAgo before counting chunks the cutoff left out

A chunk older than -modifyTimeAgo is not checked at any cutoff, so it
does not belong in the count a shorter -cutoffTimeAgo would check.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 14:21:42 -08:00
MapleWhiteZZZandMapleWhiteZZZ a89971ff66 filer: delete the chunks a failed copy wrote (#13316)
* filer: delete the chunks a failed copy wrote

A copy through the filer (POST dst?cp.from=src) writes the destination's
chunks first and its entry last. When it ended before the entry was written
(the client gave up, a chunk failed to copy, the entry write failed), the
chunks already on the volume servers stayed there, with no entry to
reference them and nothing to delete them.

The fan-out now waits for the copies it started, starts no further one
after a failure or once the request has ended, and deletes what the
completed ones wrote. A chunk copy that fails deletes the file id it was
assigned, as a failed write can still have stored the needle. A failed
entry write deletes only the chunks the destination does not hold, since
CreateEntry can fail after storing the entry.

#13217 did the same for the S3 copy paths.

* filer: keep the copied chunks when the entry write fails

CreateEntry can fail after it stored the entry: the entry stays when only
its parent folders could not be created. Reading the destination afterwards
does not settle whether the chunks are live, since an entry that was stored
may have been renamed by then, and deleting on a miss would take its data.

So a failed entry write keeps the chunks, as it did before. Only the
failures that come before the entry write delete what the copy wrote.

* filer: fail a copy whose request ended after its last chunk

A request cancelled once every chunk copy had returned still handed the
chunks on, to an entry write that the cancelled context then fails, and
that write keeps them. The end of the request now fails the fan-out
whether or not a copy was left to start, so the chunks are deleted there.

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
2026-12-02 14:10:27 -08:00
ca4e568832 volume.check.disk: resurrect needles a vacuumed replica provably never had (#13304)
* volume.check.disk: resurrect needles a vacuumed replica provably never had

-resurrectMissingNeedles copies a needle that is live on one replica and
absent on the other only into a replica that was never vacuumed: a vacuum
erases deleted needles together with their delete markers, so on a
vacuumed replica an absent needle may be a delete. Once every replica has
been vacuumed, a replica that lost writes, the tail of its volume after a
crash for one, has no repair but copying the whole volume.

A vacuum erases only among the needles the index holds when it commits.
The volume now records the largest needle id it held then, deleted ones
included, in its .vif (VolumeInfo.vacuumed_max_file_key), before the
vacuumed files replace the old ones. A needle with a larger id that the
replica has no index entry for was never deleted there, since no vacuum
has touched its marker: it was never written there. volume.check.disk
-resurrectMissingNeedles reads the record with the compaction revision
and copies such needles back; absent needles up to the recorded id are
left alone as before.

The record is only good if no vacuum went unrecorded, so it starts at a
volume's first vacuum and is kept through each one after it. A volume
vacuumed before it had a record never gets one and keeps the present
rule. A copy of a volume takes the record along in the .vif.

* volume.check.disk: look at vacuumed replicas whose live counts match, and judge only what stays unrepaired

Two replicas at different compaction revisions with equal live counts were
skipped under -resurrectMissingNeedles when both had been vacuumed, since
neither could take a needle back. One that recorded its vacuums can, and a
missed write plus a missed delete leave the live counts equal. Under the
flag such a pair is now compared.

A run without -apply ends with a verdict on the needles one replica has
and the other lacks. It counted the ones the run would have resurrected
with -apply, so two replicas each missing needles above the other's
recorded id were called a split brain not to be repaired. Needles above
the recorded id of the replica lacking them are left out of the verdict.

* volume: trust the vacuum record only at the revision it was written for

A vacuum by a volume server that does not keep vacuumed_max_file_key (an
older Go one, or the Rust one) erases delete markers above the record but
leaves the .vif as it was. Once a server that reads the record serves the
volume again, volume.check.disk -resurrectMissingNeedles takes those ids
for missing writes and raises deleted needles.

The record now names the compaction revision its vacuum produced. It is
saved after the swap, so a vacuum that fails to record it leaves a
revision that no longer matches, and check.disk and later vacuums only
take it up while it equals the volume's live revision.

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

* volume: number the vacuum record fields 12 and 13

VolumeInfo 10 and 11 already carry other bool fields in a downstream
build. A volume server of that build answering ReadVolumeFileStatus would
read here as vacuumed_max_file_key 1 at revision 1, a record that lets
check.disk resurrect every absent needle. The .vif is keyed by name, so
only the wire numbers move.

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

* volume(rs): record the largest needle id a vacuum could have erased

Mirror the Go volume server: VolumeInfo carries vacuumed_max_file_key and
the compaction revision it was taken at (fields 12 and 13). commit_compact
keeps the record through every vacuum once the volume has one, saves it
after the swap, and drops it once a vacuum went unrecorded.

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

* volume(rs): keep the ids of cut tail needles in the decoded index

The EC decoder dropped the .idx row of a deleted needle past the decoded
.dat, so the compaction that follows recorded a vacuumed max needle id
below it. volume.check.disk -resurrectMissingNeedles could then copy that
deleted needle back from a stale replica. Write the row as a tombstone
without the offset instead, as Go keeps every .ecx row.

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

* volume(rs): count tombstone keys toward the max file key on redb loads

metrics_from_idx skipped the max-key update for tombstone rows, unlike
Go's needleMapMetricFromIndexFile and the in-memory replay. A deleted
tail needle then left a redb volume's vacuum record below its id.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 14:08:37 -08:00
Chris LuandClaude Opus 5.5 add9d60378 s3api: list a versioned key whose .versions folder streams past the page (#13317)
* s3api: list a versioned key whose .versions folder streams past the page

A key's .versions folder sorts after the longer keys it prefixes:
"a.pom.versions" follows "a.pom.sha1.versions" although the key
"a.pom" sorts before "a.pom.sha1". A ListObjects page that filled in
between returned the longer key and resumed past the folder name, so
the shorter key was never listed.

When a versioned page is truncated, look up the .versions folder of
each proper prefix of the page's last item that would still stream
after it, add the live keys found, drop as many items off the end,
and resume from the last key kept instead of a .versions folder name.

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

* s3api: test versioned listing pages that end between a key and its .versions folder

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

* s3api: test encoded versioned listing pages with spaces and plus signs

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

* s3api: keep recovered versioned keys in raw key order

Encoded keys do not sort like raw ones ("a%20b-1/x" before "a+b"), so
a key recovered past the page boundary is placed by its raw key before
the page is trimmed.

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

* s3api: order a versioned page by raw key when listing with encoding-type=url

The in-page insert compared encoded keys, which sort differently from
raw ones once a directory and a file name escape a space differently.

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

* s3api: test encoded directory keys at a versioned page boundary

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

* s3api: scan raw keys when retracting a delete-marked null object

The page is now ordered by raw key, so the backward scan that finds the
null object to retract stops on raw keys too.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:52:05 -08:00
Chris LuandClaude Opus 5.5 8a6c948b12 s3api: delete a null delete marker named by versionId=null (#13311)
* s3api: split the .versions file delete out of deleteSpecificObjectVersion

deleteVersionFile deletes a version stored under .versions and repoints
the latest pointer past it. deleteSpecificObjectVersion keeps "null" as
the plain object entry, which the suspended delete and lifecycle paths
rely on, and calls deleteVersionFile for every other version id.

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

* s3api: delete a null delete marker named by versionId=null

A suspended-versioning delete stores its marker as .versions/v_null, but
DELETE ?versionId=null only looked at the plain object entry. With no
null object there, it answered 204 without x-amz-delete-marker and left
the marker in place, so the bucket could never be emptied.

When the plain null object is missing and a null marker exists, delete
the marker file and repoint the latest pointer to the prior version.
The routed specific-version delete leaves that case to the lock path,
which already handles batch deletes the same way.

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

* s3api: order the repoint past a deleted null delete marker by the versions left

A null delete marker's id has no format, so the routed version delete
read the recompute order from the first remaining version file.

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

* s3api: delete a null delete marker on the key's owner

The marker is read from the owner, so deleting it through the gateway's
own filer could answer success while the owner kept it. Both the routed
DELETE and the lock path delete it with a routed transaction instead.

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

* s3api: rank the versions left by time when deleting a null delete marker

Mixed legacy and inverted ids made the first file name a wrong guide to
the repoint order. The routed delete now finds the newest remaining
version and picks the name order that reaches it; when neither end of
the order is the newest, it leaves the delete to the lock path.

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

* s3api: keep only the ends and the newest while scanning for the null marker repoint

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

* s3api: choose the null marker repoint from the owner's own listing

A filer other than the key's owner can lag it, and the recompute runs over
the owner's full directory, so a direction picked from a replica's partial
listing could repoint the object to an older version. Scan .versions on the
owner only; when the owner cannot answer, leave the delete to the lock path.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:18:23 -08:00
3764534dd1 kms: read filer.toml and the identities file with one parser (#13313)
* kms: read filer.toml and the identities file with one parser

The KMS settings from filer.toml and from the identities file went through
two paths: the JSON one was wrapped in an adapter so it could be read like
viper. Both are now parsed into the same settings and loaded by the same
code. Viper lowercases the provider tables in filer.toml but not the values
that name a provider, so a mixed-case default_provider or bucket provider
never matched and failed the load. Those values are now lowercased for
filer.toml. Providers load in name order, a providers or buckets section
that isn't a table fails the load instead of being ignored, and so does a
default_provider that isn't a string.

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

* kms: test the parser's section types and JSON provider names

A providers or buckets section that isn't a table and a default_provider
that isn't a string fail the parse, and a JSON config keeps the case of
the provider names it uses. The check-once test now loads through the
whole loader, which sets the global provider, so it clears it after.

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

* kms: pick the first provider by name when no default is set

ListKMSProviders iterated the provider map, so with several providers
and no default_provider the global SSE-KMS provider changed between
loads, and objects written under one could not be read after a restart.

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

* s3api: report KMS load errors from the identities file

Any failure loading the identities file's kms block was logged at V(2)
as no KMS configuration, which hid the parser's errors and a
default_provider that does not exist. Only a missing block is quiet 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-12-02 13:16:52 -08:00
a16ca18ae0 kms/local: load master keys from the provider config (#13312)
* kms/local: load master keys from the provider config

The local provider generated its master keys in memory, so a restart or a
reload lost them, and with them every object they encrypted. It now reads a
keys list from its config. Each entry has a key_id, 32 bytes of key_material
in hex or base64, and optional aliases and description. A reload reads the
list again, so objects encrypted under a listed key stay readable.

A name that's already taken, key material that isn't 32 bytes, or
enableOnDemandCreate together with keys fails the provider, and the keys it
loaded before the error are cleared. No default key is generated when keys
are listed, since whatever it wrapped would be lost on a restart. CreateKey
and CreateKeyWithID refuse a name that's taken instead of replacing that key.

GetStringMap copies a list of tables like the other nested values it hands
out.

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

* kms/local: give a racing on-demand request the key the first one created

CreateKeyWithID refuses a key ID that's taken now, and the on-demand path
looked the key up and created it under separate locks. Two requests for
the same new key could both miss it, and the second then failed with
KMSInternalFailure. The on-demand path checks for the key under the lock
it stores it with, and returns the one stored in the meantime, so the
first request's data key stays readable.

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

* kms/local: serve requests that name no key with the configured aws/s3 key

With keys configured there is no generated default key, so an SSE-KMS
request without a key ID failed even when the bucket-default path
(which already resolves to alias/aws/s3) would work. Resolve an empty
key ID to alias/aws/s3, as AWS does, so an operator picks the default
by giving a configured key that alias instead of a new setting.

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

* kms/local: refuse a master key that Close cleared mid-request

A reload replaces the provider and closes the old one, which zeroes its
key material in place. A request that looked up a key before the close
could then build its cipher from zeros and store a data key no provider
can unwrap. Build the cipher under the provider lock and refuse a key
that is no longer registered.

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-12-02 13:14:11 -08:00
2938037cae filer: end a subscriber's stall when memory serves its cursor (#13310)
* filer: end a subscriber's stall when memory serves its cursor

A metadata subscriber that finds nothing in the ring yet parks until data
arrives ("no readable in-memory entries yet"), which starts its stall
clock. When data arrives the ring serves the cursor and the read goes on,
but nothing stopped the clock: only the paths that leave a gap do.

The clock is what bounds the wait on a gap. With it still running from
that first park, the first real gap the subscriber meets, hours later,
looks older than maxGapStall the moment it parks: the park gives up at
once and skips to the eviction watermark, and the events a peer would have
flushed within the flush interval are never delivered. The log shows a
subscriber "parked" for hours at a cursor a few seconds old, and the gap
skipped in the same millisecond. A mount keeps the stale listing it has
for those events, and filer.sync loses them.

resolve now ends the stall when it sends the read to memory.

* filer: age the first stall in the memory-serves test instead of shrinking maxGapStall

With maxGapStall at 50ms, a scheduler pause between the fresh park and its
give-up check expired the new stall and failed the test against the fixed
code. Keep the real bound and backdate the first park's clock.

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

* filer: shorten the comment on ending the stall in resolve

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 13:12:20 -08:00
Chris LuandClaude Opus 5.5 c7ba8bd079 sftp: give user store accounts without a Uid a non-root id (#13309)
* sftp: give user store accounts without a Uid a non-root id

An entry that leaves out Uid decoded to 0, and Uid 0 skips every
Permissions check, so a read-only account could write and delete.
Generate a regular id for it the way NewUser does, and default an
omitted Gid to the Uid.

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

* sftp: test that an omitted Uid or Gid does not load as root

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

* sftp: keep the default Uid of an account stable across loads

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

* sftp: test that a default Uid survives Reload and a new store

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

* sftp: keep a default Uid off the ids other accounts use

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

* sftp: test that a default Uid skips ids other accounts use

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

* sftp: refuse a user store with no free id for an omitted Uid

When every id in the default range is taken, loadUsers now fails instead
of reusing a taken id, and it fails before replacing the loaded users so
a Reload keeps the previous accounts.

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

* sftp: test that a full id range rejects the store and keeps old users

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:49:44 -08:00
b445228794 volume: read the fields it knows from a .vif a later version wrote (#13305)
* volume: read the fields it knows from a .vif a later version wrote

The .vif is parsed as strict JSON, so one field this version does not
know fails the whole file. The volume server only logs that and serves the
volume with an empty VolumeInfo: a read-only mark is gone, and so is the
remote file of a tiered volume. Every field added to VolumeInfo makes the
.vif files written from then on unreadable to the versions before it, which
is what a rollback runs into.

When neither the strict parse nor the old format's reads the file, it is
now parsed once more with unknown fields ignored. The fields this version
knows apply, and a warning names the file. The old format is still tried
first, since read this way it would lose its DestroyTime, and a file that
is not a VolumeInfo is still an error.

* volume(rs): read an old-format .vif before the current format

VifVolumeInfo ignores fields it does not know, so an old-format .vif
parsed as it too: its DestroyTime and BytesOffset were dropped and the
old-format fallback never ran. The Go server tries the old format before
reading a file with unknown fields ignored, which keeps the destroy time.
The old format is now taken only when every field in the file is one of
its own, and a file that is not old-format reads as before.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 12:48:05 -08:00
d05cb0d308 volume: keep the largest needle id of a leveldb-indexed volume through a vacuum (#13306)
* volume: keep the largest needle id of a leveldb-indexed volume through a vacuum

The index a vacuum builds for a volume with a leveldb needle map is loaded
by LevelDbNeedleMap.DoOffsetLoading, which counted the files and tracked
the end of the data but not the largest needle id, as the in-memory map's
loader does. After the commit the volume reported 0 as its largest id until
a needle with a larger one was written, and after each vacuum again.

The volume server sends the largest id over its volumes in every heartbeat,
and the master keeps its id sequence above it. A server whose largest ids
sit in volumes that were vacuumed since they were last written reported too
small a value, which is all the master has to go by when its own sequence
is behind.

* volume: test the largest needle id when nothing lands during the vacuum

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 12:45:23 -08:00
d0b431b192 filer: pace the deletion ledger's snapshots to a byte budget (#13301)
* filer: pace the deletion ledger's snapshots to a byte budget

The durable deletion ledger is written as a snapshot of the whole pending
set, and the snapshotter is woken by every queued and every finished
delete. A filer deleting a hundred chunks a second rewrote the set a
hundred times a second, close to 4KB written to the store per deleted
chunk. The cost of each snapshot is the size of the set, so a filer that
holds deletes it cannot finish yet, the ones it retries, rewrote that whole
backlog on every other change as fast as the store took it.

A snapshot is now followed by a pause in proportion to the bytes it wrote
(filer.deleteQueue.persistBytesPerSecond, 64KiB a second by default, and
4KiB charged per snapshot), never longer than the periodic interval. The
first change after a quiet spell is still written at once; the changes made
during the pause go into the next snapshot. A crash therefore loses the ids
queued since the last write instead of those of the write in flight.

* filer: fix the deletion ledger's write budget instead of a config key

The pacing needs no operator knob: 64KiB a second keeps a large backlog's
snapshots at the periodic interval and a small ledger's at a few a second.
The snapshotter reads the budget and the interval once when it starts, so a
test that pins the budget does not race a running snapshotter.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 12:16:02 -08:00
75ba2b125c filer: count the store's KV requests in the store metrics (#13302)
* filer: count the store's KV requests in the store metrics

FilerStoreWrapper counts and times InsertEntry, UpdateEntry, FindEntry,
DeleteEntry and the listings, but passed KvPut, KvGet, KvBatchGet and
KvDelete straight to the store. Hard link records, the deletion ledger and
the per-path commit records are all kept in KV, so that part of what a
filer asks of its store did not show in SeaweedFS_filerStore_request_total
or in the request duration histogram.

The four KV calls are now counted and timed like the others, as kvPut,
kvGet, kvBatchGet and kvDelete.

* filer: shorten the KV metrics helper comment

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-12-02 12:14:38 -08:00
Chris LuandClaude Opus 5.5 5c36ee70ee master: sign a LookupVolume token for the file id asked for (#13300)
* master: sign a LookupVolume token for the file id asked for

LookupVolume signed the token with the bare volume id, and the volume
server checks the token's fid against vid,key, so every token it handed
out was refused. /dir/lookup signs the file id. operation.LookupJwt goes
through LookupVolume, so the expired-token renewals of the S3 PutObject
and copy cleanup deletes, the admin file browser and weed benchmark all
got a token the volume server refused.

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

* master: sign lookup tokens for the base file id

The volume server checks a token's fid against the file id with its
_<delta> suffix stripped, so a token minted for vid,key_N, over gRPC or
/dir/lookup, was refused. Sign baseFid of the file id in both paths.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:13:16 -08:00
Chris LuandClaude Opus 5.5 dc15685282 filer: rename a postgres_flat scan test bucket codespell flags (#13314)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:13:00 -08:00
Chris LuandClaude Opus 5.5 ae99aae2cb mq: report the caller's deadline when a broker sees it first (#13303)
* mq: report the caller's deadline when a broker sees it first

doConfigureTopic checked ctx.Err() to tell the caller's deadline from a
broker failure. A broker's DeadlineExceeded status (or its RST_STREAM,
which gRPC maps to DeadlineExceeded once the deadline has passed) can
arrive before the context's own timer has run, so ctx.Err() was still nil
and NewTopicPublisher returned the wrapped gRPC error instead of
context.DeadlineExceeded. Once the deadline is behind us, wait for the
context's timer before reading ctx.Err().

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

* mq: let the configure call start before its deadline passes in the test

The deadline the test reported had already passed when NewTopicPublisher
started, so the check before the first broker caught it and the check after
the call was never exercised. The fake broker now moves the deadline behind
us only once it has the call, and answers with its own DeadlineExceeded.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:12:07 -08:00
Chris LuandClaude Opus 5.5 f599f870a8 s3: list without a delimiter from one range of the filer store (#13263)
* s3: -s3.listRecursiveFromStore, on by default

Lets an operator keep recursive listings on the directory walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3: list without a delimiter from one range of the filer store

A bucket that never had versioning is listed with ListEntriesRecursive:
one read of the bucket's path range per page instead of one directory
listing per directory. A folder object's "<dir>/" key waits for its place in
key order, and the folder objects whose rows sort before the range (the one
the prefix names, those the marker ends inside of) are looked up. .uploads
is skipped; a .versions folder hands the page to the walk, as does a filer
that answers Unimplemented, which is then not asked again for a minute.

The test pages through both ways over the same tree, for prefixes, markers
and page sizes, and expects the same keys, sizes, ETags and markers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: a range-read gateway lists what the walking one does

A second S3 gateway with -listRecursiveFromStore=false runs on the same
filer. ListObjectsV2 and V1 pages agree for prefixes, markers and page sizes
over folder objects, a prefix object, an unfinished upload and +/-/0
neighbours. Listing 60 keys five directories deep scans the bucket table 2
times from the range read and 302 times from the walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* s3: range-read listings without the -s3.listRecursiveFromStore flag

A filer whose store cannot list a range answers Unimplemented and the
gateway already walks that bucket's directories instead, so the flag only
switched off a path that falls back by itself. The unit test forces the
walk through the decline cache, and the postgres_flat test checks pages
against the keys in byte order rather than against a second gateway.

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

* s3: step a range-read listing over the bucket's upload parts

The walk skips the bucket's .uploads folder as one entry, but a range read
from the bucket root streamed every part of every unfinished upload and
dropped them, one 1024-row window after another, on each first page.
Every path under .uploads/ sorts before ".uploads0", so the read resumes
there and looks up the one key with that name.

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

* s3: list a waiting folder object once a row passes its key

A range-read page queued every childless folder object until a file row
arrived, so max-keys=1 over a bucket of empty folders read the whole
bucket before answering.

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

* s3: forget a deleted bucket's recursive-listing decline

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:10:19 -08:00
Yip LeoandClaude Opus 5.5 77a070fe0a s3api: tell a symlink apart from an empty object on GET and HEAD (#13299)
A symlink made through weed mount holds no data, so GET and HEAD
answered for it as for an empty file: Content-Length 0 and a type
guessed from its name. An S3 client could not tell it from an empty
file, nor see where it pointed.

For an entry with the symlink mode bit, send the target as user
metadata, x-amz-meta-seaweedfs-symlink-target, escaped like a key under
encoding-type=url, and use Content-Type inode/symlink (what file(1)
reports) when none is stored. User metadata is the one place AWS has for
an object's own fields, so SDKs and the AWS CLI show it as they are. The
link is not followed: the target is a path on the client that made it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:05:12 -08:00
Chris LuandClaude Opus 5.5 acb7728915 filer: ListEntriesRecursive RPC (#13262)
* filer: name the check that a listing expires an entry

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: StreamListRecursiveEntries lists a subtree in path order

It pages through the store's RecursiveLister until the limit, leaves out
and deletes expired entries as a directory listing does, and declines a
subtree in or holding a remote mount.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer.proto: ListEntriesRecursive

A new RPC rather than a field on ListEntries: a filer that predates it
answers Unimplemented instead of listing one directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: serve ListEntriesRecursive

Unimplemented when the store cannot list the subtree in path order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: a scoped token is refused ListEntriesRecursive

Classified with TraverseBfsMetadata: it lists a whole subtree, past the
per-directory checks a scoped ListEntries gets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: trim a trailing slash before checking a recursive listing for remote mounts

An empty directory lists from the root.

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

* filer: keep the recursive listing cursor when a page comes back empty

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:04:27 -08:00
a9d4714aed s3api, filer: keep a symlink a symlink when CopyObject copies it (#13298)
* s3api, filer: keep a symlink a symlink when CopyObject copies it

A symlink made through weed mount is an entry with the symlink mode bit,
a SymlinkTarget and no data. CopyObject builds the destination's
attributes afresh, with the permission bits from the request, so a copy
to another key dropped both and landed as an empty regular file. A
metadata-only self-copy (REPLACE) kept the target but reset the mode,
leaving the link an empty regular file in place.

Keep the symlink mode bit and the target on both paths. The permission
bits still come from the request, as for any other copy. The filer's own
copy (copyEntry) already carries the source's whole attribute set.

A copy into a new prefix creates the symlink in a missing directory, and
the filer gave each parent it created the entry's whole mode plus
ModeDir. With the symlink bit as well, a mount shows those directories
as regular files, and nothing under them can be reached. Parents now
take the entry's permission bits only.

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

* filer: drop the symlink type when promoting an entry to a directory

A key nested under a symlink promotes the symlink's entry to a
directory. The promotion added ModeDir and kept the symlink bit, so a
mount showed the directory as a regular file and could not reach the
nested key. Keep only the permission bits there too, with the same
restorableModeBits a missing parent now takes from its entry.

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

* s3api: keep a self-copied prefix object a directory when it was a symlink

A prefix object promoted from a symlink before the filer change still has
the symlink bit. A routed self-copy of it restored ModeDir and then
keepSymlink added the symlink bit back, leaving a directory a mount shows
as a regular file. keepSymlink now leaves directory destinations alone.

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

* filer_pb: a prefix object keeps no type bit but the directory's

MarkPrefixObject added ModeDir and the execute bits to whatever mode the
object had. A symlink copied onto a key that other keys are nested
under, or a self-copy outside the owner route of a prefix object
promoted from a symlink before the filer change, kept the symlink bit
next to ModeDir, which a mount shows as a regular file. Clear the other
type bits first.

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-12-02 12:04:04 -08:00
85b783cc0d s3api: copy a chunk to another volume when its volume fails the write (#13297)
* s3api: copy a chunk to another volume when its volume fails the write

CopyObject and UploadPartCopy assigned one volume to each copied chunk and
failed the whole copy when that volume failed the write: a streamed copy
sent a single POST, and a buffered copy retried only the same fid.
PutObject asks for a fresh assignment instead (upload_chunked.go), so a
volume that filled up, went away or was overloaded failed a copy that a
PUT would have survived. In production, a CopyObject failed with 500
because the destination volume server broke the connection mid-upload,
and only the client's retry completed it.

Every chunk copy now writes through uploadCopiedChunk: streamed, buffered,
range, and the five SSE re-encryption paths. When a volume fails the write
in a way another volume would not, the copy deletes whatever the failed
write may have stored, asks for another volume and writes the chunk again,
as PutObject does: up to three volumes, and only one more after an
overload. The uploader's errors are judged by
operation.ShouldReassignUpload, and a streamed POST by its status (no
response, a 5xx, or an overload refusal). A streamed retry reads the
source again, and a range copy digests only the bytes of the attempt that
landed. A failed source read is not retried on another volume: a streamed
copy now records the source's read error apart from the POST's.

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

* s3api: delete a failed copy chunk only when its write reached the volume

A streamed copy reads its source inside the write, so a source that could
not be read also came back through uploadCopiedChunk, which then deleted a
fid nothing had been written to. Only a failure of the volume itself
(copyUploadError) is followed by the delete now; the tests check that a
source failure sends none.

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

* s3api: reassign copy writes refused before the append, bound the cleanup

A streamed copy's POST dropped the volume's X-Seaweed-Write-Outcome header,
so a 409 from a volume that turned read-only before the append, or a 401 for
a token that expired in the queue, failed the copy where the uploader's
ShouldReassignUpload tries another volume. The POST now keeps the header and
reassigns on the same marked answers; unmarked 409 and 401 stay final.

The delete of a failed chunk read its answer with no deadline, so a volume
that sent the headers and stalled the body held the copy up for good. Each
delete now runs within copyCleanupTimeout (10s), its answer included, and
still logs the status and up to 4 KiB of the body.

Tests: the fake volume keeps the file it was sent, and each retry case checks
that the second volume stored the copied bytes. An SSE-C chunk copied under a
new key decrypts with the key and IV its chunk names. Marked 409 and 401
answers reassign, unmarked ones do not, and a stalled cleanup delays the copy
by the timeout only.

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

* s3api: renew an expired token for a failed copy chunk's delete

A copy's write token is minted at the assignment, before the source is
read, and lasts 10s by default. A write that failed after that left the
cleanup delete refused with 401 and the needle orphaned. PutObject's
cleanup renews the token from the master on a 401; do the same.

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

* s3api: log the status and body of a cleanup delete whose read failed

A delete whose answer began but whose body read failed, such as one cut
off by copyCleanupTimeout, was logged with the error only. Log its status
and the part of the body that arrived as well.

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-12-02 12:03:40 -08:00
Chris LuandClaude Opus 5.5 38422bd1fa filer: RecursiveLister, a subtree in path order from one range of postgres_flat (#13261)
* filer: RecursiveLister, a store capability to list a subtree in path order

The wrapper hands it to the default store, reading hard links as listings
do, and declines it when path-specific stores could hold part of the
subtree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: list a subtree with one range scan when rows are keyed by path

AbstractSqlStore lists recursively when its generator implements
RecursiveListSqlGenerator. The range runs from the directory and prefix to
the least string past every path starting with them. A directory whose
subtree spans the bucket tables is declined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: the postgres_flat generator lists a path range

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/store_test: check recursive listings

Byte order across +, -, / and non-ASCII names, prefixes holding a slash,
literal % and _, resuming after a path, pages of one and three, a
directory outside the buckets, and the directories that span bucket
tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: a recursive listing's start path outside the bucket table bounds it by full path

A start path in another bucket was trimmed as if it were inside this one, so
a start path past the bucket listed it all again, and one before it could
skip entries.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:03:18 -08:00
Chris LuandClaude Opus 5.5 b7536bd6f6 test: S3, versioning and FUSE integration tests for the postgres_flat filer store (#13255)
* test/postgres_flat: S3 against a filer on the postgres_flat store

A weed mini whose filer.toml enables postgres_flat in a schema of its own.
Objects, listings, copies, multipart uploads, versions and bucket deletion
are checked through S3 and against the rows of the bucket's table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: a FUSE mount against the postgres_flat store

Files, a directory longer than a listing page, renames, hard and symbolic
links, tree removal and a bucket made through the mount, checked against the
rows, then read back by a second mount with an empty metadata cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: run the postgres_flat S3 and FUSE tests against Postgres

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: run the postgres_flat tests on pull requests to any branch

Like the S3 workflows, so a stacked pull request runs them too, and only
when the code they reach changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: fail fast when weed mini or the mount exits

ProcessState is only set by Wait, which ran only at cleanup, so a mini
or mount that died at startup was noticed only at the 45s or 90s
deadline. Reap each command as it starts and check for its exit while
waiting.

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

* ci: run the postgres_flat tests on changes anywhere under weed/

The tests run master, volume, filer, S3 and a mount, so changes in
packages such as weed/pb, weed/wdclient or weed/credential reach them
too. Match the FUSE integration workflow and also trigger on the
fusermount action the job uses.

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

* test/postgres_flat: versioned buckets on the postgres_flat store

Versions and delete markers are rows under the key's .versions folder in
the bucket's table. Covers version listings in one page and one version a
page, delete markers, promoting the previous version, the null version
under suspended versioning, and dropping the table once every version and
the bucket are deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: run the S3 versioning suite on a postgres_flat filer

The whole test/s3/versioning suite, stress tests included, against a weed
mini whose filer.toml enables postgres_flat. The job first checks that
filemeta has the flat layout, so a filer on its default store cannot pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* test/postgres_flat: set up shared objects before the subtests

The S3 and versioning suites wrote their objects and the second bucket
inside the first subtest, so running one later subtest with -run left
the version ids empty and panicked. The parent test now writes them and
the subtests only check.

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

* test/postgres_flat: helpers fail the test that calls them

paths, tableExists, count, filerList, start and mount take the caller's
*testing.T, so a failure inside a subtest fails that subtest instead of
calling FailNow on the parent and stopping its siblings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: wait for the filemeta table before the versioning suite

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

* test/postgres_flat: POSIX subtests set up their own fixtures

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

* test/postgres_flat: absent versions must answer 404

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:42:13 -08:00
b5a7d9600e kms: read provider settings as TOML gives them (#13294)
* kms: read provider settings as TOML gives them

Provider settings were read with plain type assertions, so a setting
of another type read as its zero value. TOML decodes integers as
int64, which GetInt ignored, so max_cache_size from filer.toml never
applied, and Viper lowercases TOML keys, so the local provider never
saw enableOnDemandCreate. A cache_ttl that didn't parse fell back to
an hour without a word.

Settings are now read through one typed getter. An int64 or a whole
float64 reads as an int, a key matches ignoring case when it isn't
found as given, and a provider that reads a setting of the wrong type
fails to load and is closed. The loader reads the cache settings the
same way and fails a provider whose cache settings don't parse.

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

* kms: apply the cache defaults to a setting given as null

A JSON null for cache_enabled or cache_ttl counted as set, so it turned
caching off or failed the provider on an empty duration, where it used
to read as the default.

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-12-02 07:15:51 -08:00
ed177d31e3 kms: run provider health checks without the manager's lock (#13295)
* kms: run provider health checks without the manager's lock

GetKMSHealth held the manager's read lock while it asked every provider for
a key, and a remote KMS can take its whole timeout to answer. A provider
change waited behind it for the write lock, and every request looking up a
provider then waited behind the change. The checks now run on a copy of the
providers. SetDefaultKMSProvider and SetBucketKMSProvider check that the
provider exists and set it under one lock, so a provider removed in between
can't be left as the default or as a bucket's provider.

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

* kms: health-check only the provider a load adds

Loading a provider checked every provider loaded so far, so a configuration
with N providers made N(N+1)/2 remote calls at startup, and one slow provider
could spend the shared 10s budget and get the new provider reported unhealthy.

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

* kms: run provider health checks concurrently

The checks shared one deadline and ran one after another, so a provider
stuck until the deadline got every provider checked after it reported
unhealthy, and startup waited for the checks in turn.

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-12-02 07:11:17 -08:00
Chris LuandClaude Opus 5.5 acff807879 filer: postgres_flat store keyed by the full path (#13253)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of directory statements

Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: batch lookup takes row keys and matches rows by name and directory

A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: build the connection string with pgxutil.BuildDSN

The credential store already does; it quotes values per libpq, so a
password or certificate path with spaces or quotes no longer breaks the
connection string. The OpenPGXDB alias has no callers left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: scan pages take the row key of the last row as their cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: postgres and postgres2 share their connection setup

ReadConnection reads the settings and their defaults, Connection.Open
opens the store's pools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: key-value records may live in a table of their own

A store whose entry tables have another layout keeps its key-value
records in KvTable, written by KvSqlGenerator; its scans then read only
entries and need not tell the records apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: SQL generator keyed by the full path

Rows have path as their primary key; a (directory, name) unique
constraint serves the directory listings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: postgres_flat store

Entries are keyed by their full path, the object key inside a bucket's
table; buckets get tables of their own as in postgres2. Key-value
records keep the postgres2 layout in filemeta_kv. The store refuses a
filemeta table of another layout, so it needs a schema of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: register postgres_flat and add it to the filer.toml scaffold

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: test the arguments each generator binds

Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

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

* filer/postgres_flat: name a missing filemeta table instead of a foreign layout

With createTable = false and no filemeta table, the layout check said the
table had no path column and blamed a postgres2 layout. Report the missing
table and the key-value table that also has to be created.

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

* filer/postgres: postgres_flat escapes the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one, but the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: escape the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: postgres_flat shares the generator's tableIdent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

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

* filer/postgres_flat: find filemeta along the search path when checking its layout

The store's queries name filemeta unqualified, so with schema = "a,b" they
reach a table in b; the layout check looked in current_schema() only and
refused it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres_flat: force byte order when the path column is locale-ordered

Directory listings order and bound rows by path, but only the name
column's collation was checked. A createTable with a locale-ordered path
column listed in locale order, and byte-order bounds missed entries.

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

* filer/postgres: read the ordered columns' collation along the search path

The collation check looked for filemeta in current_schema() only. With the
tables in a later schema of the search path it found no column and took the
database's order, so a locale-ordered path column next to a C database went
unforced, and byte-ordered columns in a locale database got a needless sort.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres_flat: list a directory from its path range

A directory's children are the rows of its path range whose directory is
the listed one. The listing reads that range in growing batches and skips
the rows of the children's subtrees in Go, so a versioned object's
.versions rows cost no query of their own. Past 64 rows of one subtree it
queries again from that subtree's end. A name prefix narrows the range.

Listing no longer reads the (directory, name) index.

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

* filer/postgres_flat: find a folder's children in its path range

Deleting a folder's children looked them up by directory alone, which
only the (directory, name) index serves. Bound the delete by the
folder's path range as well.

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

* filer/postgres_flat: key the table by path alone

Listing and deleting a folder's children both read the path range now,
so the (directory, name) unique index only cost writes and storage:
flatPath already makes the path unique per (directory, name).

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

* filer/postgres: read the ICU or builtin database locale before datcollate

An ICU-default database can report datcollate 'C' while its default
collation orders by the ICU locale, so a name column on the database
default looked byte-ordered and the listing kept locale order. Read
datlocprovider and the provider locale (via to_jsonb, so servers before
Postgres 15 still answer) and treat an ICU default as locale-ordered.

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

* filer/postgres_flat: list a folder's children from its path range

The bucket enumeration listed /buckets by directory and ordered by name,
a sequential scan and sort now that path is the only index. Read the
folder's path range in path order instead.

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

* filer/postgres_flat: only the path column needs byte order

Listings now order and range by path alone, and directory and name are
only compared for equality, which no deterministic collation changes.
Drop their COLLATE "C" and check only the path column's order.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 07:05:13 -08:00
Tiago PosseandClaude Opus 5.5 ce7b6c93b2 filer: read the views of the chunk a boundary read leaves in one goroutine (#13293)
A read across a chunk boundary started a goroutine for each view of the
chunk the stream leaves, outside the limit on chunks read at once, so a
compressed chunk written over in many places could start any number of
them. One goroutine started before the others now reads those views one
after another, and the other views are back under the errgroup limit. It
reads every view from the held download before a view the download can't
serve falls back to a read of its own, as that read can make room and
evicting the chunk waits for the holds.

The test of a boundary read that doesn't wait for the chunk it leaves now
has four times as many views of that chunk as chunks run at once, and
checks that the read starts fewer goroutines than that.

The waits for a prefetch to reserve and for a boundary read to fetch its
last chunk are bounded, so a failing test reports instead of hanging.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 07:04:19 -08:00
Martijn HoekstraandClaude Opus 5.5 411ab1d920 worker(rs): refuse short JWT keys under fips.mode strict (#13284)
* worker(rs): refuse short JWT keys under fips.mode strict

weed-worker, weed-vector and weed-vector-cli now check the JWT keys of the
security.toml they read, as every Go process does: under fips.mode strict
each exits at startup naming every key shorter than the 14 characters FIPS
140 needs for HMAC keys, with the rule and messages of
seaweed_common::jwt_keys (#13206); outside strict mode each such key but a
previous_key gets a warning. A filer signing key given on the command line
(--filer-signing-key, WEED_FILER_SIGNING_KEY) is checked the same way.

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

* worker(rs): warn about a short signing key flag outside strict mode

A filer signing key given by --filer-signing-key or WEED_FILER_SIGNING_KEY
was checked only under fips.mode strict; outside it, a key strict mode
would refuse now gets the warning a short key in security.toml gets.

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

* test: start the worker binaries with short keys under fips.mode strict

Integration tests start the built weed-worker, weed-vector and
weed-vector-cli under WEED_FIPS_MODE=strict with a 10-byte key in
security.toml, or a short --filer-signing-key, and check that each exits
naming the key. They run in the existing cargo test jobs and need no
cluster: the check comes before the binaries dial anything.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 06:24:14 -08:00
6a67fe503e vacuum: compact copies held read-only by a readonlyCanDelete mark (#13283)
* vacuum: compact copies held read-only by a readonlyCanDelete mark

A volume marked with volume.mark -readonlyCanDelete takes no new writes
but keeps taking deletes, so it can drain instead of holding a volume
slot (#10688). The automatic vacuum never reclaims those deletes: it
skips every read-only copy unless low disk space is the only cause, and
a mark clears that exception (#11519). The space comes back only once
the last needle is deleted (deleteEmpty) or through volume.vacuum
-volumeId, one volume at a time, so a volume that never drains
completely keeps its garbage.

VacuumVolumeCheck now also reports can_delete_mark: the copy is
read-only through a readonlyCanDelete mark and nothing that refuses
deletes (no plain read-only mark, no I/O quarantine, not tiered to
remote storage). The sweep compacts such a copy like a writable one,
except when the master pushed the mark itself to quarantine a duplicate
volume id. The mark survives the compaction, so the copy stays
read-only, keeps taking deletes and stays out of the writables. A
read-only volume reserves no headroom, so the space it gives back
becomes free volume slots.

The Rust volume server reports the same field. In volume.vacuum, the
help text and the list of read-only volumes the sweep skips leave out
copies that still take deletes. For the unnamed collection, which the
shell vacuums volume by volume, such volumes are left to the sweep: an
explicit request would also compact a quarantined copy.

An older volume server does not set the field and an older master
ignores it, so a mixed cluster keeps skipping these copies.

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

* shell: say which marked volumes volume.vacuum leaves to the sweep

For the unnamed collection, volume.vacuum sends one request per volume
and skips a volume held by a readonlyCanDelete mark, while the "skipped
by the sweep" hint leaves such volumes out because the sweep compacts
them. With a filter matching only those volumes, the command returned
without a request and without a word. It now lists the marked volumes
over the threshold that it leaves to the automatic sweep.

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

* storage: drop the compacted needle map a read-only commit leaves unused

CommitCompact reloads a read-only volume into a sorted map, so the
compacted map built for the reload is never consumed: it stays in
v.tmpNm with every needle of the volume, and with a leveldb index its
.cpldb stays on disk. The next compaction reopens that .cpldb as is, so
needles deleted between the two compactions come back in the leveldb
map with stale offsets once the volume is writable again, and reads of
them fail with EOF instead of not found.

The sweep now compacts readonlyCanDelete volumes, so this path is no
longer limited to an explicit volume.vacuum -volumeId.

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

* storage: do not tie the canDelete compaction test to random needle sizes

newRandomNeedle sizes its data at random, so three deleted needles out
of six left under 30% garbage about once in twenty runs and failed the
precondition. The test only needs the deletes to leave some garbage.

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

* shell: say the sweep skips quarantined copies in the left-to-sweep note

The note named unnamed-collection volumes as left to the automatic
sweep, but the sweep skips a copy the master holds for a duplicate
volume id under the same mark, and the topology does not show that
quarantine. The note now says so. It also describes the copies by what
the topology shows, read-only but still taking deletes, since a copy
read-only only for low disk space looks the same when its probe fails.

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-12-02 04:23:39 -08:00
c96636ecd0 filer: fold chunk lists for scoped commits (#13281)
* filer: fold chunk lists for scoped commits

A filer serving a keep-only scoped token never folded chunk lists, and
refused any new chunk for an entry holding manifests, so scoped clients
kept their lists flat. On a store with a value size limit, such as
FoundationDB, a scoped file stopped fitting at about 1000 chunks.

The filer now folds scoped commits and reuses stored manifests as it does
for unscoped ones. Folding runs after the retained-data check, so the only
manifests a scoped commit stores are ones the filer wrote:

- a scoped request may keep a manifest stored at the target, sent as
  stored; any other manifest is refused, with or without a proof, and a
  stored manifest cannot be kept as a data chunk;
- the chunks held by the stored manifests count as stored at the target
  and join the identity map, so they may be retained flat but not under
  another spelling of their file id;
- those chunks are read under the handler's path lock, not at admission;
  admission still refuses a manifest the target does not store and leaves
  the checks that depend on the held chunks to the locked check. A
  manifest that cannot be read refuses the write as Unavailable. An update
  rechecking inside its store transaction reuses the chunks it already
  read, so it does no volume I/O there.

Appends to a folded entry are allowed under the same rules: an append
keeps every stored chunk, and the locked check refuses aliases of the
chunks the stored manifests hold.

* mount: explain why a scoped mount keeps chunk lists flat

A filer serving a scoped token now folds scoped commits itself and keeps
only the manifests it wrote. The mount's flat rule is unchanged; only the
reason given for it was out of date.

* filer: test a scoped truncate through a stored manifest

* filer: refuse manifest chunks in a scoped append

An append moves each chunk it carries to the end of the file. A manifest
cannot be moved that way: the chunks it holds keep their own offsets, so
the appended range would read no data and the manifest's bytes would still
read at their old place. Before this series a scoped request could carry no
manifest at all; now that a scoped commit may keep a stored manifest, an
append still takes data chunks only.

* filer: read only the stored manifests a scoped commit drops

The locked retained-data check read every stored manifest whenever a
scoped request had chunks, so each flush of a folded file and each append
cost one volume read per manifest under the path lock. The unscoped path
reads only the manifests a commit drops.

Read the same way for a keep-only scope: only the stored manifests the
request does not keep unchanged, and none for an append, which keeps every
stored chunk. A kept manifest keeps its chunks referenced, and garbage
comparisons match chunk identities, so another spelling of one of its
chunks cannot get the needle deleted; such a chunk now needs its own proof
like any new chunk. Truncating through a manifest and listing its chunks
flat still work, since both drop it.

* filer: find the dropped manifests of a scoped commit in one pass

Index the manifests the request keeps by file id instead of scanning the
request for each stored manifest, which compared and cloned chunks
quadratically in the number of manifests.

* filer: rewrap the scopeManifestReader 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-12-02 04:22:12 -08:00
Chris LuandClaude Opus 5.5 4cb096e32f filer, s3: report a failed read as an error, not as a missing entry (#13289)
* filer/mongodb: report a failed read as an error, not as a missing entry

FindEntry logged any read error other than ErrNoDocuments and returned
filer_pb.ErrNotFound, so a lookup that could not reach MongoDB answered
that an existing entry was gone.

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

* filer/arangodb: report a failed read as an error, not as a missing entry

FindEntry logged any ReadDocument error other than not-found and
returned filer_pb.ErrNotFound, so a lookup that could not reach ArangoDB
answered that an existing entry was gone.

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

* filer/rocksdb: report a failed read as an error, not as a missing entry

FindEntry and KvGet checked for a missing value before the read error,
and the value is nil after any failed read, so every read error came back
as not found.

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

* s3: a versioned read whose lookup fails is not NoSuchKey

In a versioned bucket, GetObject, HeadObject and GetObjectAttributes
answered NoSuchKey for any error from getLatestObjectVersion, so a filer
or store outage told clients that existing objects were gone. They now
classify the error the way CopyObject's source lookup does: NoSuchKey
only when the object is missing, 503 for transient failures and 500
otherwise.

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

* s3: keep the cause when the latest version file cannot be read

doGetLatestObjectVersion formatted a failed read of the version file the
pointer names with %v, so a transient failure there answered 500 instead
of 503.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:20:06 -08:00
Chris LuandClaude Opus 5.5 1f65d9e708 s3api: answer GetBucketLocation with a LocationConstraint document (#13292)
GetBucketLocation wrote the CreateBucket request body
(CreateBucketConfiguration), so clients that check the root element, such
as the AWS Rust SDK, failed with "expected LocationConstraint tag". Reply
with an empty LocationConstraint in the S3 namespace, which is what AWS
sends for us-east-1 buckets.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:10:17 -08:00
Chris LuandClaude Opus 5.5 97cac5f5e5 test: fix mq tests broken by separately merged changes (#13285)
* mq/logstore: rename the tiered copy of a duplicated test name

TestTimeReadWithNothingNewKeepsItsPosition was added in both
merged_read_test.go and merged_read_table_test.go by changes that
merged separately, so the package's tests stopped compiling. The
table-backed one becomes TestTieredTimeReadWithNothingNewKeepsItsPosition.

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

* query engine: make the topic table test's control entry a close marker

The test's offset 5 had no key but kept its value, which was a control
entry before keyless messages became data. Now only an entry with
neither key nor value is skipped, so the baseline scanned that message
in both partitions and counted 22 rows instead of 20. Offset 5 drops its
value too, so it is the close marker the test means.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:07:51 -08:00
Yip LeoandClaude Opus 5.5 13d65deb3a filer/tikv: report a failed read as an error, not as a missing entry (#13287)
FindEntry turned every failed read into filer_pb.ErrNotFound, because
the value it checks is still nil after any error. While TiKV cannot be
reached, or a region has lost its leader, a lookup of an existing entry
answers "not found" once the client library gives up its backoff (about
40 s): the S3 gateway returns 404 NoSuchKey to HEAD and CopyObject,
weed mount returns ENOENT and the filer HTTP API 404. Writes in the same
outage fail with an error, so only reads report the entry as gone.

A read that TiKV answers with "not exist" is still a missing entry; any
other error is returned to the caller.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:07:00 -08:00
Chris LuandClaude Opus 5.5 b1f86ddfa2 s3: support PutBucketDefaultStorageClass and GetBucketDefaultStorageClass (#13282)
* s3: add PutBucketDefaultStorageClass and GetBucketDefaultStorageClass

The setting is kept in the bucket entry's extended attributes next to
the other bucket configuration, so every gateway sees it through the
bucket config cache. Only STANDARD and INTELLIGENT_TIERING are accepted,
matching the AWS model; STANDARD clears the stored value.

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

* s3: give new objects the bucket default storage class

PutObject, POST uploads, CreateMultipartUpload and CopyObject store the
bucket default when the request names no storage class. The request
headers are left alone, so bucket-policy storage-class conditions and
the self-copy change check still see only what the client sent. Upload
parts are not tagged; a completed upload takes the class recorded when
it was initiated.

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

* s3: test the bucket default storage class APIs and write default

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

* s3: fail a write whose bucket default storage class cannot be read

A failed bucket config lookup used to fall back to STANDARD, so a write
could store a different class than the bucket default asks for. The
write now returns the lookup error instead. A request that names its
own class still needs no lookup.

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

* s3: give extracted ZIP directory members the bucket default storage class

Directory members are created through mkdir rather than putToFiler, so
they stored no class while the files next to them did.

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

* s3: reject a default storage class body with trailing data

The decoder stopped after the first element, so a valid configuration
followed by another element or stray bytes was accepted. The body is
now read with a size bound and only whitespace, comments or processing
instructions may follow the configuration.

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

* go.mod: bump aws-sdk-go-v2/service/s3 to v1.117.1

The release adds the PutBucketDefaultStorageClass and
GetBucketDefaultStorageClass client operations.

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

* s3: test the bucket default storage class through the AWS SDK

Covers get/set, an unsupported class, the setting stored in the bucket
entry and read back by a fresh bucket config, PUT, explicit classes,
multipart initiation, copy, existing objects, and per-API grants.

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

* s3: let each default storage class subtest set up its own state

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

* s3: assert the explicit STANDARD class exactly in the default class test

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

* s3: note that the bucket default storage class is a label only

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 04:05:48 -08:00
6b402aa87c sftp: serve one session on stdin/stdout when run as an OpenSSH Subsystem (#13278)
* sftp: add -stdio to run as an OpenSSH Subsystem

weed sftp -stdio serves one SFTP session on stdin/stdout, so sshd can run it
as its sftp subsystem and handle authentication itself (PAM, SSSD, 2FA,
AllowUsers, Match blocks):

    Subsystem sftp /usr/local/bin/weed sftp -stdio -filer=filer:8888

The session belongs to the OS user sshd started it as. With -userStoreFile
that user must be in the store, and its HomeDir and Permissions apply as
over SSH; without one, the session reaches the whole filer, which the
process's filer access allows anyway. The SSH listener options are ignored
and nothing but SFTP is written to stdout.

Checked with OpenSSH's sftp -D: put/ls/rm on the whole filer without a
store; with a store the user is jailed to its home, and a user missing from
the store is refused.

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

* sftp -stdio: explain an unreadable user store, test the stream

The session runs as the logged-in OS user, who must read the store; a
store without passwords or keys can be shared with them. Tell that user
why the store is refused instead of a bare permission error.

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

* sftp: stdio sessions reuse handleSFTP

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

* sftp: a refused -stdio session exits 1 without printing usage

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

* sftp -stdio: give up after 30s when the filer is unreachable

The listener keeps waiting for the filer; a stdio session is one login and
should not hold a process for the whole outage.

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

* sftp -stdio: bound the filer configuration request by the wait

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

* sftpd: skip the unreadable-store test on Windows

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

* sftp: detect the sshd Subsystem launch instead of a -stdio flag

weed sftp serves one session on stdin/stdout when sshd starts it: SSH_CONNECTION
is set and stdin and stdout are both pipes or sockets. A listener started by
systemd, a container, nohup or a shell has a terminal, /dev/null or a file
there, so it keeps listening.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 04:02:12 -08:00
f88ca328da sftp: answer md5sum, sha1sum, df and echo exec requests (#13277)
* sftp: answer md5sum, sha1sum, df and echo exec requests

SFTP clients such as rclone verify transfers and show free space by running
md5sum/sha1sum/df over an SSH exec request. weed sftp rejected every exec
request, so rclone fell back to comparing sizes and could not report usage.

Answer the few commands those clients send, without a shell:

- echo <text>: prints text (rclone's shell detection)
- md5sum/sha1sum [path]: the file's hash in coreutils format, or the
  empty-input hash without a path (the support probe). The path is resolved
  inside the user's home and needs read permission. MD5 uses the hash the
  filer stored when there is one, otherwise the content is read.
- df [-k] [path]: the filer's volume capacity in df -k format

Anything else fails with exit status 1. Checked with rclone: hashes md5 and
sha1 detected, md5sum/sha1sum match local files, `rclone about` works.

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

* sftp: describe exec commands without naming one client

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

* sftp: exec hashes cover sparse files and stop with the connection

- md5sum/sha1sum read a file's whole logical content, with zeros for the
  holes and tail no chunk stores, through the same sparse-aware stream an
  in-place SFTP write uses; it ends with the SSH connection
- a trailing escaped space stays part of the file name
- df checks that the path exists

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

* sftp: relative exec operands, hashes of holes stop, setstat size clears MD5

- a command's relative path is relative to the home, as over SFTP, so df
  and the hashes of a root-home user look up the right entry
- writes into the hash check the connection, so a large file that is all
  holes stops too
- a size change through SETSTAT drops the stored MD5, which md5sum reports

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

* sftp: an exec ends when the client closes its channel

The command's context ended only with the SSH connection, so a client that
closed one exec channel and kept the connection left a hash running. The
channel's request stream closes with the channel, which now cancels it.
A second exec on the same channel is refused, as OpenSSH does.

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

* sftp: a channel runs one exec or one SFTP session

With the exec running beside the request loop, a subsystem request after
it would have started SFTP on the same channel while the command was still
writing to it.

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

* sftp: refuse a subsystem request without a name instead of panicking

The subsystem name was read as Payload[4:], so a request with fewer than
four payload bytes panicked the channel goroutine and stopped the server.
Decode the name like the exec command.

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

* sftp: test that a running exec keeps its channel from starting sftp

Also say in handleExec that its context ends with the channel.

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

* sftp: df drops -k only as a whole option

"df -kfoo" was read as "df foo"; now -kfoo is the path, which fails
unless such a file exists.

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 03:54:26 -08:00
e32f1aa20e filer: don't evict a chunk a stream is still reading (#13276)
* filer: don't evict a chunk a stream is still reading

The reader cache map and the budget fell back to evicting a chunk a
stream was in as soon as they found no idle one, even while a running
download held the rest and would become evictable once it finished. The
stream then fetched its chunk again. They now evict a pinned chunk only
once pinned chunks alone fill the limit or the budget. A budget wait
wakes when a stream enters or leaves a chunk, and when a pinned
download reserves.

A read across a chunk boundary leaves the stream's chunk before making
room, or its pin would count against another stream's chunk, and carries
the stream to its last chunk. Its reads of the chunk it leaves hold that
download, start first and take no concurrency slot, as evicting the
chunk waits for them.

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

* filer: wait for the budget waiter in reader cache tests instead of sleeping

A reservation that reaches the budget only after the sleep sees the new
state on its first check, so these tests could pass with the wakeup or
the wait rule they cover removed. Wait until the reservation is parked
in reserve, and fail at once if it finishes without waiting.

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

* filer: release blocked test fetches when a boundary read test fails

A t.Fatal before the gate closed left the deferred cache destroy waiting
for the blocked fetch, so the test hung instead of failing. The wait for
the head read to pin chunk0 is now bounded too.

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

* filer: hold the chunk a boundary read leaves from one look at the stream

The hold pass looked up the stream's chunk per task and the leave looked
again, so a concurrent read on the same reader that moved the stream in
between got its new chunk detached and unheld, and the boundary read could
download that chunk again. Take the stream's chunk once, hold it for the
views reading it, and detach only that chunk.

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

* filer: tie the budget-wait test check to the test's own reservation

waitForBudgetWaiter now starts the reservation itself and only accepts a
goroutine parked in reserve that is that goroutine or a download it
started, so an unrelated waiter cannot let a test move on early. The
direct budget tests cancel their waiter on cleanup, since destroy() does
not reach a cacher outside the map.

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-12-02 03:52:46 -08:00
Chris LuandClaude Opus 5.5 ca09dae400 filer/postgres: postgres and postgres2 share their connection setup (#13252)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of directory statements

Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: batch lookup takes row keys and matches rows by name and directory

A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: build the connection string with pgxutil.BuildDSN

The credential store already does; it quotes values per libpq, so a
password or certificate path with spaces or quotes no longer breaks the
connection string. The OpenPGXDB alias has no callers left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: scan pages take the row key of the last row as their cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: postgres and postgres2 share their connection setup

ReadConnection reads the settings and their defaults, Connection.Open
opens the store's pools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: test the arguments each generator binds

Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

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

* filer/postgres: escape the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:46:57 -08:00
Chris LuandClaude Opus 5.5 abe623c570 filer/sql: generators bind their own statement arguments (#13251)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of row statements

Insert, update, find and delete now take the row key and return their
arguments with the query, so a generator decides how a key maps to its
columns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: generators bind the arguments of directory statements

Listing and deleting a directory's children take the directory and return
their arguments with the query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: batch lookup takes row keys and matches rows by name and directory

A key-value key's directory column already determines its dirhash, so the
batch read no longer selects dirhash to match its rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: scan pages take the row key of the last row as their cursor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/sql: test the arguments each generator binds

Each statement's arguments must match its placeholders in count and
column. Check them for every generator method, including the Postgres
UPDATE whose parameters are now numbered key first.

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

* filer/postgres: escape the table name inside its quotes

A double quote in it is doubled, as PostgreSQL reads a quoted identifier.
Bucket names cannot hold one; the statements no longer rely on that.
Reported by CodeQL (go/unsafe-quoting) on the lines this branch changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/postgres: keep the nameExpr doc comment on nameExpr

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:45:44 -08:00
889d15b8de sftp: refuse paths that are not valid UTF-8 (#13279)
* sftp: refuse paths that are not valid UTF-8

Filer entry names are proto strings and must be valid UTF-8.
util.FullPath.DirAndName replaces invalid bytes in the last path element
with "_", but leaves the directory part as is. So an SFTP request naming
"bad\xfe" silently acted on "bad_": Mkdir created a directory "bad_",
Rename moved the source to "bad_", Open/Put uploaded to "bad_", and
Stat/Setstat matched an unrelated "bad_" entry. Any later request using
the name as a directory then failed to marshal, so the mangled entry
could not be removed under the name the client used. rclone's
FsEncoding/invalid_UTF-8 test hits this and leaves "invalid utf-8_"
behind, breaking every later listing check.

Reject such paths in toAbsolutePath, which every request (including the
rename target) goes through, with SSH_FX_BAD_MESSAGE, so nothing is
created or changed.

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

* sftp: shorten the invalid UTF-8 path comments

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-02 03:43:49 -08:00
ca4d7939ab sftp: fail listing a missing directory (#13280)
The filer streams nothing for ListEntries on a directory that does not
exist, or on a file, so OPENDIR succeeded and READDIR returned an empty
listing. Clients could not tell a missing directory from an empty one:
`rclone lsf remote:does-not-exist` exited 0, and rclone's
FsListDirNotFound test got nil instead of "directory not found".

When the first page comes back empty, look the path up and return
os.ErrNotExist unless it is a directory, which the request server sends
as SSH_FX_NO_SUCH_FILE. Non-empty listings pay no extra lookup.

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:43:25 -08:00
Chris LuandClaude Opus 5.5 2574cedfd3 s3: publish a recovered PUT's event at its commit stamp (#13265)
* s3: publish a recovered PUT's event at the stored entry's commit stamp

A PUT whose create committed but lost its answer, and that recovery
then found stored, published its event at the gateway's clock. A later
write to the same key that carries its filer stamp could then sort
before it. Both recovery paths now take the stamp the committing filer
gave the stored entry, as recovered multipart completions do.

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

* mq: return the context error when it ends a topic configure

A start whose context ended during ConfigureTopic on the last broker
answered with the RPC's text, so errors.Is(err, context.Canceled) did
not hold for it as it does for a context that ends before an attempt.

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

* mq: name the broker whose topic configure failed

doConfigureTopic built lastErr with the broker address but returned the
bare RPC error, so a failed configure did not say which broker refused.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:38:58 -08:00
5a8e774e36 shell: harden volume.tier.upload for unattended batch runs (#13254)
* shell: harden volume.tier.upload for unattended batch runs

- validate -dest against the master's storage backends before any volume
  is marked read-only, instead of failing per volume after the freeze
- mark replicas read-only with canDelete so TTL expiry keeps draining the
  volume during the upload, and restore writable marks when the upload or
  metadata replication fails partway
- keep going after a per-volume failure in batch mode and report all
  errors at the end
- treat an unset -disk as "any disk"; flag.String never returns nil and
  ToDiskType("") is the hdd type, so the batch silently skipped ssd and
  tagged volumes

Refs #13223

* shell: keep deletes refused while volume.tier.upload copies a volume

A delete accepted during the copy appends a tombstone to the source .dat,
so the attach refuses the upload, and one accepted after a replica's .idx
snapshot is dropped when that replica installs the copy.

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

* shell: leave replicas that were read-only alone when a tier upload fails

VolumeMarkWritable persists ReadOnly=false, so the rollback cleared an
operator's read-only mark on any replica that was frozen before the run.

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

* shell: roll back the replica whose read-only mark failed in volume.tier.upload

VolumeMarkReadonly freezes the volume locally before its second master
notification, so an error there leaves the replica read-only although it
never joined the marked list. Also name that replica in the error.

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

* shell: let the tiered source accept deletes once every replica has its index

The copies load as tiered volumes that accept deletes, but the source kept
the no-delete mark until its next reload, so a delete applied on a copy
then failed on the source.

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

* shell: bound each rollback mark in volume.tier.upload

A stalled VolumeMarkWritable held up the upload error and, in a batch run,
every later volume.

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

* shell: keep replicas frozen when the tier upload attached before failing

A stream that breaks after the volume server attached the remote copy
returns an error, and reopening the other replicas then let them take
writes the remote copy lacks. Ask the source first; a rerun finishes the
upload from its remote copy.

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

* shell: bound the final delete mark in volume.tier.upload

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-12-02 03:38:02 -08:00
e10cf7fd85 shell: a moved volume does not keep its source disk id in the model (#13275)
* shell: a moved volume does not keep its source disk id in the model

adjustAfterMove added the moved volume to the target's VolumeInfos with the
source's DiskId. volumeServer.evacuate moves the normal volumes first and then
plans the EC shards on the same topology, where the disk ids of a node come
from its volume and shard records. A volume moved off disk 3 of a four-disk
server therefore gave its one-disk target a disk 3, the planner sent EC shards
there, and the target refused every such move with "invalid disk_id 3: only
have 1 disks".

The target server picks the disk for a moved volume, so record it with disk id
0 (unknown) on a copy, leaving the source's record as it is.

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

* shell: test the EC phase of evacuate on the model the volume phase left

Drive evacuateNormalVolumes and then evacuateEcVolumes, the two phases
the command runs on one topology, instead of calling adjustAfterMove
directly, and check the disk each planned shard move names.

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

* shell: trim comments on the moved volume record

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-12-02 03:32:44 -08:00
Chris LuandClaude Opus 5.5 2b157f2ef1 test: clear the codespell hits left after #13290 (#13264)
* test: use a codespell-clean non-ASCII key in TestEncodeKey

Codespell reads caf%C3%A9 as the misspelling caf.

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

* topictable: reword want's in the CheckSchema comment

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:28:00 -08:00
Yip LeoandClaude Opus 5.5 22abfe2d1b shell: leave emptier servers without free slots out of the -byDiskUsage ideal (#13247)
* shell: leave emptier servers without free slots out of the -byDiskUsage ideal

volume.balance -byDiskUsage never picks a server without a free volume
slot as a move target, but planBalance counted every server in the ideal
ratio. A server that is emptier than the rest but has no free slot, as
happens to an auto-sized disk (no -max) whose free space is held as
growth room for its partly written volumes, pulled the ideal below the
usage of the servers that could take a volume. Every target's next
ratio then exceeded the ideal, planBalanceMove stopped at the first one,
and the run planned no move while the fullest servers kept filling.

The ideal of a -byDiskUsage run now leaves those servers out: a server
without a free slot below the ideal is dropped and the ideal recomputed
over the rest, until none is below it. A server without a free slot
above the ideal still counts, as it is drained as a source.

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

* shell: leave servers out of the -byDiskUsage ideal by their raw ratio

idealRatioOfReceivingServers compared a server with DensityRatio, which
gives a server with no whole volume used a floor of half a volume over
its capacity. A small disk without free slots then compared above the
ideal and stayed in it, holding the ideal under the targets' next ratio
as before. Compare the raw used/capacity ratio, the one the ideal is
made of.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:22:35 -08:00
Chris Lu 081218bf8a test: reword misspelled fixtures that trip codespell (#13290) 2026-12-02 03:21:01 -08:00
9f9c28471f s3api: free the parts a multipart completion does not name (#13248)
* s3api: free the parts a multipart completion does not name

prepareMultipartCompletionState skipped every entry of the upload
directory whose part number the request does not name: it was neither a
part of the object nor one of the unused entries freed with their data.
The completion then removes the upload directory metadata-only, since
the object's chunks are its parts' chunks, so the skipped parts' chunks
stayed on the volume servers with nothing referencing them until a
volume.fsck purge. Once the upload is completed they cannot be listed,
completed or aborted any more.

The completion now keeps those entries aside and, once its object is
committed and the upload directory is gone, deletes their chunks by
file id, resolving manifest chunks first. They are not freed before the
commit, as the unused attempts are on the routed paths: until a
completion succeeds the upload stays open with all its parts, and the
commit transaction can still refuse the write. When another completion
of the upload owns the commit (metadataOnlyCleanup), its object can hold
them, and they are kept.

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

* s3api: give the unrequested-part cleanup one deadline and check the committed object first

The client waits for the completion it already committed, so the cleanup
of the parts the request did not name gets one deadline,
unrequestedPartsCleanupTimeout, instead of a lookup timeout for each part
with manifests: the chunks of the parts without manifests are deleted
first, then manifests are resolved part by part while time is left.
deleteOrphanedChunksWithContext passes the deadline to the volume lookups
and deletes; deleteOrphanedChunks keeps its behaviour.

A completion without a ring owner commits under the object lock without
the upload-directory precondition, so a routed completion of the same
upload can commit after it with a list that names those parts, and
remove the directory. The cleanup now frees them only when the key's
current object is this completion's commit (this upload, the same
chunks), checked once the directory is gone, when no routed completion
can commit any more.

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

* s3api: deleteOrphanedChunks takes the context its lookups and deletes use

Fold deleteOrphanedChunksWithContext into deleteOrphanedChunks instead of
keeping a second name; the existing callers pass context.Background().

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

* s3api: check the entry the completion wrote, under the cleanup deadline

The check before freeing the unrequested parts resolved the object by
its key, outside the cleanup deadline. A key ending in "/" is written
inside the directory it names ("dir/" at dir/dir), so the check read
another entry and kept the parts, and a filer that stopped answering
after the commit could hold the completion without a limit. The
completion now records where it writes its object (the version file on a
versioned bucket), and the cleanup reads that entry back, from the write
owner when there is one, under the same deadline as the deletes.

Each part whose manifests resolve is deleted before the next manifest is
read, so a read that runs out the deadline no longer strands the parts
resolved before it.

The cleanup's filer reads, that check and deleteOrphanedChunks' volume
lookup, go through withFilerClient with the deadline, so the deadline
running out is not booked as a failure of the filer and does not open
its circuit for other requests.

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-12-02 03:18:04 -08:00
Chris LuandClaude Opus 5.5 ab6b1598b9 mq/offset: fix a flaky partial-listing test (#13288)
mq/offset: fail the test lookup the way a filer store does

TestListConsumerGroupPositionsReturnsWhatItReadOnAFailure flaked (about
1 in 60 runs): its fake filer failed the unreadable position with
codes.Unavailable and no details, which pb treats as a dead channel. The
shared ClientConn was closed and the concurrent loads of the other
partitions failed with it, so the listing returned one position, not two.

A real filer answers a store read error with a plain error (codes.Unknown),
which keeps the channel. The fake now does the same.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 03:15:58 -08:00
Chris LuandClaude Opus 5.5 9e4e1ade67 filer: conformance suite for filer stores, run against Postgres and MySQL in CI (#13250)
* filer/store_test: conformance suite for filer stores

Entries in and out of buckets, byte-ordered and prefixed listings,
key-value records, transactions, bucket tables and the snapshot scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer: run postgres2 and mysql2 through the conformance suite

RUN_POSTGRES_TESTS and RUN_MYSQL_TESTS enable them, as RUN_REDIS_TESTS
does the Redis stores; each test gets a schema or database of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* ci: give the go test job Postgres and MySQL services

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK

* filer/store_test: create the shared fixtures before the subtests

The scan and delete-folder-children subtests read the order directory that
only the list subtest created, so selecting either one with -run failed on
a conforming store.

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

* filer/store_test: roll back a transaction an assertion abandons

A failed assertion between BeginTransaction and the commit left the
transaction open with its locks, and the cleanup's DROP SCHEMA then waited
on them until the go test timeout.

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

* filer/store_test: check limited listings without trimming the result

The limit-1 checks sliced the listing to one name, so a store that ignored
the limit passed, and one that returned nothing panicked. Allow only the one
look-ahead entry the SQL stores return and compare the first name.

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

* filer/store_test: give the exclusive limit check three eligible names

Starting after a%b left only two names under the prefix, so a store that
ignored the limit still met the one look-ahead bound.

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

* filer/store_test: check that a bucket drop removes nested entries

A store that reports CanDropWholeBucket gets no recursive walk from the
filer, so its DeleteFolderChildren on the bucket has to remove every
descendant. With only a direct child in bkt2, a store that deleted the
direct children and kept the table passed.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:13:02 -08:00
Chris LuandClaude Opus 5.5 51d2b2b712 mq: read a table-backed topic's history from its Iceberg table (#13260)
* mq: read a topic table's data files back as log entries

A view of a topic's table holds the current snapshot's offset map and, per
_partition, its data files with the _offset and _ts_ns bounds from the
manifests. A partition's rows are read by offset or by time, skipping files
and then row groups whose bounds miss the read, and come back as the log
entries they were copied from: key, timestamp, offset, and the message as
_value or as the record re-encoded from its columns. Views are cached per
topic, rechecked every few seconds, rebuilt only when the metadata location
moves, reuse already-parsed manifests, and are evicted past a bound on the
data files they hold. A table that is gone or replaced by another UUID reads
as empty; one with delete files is refused.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a table-backed partition below its table's high-water mark from the table

The merged reader takes the partition's table, looked up on every read so a
table attached later is seen. An offset read below the mark reads the table
up to the mark and continues into the log files and compacted parquet from
the mark; a time read takes the table's rows after the time and then the
files' entries at or above the mark. Log files left below the mark by a
crash between the writer's commit and its delete are never read. The broker
hands its partitions' disk reads to the table through the topic's cached
view; a topic without a table, or whose topic.conf is gone, reads its files
as before.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: start a table-backed partition's offsets at its table

A partition whose log files below the table's high-water mark were deleted
would reload with a high-water mark and log start taken from the files that
are left. Loading it now continues its offsets no lower than the table's
mark and starts its log at the table's lowest offset, or, when the table
holds nothing of it, at the first file offset at or above the mark. A
retired range of a repartitioned topic is read and bounded the same way,
and a retention purge raises the log start likewise, so purging hot log
files never makes the table's offsets out of range.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: keep a flushed data source's finished flag atomic

The streaming goroutine sets finished while the merge loop reads it through
HasMore, which the race detector reports on any scan that reads flushed
data.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: scan a table-backed topic's history from its table

The hybrid scanner hands each partition's merged read the topic's table,
so a scan reads the table's data files below the partition's high-water
mark, pruned by _partition, _offset and _ts_ns, and log files from the mark
on, skipping any a crash left below it. Aggregations no longer answer such
a topic from parquet statistics and log counts, which hold none of its
table's rows; they scan instead.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a schematized row's raw _value back as its message

A schematized topic's table can keep a message that is not a record, a
tombstone or an undecodable value, as raw bytes in an optional _value with
the record columns null. Such a row now reads back as those bytes; a row
whose _value is null reads back as its record, and a schemaless topic's row
as its _value as before.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: delete log files a topic table already holds

A log file or compacted parquet whose every offset is below a partition's
table high-water mark is never read again, so it can go. The mark used is
that of the newest snapshot at least a minute old: a reader's view of the
table is at most a few seconds old, so it already reads those offsets from
the table and never from a file being deleted. Files without an offset
range and the file holding the partition's highest offset are always kept.
DeleteCoveredLogFiles is for the topic's writer after its commit; a leader
also deletes them under its fence on load and on each retention pass,
covering a writer that crashed between its commit and its delete.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: report a topic table's rows as parquet_archive

A table-backed topic's scan labelled every row live_log, its table's
included. The flushed data source now records the high-water mark of the
table its merged read was handed and reports the rows below it, which come
only from the table's parquet data files, as parquet_archive.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: delete the log files a topic table holds after each run

Every mq_topic_table run now ends by deleting, in each partition, the log
files wholly below the offsets of the newest snapshot at least
LogDeleteGrace old, never the leader's newest file. A commit is never old
enough on the run that makes it, so each run deletes what earlier ones
copied; the partition's leader deletes the same files when no run follows.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a time read's position when nothing on disk follows it

A time read that found nothing after its position returned a position at
time zero: the parquet reader reports the newest time it delivered, which
is none. A loop over an empty memory buffer then read the whole partition
from the start, came back to the same empty read, and started over, so a
query asking a broker for its unflushed messages streamed the partition
forever. The merged and the table-tiered readers now keep the position
when they deliver nothing past it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: publish a topic table view under the lock eviction reads it with

A loaded view was stored under its entry's loading lock while eviction,
run by another topic's load, read every entry's view under the cache's
lock, so two topics refreshing at once raced. A view is now stored holding
both locks: a load reads it under the first, eviction under the second.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep no topic table view larger than the whole view cache

Eviction never dropped the view just loaded, so one topic whose table had
more data files than the cache's bound stayed cached past it, and evicted
every other topic's view on the way. Such a view is now answered and not
kept; the others stay.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: look up a topic table's mark again where a read leaves the table

A read kept the table mark it started with. One slow over the table's
rows could outlast the grace: the writer commits past that mark, the logs
below the new mark are deleted, and the read then lists the logs from its
old mark and passes over the deleted offsets without a word. The read now
asks for the table again each time it leaves it and reads on in the table
up to the mark it finds, until the mark stops moving; a time read takes
the rows between the marks by offset. A gap where the logs begin is
checked against the table once more, and read from the table if it took
it meanwhile.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a topic table's timestamps back without going through nanoseconds

A timestamp or time column was turned into micros by way of nanoseconds,
which overflow for dates before 1678 or after 2261, so a year 1 or year
9999 value came back as another date. Each unit now converts to micros
directly. The table fixture wrote every topic's rows whole into _value
once every table had that column, so the record columns these reads take
went untested; it now writes a schematized topic's rows as columns.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* iceberg: order a compaction bin by the first sort field that varies in it

A topic table sorts by _partition, then _offset, and is partitioned by
_partition, so every file of a bin holds one _partition. Ordering the bin
by it kept the files in manifest order, and a merged file's offsets came
out of order for the topic table reader, which delivers a data file's rows
as offsets in order.

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

* mq broker: list a retired range from its table's lowest offset

A topic lookup lists each retired range with the bounds of its own files,
so once the table held a range's history and its log files went, the range
was listed from its newest file on, while its reader serves the table's
offsets below it.

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

* iceberg: never merge compaction inputs across a file left out of the merge

A file already at the target size takes no part in compaction, yet small
files on both sides of it in sort order went into one bin, so the merged
file's bounds spanned it. For a topic table that is a data file whose
_offset range overlaps another's, which a reader finishing one file before
the next cannot read in order. An ordered bin is now cut wherever a file
left out of the merge falls between two of its files, so every merged file
covers a range no file outside its run lies in.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: merge a topic table's overlapping data files by offset when reading

A partition's data files were read one after another by their lowest
offset, which only reads in offset order while no two ranges overlap. A
rewrite by another engine can leave a file spanning another one, and then
a read from inside the overlap delivered the spanning file's later rows
first, and a read that stopped early left the rows in between behind.
Files whose offset ranges overlap are now read together, their rows merged
by offset and an offset held twice delivered once.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: open a topic table's data files only as a read reaches them

A merged read opened every file of an overlapping group before it
delivered a row, and a file the manifest records no offset bounds for
overlaps every other one, so a short fetch held a reader for each file of
the partition's history. The files of a read now wait in a heap keyed by
the lowest offset each can hold, and a file is opened only once nothing
before that offset is left to deliver; a file without bounds is opened
where the read starts, and its row groups' statistics skip what they rule
out.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: retire no log file a topic's table does not hold yet

Retention deleted a table-backed topic's log files by age alone, so with
the table writer behind it deleted messages the table did not hold, and
they were gone from both. On such a topic a file now expires only once
all it holds is below the table's mark of a grace-old snapshot, the same
files the leader deletes as covered; what the table holds ages out with
table retention.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound a table-backed range's bounds by its caller's deadline

The table lookup that widens a partition's bounds ran under a background
context, so a retention pass or a retired-range lookup with a deadline
waited on a stalled table catalog for as long as it stalled. It now runs
under the caller's context.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check a topic table's mark again when a time read reaches its files

A time read caught up with the table and then read the files above the
mark it last saw. A view that had moved on meanwhile, with the logs below
its new mark deleted before the files were listed, left the offsets
between the two marks to neither. The time read now asks for the table
again at the first file entry it would deliver, or after the files if they
held none, and on a moved mark reads the table up to it before reading the
files again.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: bound the topic table views kept, empty ones included, and keep those in use

Eviction only counted data files, so views of tables holding none, and
entries a failed first load left behind, were never dropped; and it could
drop an entry while a caller was loading it, so the next caller loaded the
same table again alongside. A failed first load now leaves no entry, at
most maxCachedTopics views are kept, and an entry a caller still holds is
never evicted. The eviction test now requires exactly the one eviction
that makes room.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check a topic table afresh before deleting the logs below its mark

A leader's covered-log delete and log retention took the table's mark
from the cached view, up to a few seconds old, so a table rolled back to a
lower mark meanwhile had its logs above that mark deleted although it no
longer held them. Both now check the table before acting: the cache takes
a maximum age, a read passes ViewRefresh and a delete zero. A cached view
is also reused only for the same table state, since a commit that rewrote
the metadata in place keeps its location.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* iceberg: leave a sort field holding nulls to order a compaction bin

A sort field whose bounds are one value in every file was taken as
constant and the bin ordered by the next field, yet bounds leave nulls and
NaNs out, so a column holding them besides its one value is not constant.
A field is now skipped only when the files also record no null in it, and
no NaN for a floating point one.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: delete a topic's covered logs only while it still names the table

A run's log cleanup used the table metadata the run started with, so after
the topic left the table, or the run lost its lock, it still deleted the
logs below that table's marks. The cleanup now checks, when it runs, that
it still holds the topic's lock and that topic.conf still names the table
with its recorded UUID, and reads the marks from the table as it is then.
It still runs after a run that failed otherwise.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: check a topic table again before each covered log it deletes

The leader read the table's mark once, listed the files below it, then
deleted them one by one, so a rollback or a detach landing in between went
unseen and files the table no longer held were deleted. The delete now
holds the table writer's lock, so the topic cannot leave the table
meanwhile, and before each file reads topic.conf and the table afresh,
stopping at the first file not below the mark it finds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: let a caller waiting on a topic table's load give up at its deadline

A caller wanting the view a stalled load of the same table was making
waited on a mutex, past its own deadline, for as long as the load stalled.
The entry is now held by a one-token channel a waiter selects on with its
context, so it returns at its deadline and lets go of the entry.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: give up a scan's table lookup when the query is cancelled

The table a scan reads below each partition's mark was looked up under a
background context, and the flushed data source waited on its channels
alone, so a cancelled query stayed blocked on a stalled table catalog. The
scan's context now reaches the topic.conf read and the table lookup, and
the data source returns once it is done.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: take a topic table's lock only when a covered log is left to delete

The leader's covered-log pass took the table writer's lock for every
table-backed partition it leads once the table had a mark, every five
minutes, even with nothing to delete. While a copy run held the lock, each
such partition waited out the lock wait and logged a failure, holding up
the rest of the retention tick. List the covered files first and take the
lock only when there are some; the per-file checks under the lock stay.

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

* mq: drop a topic table view only with the last caller holding it

An oversized view was removed while other callers still held it, so the
next caller loaded it again alongside; an entry no load filled was removed
only by a failing load that was its sole holder, so one whose callers
failed or gave up in another order stayed; and eviction that found every
candidate held left the cache above its bounds with nothing to evict
again. Callers now let go through one release: the last one removes an
entry no load filled or one marked to drop, as an oversized view is, and
each release runs eviction again.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: check a topic's table again before each covered log the cleanup deletes

The cleanup checked the lock, topic.conf and the table once, then deleted
every file below the marks it read, so a detach, a dropped or replaced
table, or a lapsed lease landing during the deletes went unseen. The
deletes now check all three again before each file, with the mark of the
table as it is then, and stop at the first file not below it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: let a flushed data source's producer close its own channels

Next can return on the query's cancellation while the producer is still
sending, and the merge then closes the source, which closed the result
and error channels under that send. The producer now owns them: Close
only signals it to stop, every send also selects on that signal, and the
producer closes the result channel when it exits, after sending its one
error if it has one.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: fail a scan whose data source fails after its first row

The merge only logged an error from a source past its first row, the
query's cancellation included, and returned the rows read so far, so a
cancelled or timed-out COUNT or SUM answered with a wrong number. It now
closes its sources and returns the error, and the scan wraps it, so a
caller can tell the context's error from others.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: check a topic table again before each group retention deletes

Retention read a table-backed partition's deletable mark once, chose its
expired groups, then deleted them with no further look, as the covered-log
delete did before it rechecked; a rollback in between left groups deleted
that the table no longer held. The live and retired purges and the
covered-log delete now share one guard: it holds the table writer's lock
and, before each group or file, reads topic.conf and the table afresh,
stopping at the first one not below the mark it finds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound a partition load's reads of what it already stores

Loading a partition reads its files' offset range and, for a table-backed
topic, the table's, while holding accessLock, under a background context,
so a stalled filer or table catalog held every other partition operation
for as long as it stalled. The reads now get the bound a load's fence
take has; past it the load fails, as it does when the stored offsets
cannot be read, and the caller retries. Falling back to the log files'
bounds would start the log above the table's offsets with no later
refresh to lower it, so consumers resetting to the earliest offset would
skip the table's history.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: count a flushed source's pending error as more to read

The merge asks HasMore before reading a source again, and HasMore looked
only at buffered rows and whether the producer finished, so a producer
that failed after its last row and finished before the merge asked had
its error never read, and the scan returned the rows so far as its
answer. An error waiting counts as more to read now, so Next returns it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: keep the table's files of a topic that left it before the delete

A topic that left its table between the listing of what the table held
and the guard the delete takes got no guard, which let every listed file
go, though readers take those offsets from the logs again. Files chosen
by the table's rules, the covered logs and the groups retention trimmed
to the table's mark, are now kept when no table remains; files of a topic
that had no table when the pass began still expire as before.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query: order the pending-error merge test's row before its error

The test's producer could send its error before the first Next took the
row, and Next then picked either one, so on some runs the error came
through the first read and the test passed without exercising HasMore.
The producer now holds its error until the first Next has the row, and
the merge asks again only after the producer has finished, so the test
fails every time without the pending-error fix.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: read a topic table's chunk-backed files under the caller's context

A manifest or manifest list stored in chunks was read through a stream
reader built without a context, and the stream reader looked up and
fetched each chunk under a background context even when built with one,
so a stalled volume server held a partition load past its bound while it
held accessLock. A chunk stream reader now looks up and fetches its chunks
under the context it was built with, and a table's chunk-backed files are
read with the caller's.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: keep the expiredLogFiles doc comment on expiredLogFiles

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

* mq broker: let the table catalog read chunk-backed table metadata

The broker's table catalog reached its filers through a client with no
way to look up chunk locations, so a table whose catalog record holds
only the location of its metadata, as one whose metadata outgrew a
request does, failed to load once that file was stored in chunks: the
topic's history could not be read. The client now resolves chunks the
way the broker's own filer client does.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* iceberg: read chunk-backed table metadata under the caller's context

A catalog record holding only a metadata location had its chunk-backed
file read by StreamContent, whose lookups and fetches run under a
background context, so a stalled volume server held a table load past its
caller's deadline: a broker loading a table-backed partition under
accessLock past its bound. The read now streams under the read's own
context, which already bounds its other filer calls.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* filer: give up a LookupFn volume lookup's retries at its caller's deadline

LookupFn retried a failed volume lookup through util.Retry, which sleeps
its backoff without looking at the caller's context, so a lookup failing
near a deadline outlived it by up to the whole backoff; a table load under
a broker's accessLock held it that long. The lookup now retries through
util.RetryWithBackoff with the same transient-error rule and about the
same total wait, which stops when the context is done.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:48:04 -08:00
Chris LuandClaude Opus 5.5 284d491587 s3: forward notification topics to webhook targets (#13245)
* util: move the guarded dialer out of the volume server

The deny list and the dialer that re-checks every resolved address at
connect time move into weed/util/netguard, with the allow-private knob as a
policy, so other outbound clients can dial through the same guard.

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

* mq: fence consumer group position saves by generation

A position saved with a generation is written only while the stored one
carries no newer generation, or the same generation from another writer:
the save reads the stored position and writes on the condition that it is
unchanged, routed to the entry's owner filer, and re-reads when another
writer got there first. A single consumer that elects itself can then store
its offsets without a deposed predecessor overwriting them. Saves without a
generation keep overwriting as before.

Loading a missing position now reports ErrNotFound instead of trying every
filer and marking each one failed.

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

* s3: post bucket event batches to a webhook target

A webhook destination renders a batch of records as one
{"Records":[...]} body, posts it with the target's bearer token, and takes
any 2xx as delivered. The renderer is a function the destination holds, a
stand-in that refuses until the record renderer lands. It dials through the
guarded dialer under a new Local policy, which refuses metadata-service,
link-local and unspecified addresses at connect time but lets an operator
point a target at a private host or a sidecar on loopback. Redirects are
followed only to the endpoint's own host and never down from https.

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

* s3: forward each target's topic to its destination

A Forwarder runs beside the Publisher on every gateway. Each enabled target
with a destination gets a lock, s3.notify.<target>, held through
LockClient.StartLongLivedLock, so one gateway forwards a target and targets
spread across gateways; a topic target has none.

The holder runs one loop per partition of the target's topic: fetch from the
stored offset at the partition's leader, decode the records, deliver them as
one batch, store the next offset. A fetch that stops short at a segment
boundary just continues from its next offset. A failed send, a rejected one
included, blocks the partition and is retried with capped backoff, and the
offset is stored only after the destination took the batch. An offset that
retention removed skips to the earliest one and counts the gap.

Offsets go to the consumer group offset storage under group forwarder,
fenced by the lock generation. On taking the lock a forwarder stores each
partition's offset back under its generation, so an older holder's saves are
refused and it stops. A stored generation at or above its own means the
lock was lost, unless the forwarder has since held the lock through a full
renewal, which happens only when the lock server's counter restarted; it
then fences above the stored generation.

Metrics per target: records delivered, send retries, retention gaps, and
lag from the forwarding gateway.

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

* s3api: run notification forwarders beside the publisher

Every gateway with filers starts a Forwarder with the publisher. It elects
itself per target through the gateway's object-write lock client, stores
offsets in the filer, reads through the same brokers the publisher uses,
follows the target registry as the publisher does, and releases its locks
on shutdown.

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

* s3: post a test event to a webhook on its own

The renderer refuses an s3:TestEvent that shares a body with other records,
so a webhook splits a batch around each one and posts them in order, the
test event as its own body. The test is a stand-in until the renderer's
lands.

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

* s3: skip a bucket event record that can never be delivered

A record that does not decode, or that the renderer refuses, used to be
retried like a failed send and would block its partition for good. The
webhook now renders a whole batch before posting any of it and names the
records that cannot render; the forwarder drops those, counts them per
target and reason in notification_skipped_records_total, logs each offset
once, and sends the rest. Only transport and HTTP failures are retried.

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

* mq: read a fenced position save at the filer that applies it

The fenced save read the stored position from whichever filer answered and
then sent its conditional write to the key's owner, so with filers that keep
their own stores the condition could be checked against an entry other than
the one read, failing until replication caught up or judging a stale copy.
The storage now takes the ring's owner lookup, the one route-by-key writes
already use, and sends both the read and the write to that filer. The
gateway hands its object-write lock client's PrimaryForKey to the forwarder
offsets.

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

* s3: follow a repartitioned notification topic

A forwarder listed its topic's partitions once, when it took the lock, so a
repartition left the new partitions unforwarded until the lock moved. It now
lists them again every 30 seconds, starts a loop for each new partition, and
marks the loops of partitions no longer listed as replaced; such a loop keeps
delivering what its partition holds and ends once it has caught up. A
failed fetch now looks up the leader of that exact partition, not of any
partition with the same range.

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

* s3: let the first forwarder take the lock before the second asks

The election test synced both gateways at once, and each forwarder asks for
its lock from its own goroutine, so the second could ask first and store the
offsets the test expected from the first.

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

* s3: warn when a partition returns nothing below its high-water mark

A fetch that returned no records and kept its next offset below the
high-water mark looked like an idle partition, so the forwarder waited
without a word while its lag stayed up. It still waits, since skipping would
lose the records, but now warns at most once a minute with the topic,
partition, offset and high-water mark, so the lag has an explanation.

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

* s3: render webhook bodies with the bucket event renderer

The webhook now renders through Render and posts each s3:TestEvent alone by
IsTestEvent, replacing the stand-ins it held until the renderer landed.
The tests send real records and read the object keys and test request ids
back out of the bodies.

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

* netguard: refuse the IPv6 and Alibaba metadata service addresses

AWS's IPv6 metadata address fd00:ec2::254 is unique-local and Alibaba's
100.100.100.200 sits in the CGNAT range, so the Private and Local
policies let a webhook or remote endpoint reach them. Refuse both under
every policy, like 169.254.169.254.

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

* grafana: chart the notification forwarder metrics

Add an S3 Notifications row with delivered records, lag, send retries,
and records skipped or lost to retention per target.

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

* s3: follow only webhook redirects that keep the POST

On a 301, 302 or 303 Go resends the request as a GET without a body, so an
endpoint that redirected and then answered 2xx counted as delivered while
it received no records. Only 307 and 308, which keep the method and resend
the body, are followed now; any other redirect fails the send and is
retried.

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

* s3: keep webhook endpoint secrets out of errors and logs

The guarded dialer names its endpoint in every refusal, and the forwarder
logs that error, so a webhook endpoint carrying credentials in its userinfo
or a token in its query had them written to the log. The dialer now gets
the endpoint as scheme, host and path only, and the parse and request
errors no longer echo the URL.

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

* mq: load a consumer group position from its owner filer

A forwarder taking over read its start offset from whichever filer answered,
while its fenced saves read and write at the key's owner. With filers that
keep their own stores, a replica still holding an older offset handed the
new holder that offset, which it then stored under its higher generation at
the owner, replaying everything delivered since. Loads now go to the owner
too when the storage knows it.

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

* mq: bound consumer group position loads and saves by the caller

LoadConsumerGroupPosition and SaveConsumerGroupPosition ran their filer
calls under context.Background(), so a filer whose store stalled held a
forwarder's save forever: ending the lead waited on it, the lock was never
released, and Close hung while the lock kept renewing. Both now take the
caller's context; the forwarder gives each call its RPC deadline under the
lead's context, so stopping returns and the lock is released. The offset
wrappers the broker uses keep their signatures.

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

* mq: list a consumer group's positions across partition generations

ListConsumerGroupPositions walks every generation and range directory of a
topic and returns the group's stored position in each, keyed by partition
directory, so a consumer can tell which ranges it holds offsets for that
the topic no longer lists.

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

* s3: stop forwarding ranges a repartition removed

A repartition drops the old assignments, and the broker serves only
assigned ranges, so the loop draining a removed range retried a refused
fetch forever, and after a restart nothing looked at it at all. Reading a
removed range's flushed data would need a read-only path in the broker.
Until then a removed range's loop delivers the batch it holds and ends,
and the forwarder logs an error naming each range it stops and, when it
takes the lock, each partition directory holding a stored offset the topic
no longer lists. The fake broker now refuses unassigned ranges as the real
one does.

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

* s3: deliver what a repartition left in the retired ranges

The lookup now offers the sealed ranges a repartition retired, and any
broker serves them from their files, so the forwarder no longer drops
them. On taking the lock and on each re-list it asks for the retired
ranges too and runs a loop for each, from its stored offset up to its
high-water mark, after which the loop ends; a range it was forwarding as
current and that is now retired gets the same end. A read below a retired
range's log start counts as a retention gap, as for a live one.

A key's records in a retired range precede its records in the ranges that
replaced it, and loops running side by side would not keep that order. So
the retired ranges go first, one generation at a time, oldest first, and
the current ranges start only once none is left. A range listed neither as
assigned nor as retired, as while a drained range is not sealed yet, pauses
until it is offered again.

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

* s3: match a retired range to its forwarding loop by directory

The broker lists a retired range at the second its generation directory
is named for, while the assignment the forwarder started its loop from
carried nanoseconds. After a repartition the retired entry missed the
running loop, so a second loop started on the same stored offset and
delivered the batch the first was still retrying. Key the loops by
partition directory; the fake broker now lists retired ranges and the
fake positions store offsets at that resolution, like the real ones.

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

* s3: replace a paused forwarding loop only once it ended

A range drained but not sealed yet is listed neither as assigned nor as
retired, so its loop is paused and dropped from the lead's loops while
it may still be retrying a batch. Once the range was offered as retired
a new loop started at the stored offset and sent that batch again. Keep
a paused loop until it ends, and start the range again only then.

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

* s3: hold the new ranges while a drained one is not sealed yet

A repartition saves the new ranges before it drains and seals the old ones,
so for a while an old range is offered neither as assigned nor as retired,
and the forwarder started the new ranges at once: a key's new records could
go out before its records still waiting in the old range. On each look at
the topic the forwarder now lists the directories holding a stored offset
that the topic does not offer, and probes each at its offset; one that may
still hold records past it, refused because it is not sealed, holds the new
ranges until it is offered as retired and drained. One that answers with
nothing past the stored offset is settled, sealed and empty or already
delivered, and stays so for the lead. While holding, the forwarder logs at
most once a minute and keeps looking even with no loop running.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: have the fake broker serve only the generation a fetch names

The broker now refuses a fetch naming a generation other than the one it
assigns for the range, unless that generation is sealed and read as
retired. The forwarder tests' fake broker matched an assigned range by its
range alone, so it served the live generation to a fetch for an older,
unsealed one; it now matches the generation too, as the broker does.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold the current ranges until the stored offsets can be listed

A lead whose first look at the stored offsets failed took that as no old
range left unsettled and started the current ranges, delivering a key's
newer records ahead of the ones still in a drained range that is not sealed
yet. A failed look now holds the current ranges as an unsettled range does,
and is retried with backoff and on each partition refresh; the current
ranges start only after a look succeeds. Retired ranges and loops already
running carry on meanwhile.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3api: leave forwarding off on an unusable broker TLS config

The forwarder loaded the grpc.msg_broker client TLS config with
LoadClientTLS, which exits the process on a bad one, and every gateway with
filers builds a forwarder whether or not it has webhook targets. It now
loads it as the publisher does: an unusable config is logged and leaves
forwarding off while the gateway keeps serving.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold the new ranges for an unsealed old range with no stored offset

The check for old ranges still unsealed looked only at ranges holding a
forwarder offset. A forwarder starting for the first time while a drained
range was not sealed yet had stored none in it, so it started the new
ranges and delivered a key's newer records ahead of its older ones. The
consumer group listing now names every partition directory of the topic,
with no position where the group stored none, and such a range is probed
from offset 0. A range with nothing left past that offset, including one
whose records retention already removed, is settled.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: check the load in the fenced save race test

The test read the stored position back ignoring the load's error, so a
failed load panicked on a nil position instead of reporting the error.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: take a partition over at the offset its last holder committed

A new forwarder generation claimed a partition by writing the offset it
had loaded. When the old generation committed again in between, the claim
rewound the stored offset and the new lead replayed what had been
delivered since. A fenced save that takes over from an older generation
now keeps the offset that generation committed last, rereading it on a
conditional write miss, and hands it back in the position, and the
forwarder starts from it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: wait for a position's owner filer instead of asking another

A position store routed by owner fell back to any filer while the owner
of a key was not known yet, as before the lock ring is learned. That
filer's not-found ended the load there, though it may only not have
caught up, and a claim on it would start the partition over. Loads and
fenced saves now fail until the owner is known, and the forwarder
retries them; a store without an owner routing still uses any filer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: wait for the last checkpoint before a forwarder handoff in tests

The resume, repartition and election tests stopped the first forwarder
once its records were delivered but possibly before their offsets were
stored, so they could pass on a replay rather than on a committed
handoff. They now wait for the final offsets first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: have Close wait for removed targets to release their locks

A target removed from the registry had its forwarder cancelled and
dropped from the targets, so a Close soon after did not wait for it and
returned with that target's lock possibly still held. Removed forwarders
are now kept until they are done, and Close waits for them as well.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold newer retired generations behind an unsealed older one

A range of an old generation still unsealed held back only the current
ranges. A generation retired after it was offered and delivered right
away, ahead of the older generation's records of the same keys. The
unsealed range's generation now counts as the oldest one left, so only
that generation's own sealed ranges are forwarded until it is sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: check the forwarder lock right before each send

A lead checked its lock at the top of each fetch and after a failed send's
backoff, so a lead that lost the lock while it fetched a batch still sent
it, and the next holder sent it again. The lock is now checked right
before each send. Delivery stays at-least-once: a lock lost during a send
cancels that send once the lead notices, which may be after the endpoint
took the batch.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: read a retired range past a broker that answers with an error

Any broker serves a retired range from its files, but a fetch took the
first broker's answer even when it was a storage error, and each retry
asked that broker first again, so one broker that could not read the
files held the range up for good. A retired fetch answered with an error
other than an offset out of range now goes on to the next broker, and
returns the error only when none could read it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count ranges held back behind an older generation in the lag

The lag gauge summed what each running loop reported, so the current
ranges held back while an older generation was still unsealed, and the
retired generations waiting their turn, showed no lag however much piled
up in them. On each partition refresh the lead now reports their lag
from the stored offset to the high-water mark, read from the range's
leader or the retired listing, and drops the lag of ranges it no longer
has.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: hold retired generations too while stored offsets cannot be listed

A lead whose look at the stored offsets failed held only the current
ranges and went on forwarding retired generations, though an older
generation it could not see might still be unsealed and hold earlier
records of the same keys. A failed look now holds every range not yet
running until a look succeeds; loops already running carry on.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: read stored offsets only of the ranges a lead does not know yet

The check for unsettled ranges listed every partition directory and read
every stored offset in it one by one under one deadline, before dropping
the ranges the topic offers and those already found settled. A topic
with many past generations could take longer than the deadline on every
refresh and hold a new lead for good. The listing now takes the
directories to skip and reads only the remaining offsets, a few at a
time, and the lead skips the offered ranges and those it found settled.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: test the failed-listing hold with no unsealed range

The failed-listing test also had an older generation unsealed, which
holds the newer ranges on its own once a listing succeeds, so it did not
show the listing guard by itself. A second case has no unsealed range:
nothing goes out while the listing fails, and both the retired and the
current range do once it succeeds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: stop the lead before marking a failed loop ended

A forwarding loop that failed, as on being deposed, was marked ended
before it cancelled its lead. A partition refresh in between saw a
retired range's loop ended, took the range as delivered, and started the
next generation's ranges on the lead that was about to stop. The lead is
now cancelled first, so no refresh acts on the failed loop.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count no retention gap below an offset only claimed

A lead claiming a partition with no stored offset wrote offset 0 to fence
it before reading anything. A lead that stopped there left 0 behind, and
the next one, finding the log start past it, counted those offsets as
lost though no forwarder had ever been at them. A claim made before any
read is now marked as such, a takeover keeps the marker of the entry it
replaces, and only an offset a lead read from counts a gap.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: retry a takeover save at the offset it kept

A claim's save that took a partition over from an older generation kept
that generation's last offset, but when its reply was lost the retry
went out with the offset the claim had loaded. The stored entry was by
then the claim's own, so the retry kept nothing and rewound the
partition, replaying what had been delivered since. A failed save now
retries with the offset and marker the attempt settled on.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: store an offset as read from once the first fetch succeeds

A claimed offset lost its claimed marker only when a later save moved it,
so a lead that read an empty partition and stopped left it marked as
never read. Records published and then removed by retention while no
gateway forwarded the target were skipped without a gap counted or
logged. The first successful fetch now stores the offset as read from,
once per claim, even when it has not moved.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: wait for the stalled topic's publisher before reading it in a test

The worker sets the topic publisher up on its own goroutine, which on a
loaded host can start after Publish has stopped waiting.

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

* s3: keep what a timed-out offset check settled for the next one

A check for unsettled ranges that could not read every stored offset
within its deadline returned nothing, so each retry read the same ranges
again and a long enough history kept the new ranges held for good. The
listing now returns the positions it read along with the error and goes
on past one that fails, and the check probes those and keeps the ranges
it finds settled before reporting the failure, so the next check reads
only the rest. The ranges stay held until a check covers them all.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: say which records the notification lag counts

The lag gauge's help, and the dashboard panel with none, read as every
undelivered record, but the records of an old range still being sealed
after a repartition cannot be read and are not counted. Both now say the
gauge covers the current ranges, the ranges held back behind an older
generation, and the sealed retired ranges.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:45:41 -08:00
Chris LuandClaude Opus 5.5 960230f86d mq: keep keyless and valueless messages in compacted parquet (#13258)
* mq: keep keyless and valueless messages in compacted parquet

mq.topic.compact treated every message without a key, every message
without a value, and every value that happened to parse as a
DataMessage with a Ctrl as a control entry, and left it out of the
parquet it wrote. Kafka records with a null key and tombstones were
gone once retention removed their logs, and so was a JSON string value
whose bytes parse that way.

The only control entry a log holds is a publisher's close marker, which
the broker logged without its Ctrl, as an entry with neither key nor
value. That is now the whole rule, for compaction and for reading
parquet back. A schematized topic's message without a value is still
left out, since its row has no column to hold one.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: ack a publisher's close marker without logging it

The marker a publisher sends when it finishes was appended to the
partition log like a message, minus its Ctrl, so it took an offset and
sat in the log as an entry with neither key nor value that every reader
had to recognize and skip. The broker now acks it and moves on. Every
message the publisher sent before it on the stream was acked first, so
the publisher's wait for its last ack is unchanged. Logs written before
still hold markers, which readers keep skipping.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: log a Ctrl message that carries a key or value

The close-marker branch dropped every DataMessage with a Ctrl, though
one carrying a key or value was published before. Only a bare marker,
a Ctrl with neither, is acked without an offset now; anything else is
stored at its offset as it was.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* query engine: skip only close markers, as compaction does

Compaction now keeps keyless messages and values that happen to parse as a
DataMessage with a Ctrl, but the SQL engine still dropped both from log scans
and live-log counts, while COUNT(*) took parquet row counts from file stats.
After compaction COUNT(*) included messages SELECT did not show. Scans and
counts now use the same rule as compaction and parquet reads.

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

* query engine: leave out a schematized message without a value, as compaction does

Compaction writes no row for a schematized message without a value, so a live
log count that included one dropped by one once its log was compacted. Scans
and live-log counts now skip what compaction skips.

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

* query engine: count only rows among broker-buffered messages

The COUNT(*) fast path added every unflushed broker message, so a close marker
or a schematized message without a value counted until its flush, when the
live-log count left it out. Unflushed messages now count by the same row rule.

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

* query engine: test the broker-buffered count against the scan

COUNT(*) adds the broker's unflushed messages by the row rule a scan of
them uses, but nothing tested it. The count moves into countRows, and
the scan test checks it gives the number of rows the scan returns for a
schemaless and a schematized topic, so close markers and schematized
messages without a value stay out of both.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:10:22 -08:00
Chris Lu 6a9fe874d7 mq: keep a time read's position when nothing on disk follows it (#13259)
A time read that found nothing after its position returned a position at
time zero, since the parquet reader reports the newest time it delivered.
A loop over an empty memory buffer then read the partition again from the
start. The broker's unflushed-message query does exactly that, so once a
partition's buffer was flushed and empty it streamed every flushed message
as unflushed, and weed sql counted each row twice. The merged reader now
keeps the position when it delivers nothing past it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34
2026-12-01 20:33:02 -08:00
Chris LuandClaude Opus 5.5 bc1b805c82 mq: copy a table-backed topic's sealed log data into its Iceberg table (#13256)
* mq: export logstore's log file offset range and control entry checks

The topic table writer decides what is sealed from a partition's file
offset ranges and drops the same control entries compaction drops, so it
calls these instead of keeping copies.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: tell which of a partition's files its leader will not write again

A topic table may only take what is sealed. The fence names a writer
and an epoch, not a file, and each flushed window lands whole as a new
file under it, so every log file but the one holding the highest offsets
is sealed; the newest may still be followed by a window in flight. A
sealed fence takes no more windows, so all of its files are. Parquet
left by mq.topic.compact rewrites earlier logs and is always sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a topic table's copied offsets in its snapshot summary

Each append records seaweedfs.mq.offsets, the first offset of every
partition not yet in the table. A snapshot that rewrote files without
carrying the map defers to its newest ancestor that has one; a table with
snapshots and no map anywhere holds rows of unknown offsets and is not
written to.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: build a topic table's rows from log entries

A message becomes a row of its table: the system columns from the log
entry, then the record's fields by name, or the whole message in _value
for a schemaless topic. Rows are laid out in the table's current schema
through iceberg-go's Arrow mapping, so the Parquet file they are written
as carries the table's field ids and the types Iceberg readers expect.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: compare topic tables by name in topictable

The table writer in the worker has to tell whether topic.conf still names
the table a job was proposed for, by bucket ARN, namespace and name, the
same way the broker compares a configure request with what is stored. The
comparison moves next to the rest of the topic table layout so both call
it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's offset map through maintenance snapshots

Compaction, delete rewrites and manifest rewrites keep a table's rows,
so the offsets a topic table holds are unchanged by them. Their
snapshots now carry the parent's seaweedfs.mq.offsets, so the topic
writer and readers find the map on the current snapshot rather than
only on an ancestor that snapshot expiry may remove.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: start a table's running totals at its first snapshot

Totals were only carried from a parent that recorded them, so a table
whose first snapshot the worker wrote never got total-records or
total-data-files, and no later snapshot could carry them. A snapshot
without a parent adds to an empty table, whose totals are zero.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's sealed log data into its Iceberg table

copyTopicTable reads each partition from the offset the table's current
snapshot records up to what its leader has sealed, through the merged
reader that already serves log files and compacted parquet, and writes
the rows as data files under data/<_partition>/ named by their offset
range. A file holds one partition value, so it never spans partitions or
days, and its rows are one contiguous offset run in offset order.

The append goes through commitWithRetry and records the advanced offset
map in seaweedfs.mq.offsets. Each attempt re-checks that topic.conf
still names the table and that the table still names the topic, and
re-reads the map: a partition another writer moved since this run
planned keeps that writer's offset, and this run's files for it are
removed, so no offset is appended twice. A run that dies before its
commit leaves only unreferenced files for orphan removal. Log files are
left in place; the broker cannot read the table yet.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: run mq_topic_table for topics that name an Iceberg table

The worker registers an mq_topic_table job beside iceberg_maintenance and
runs it in the Iceberg lane. Detection reads every topic.conf under
/topics; a topic naming a table is due once one of its partitions has
128 MiB sealed past the table's offsets or a sealed file 5 minutes old.
Execution takes the filer lock mq.table.<namespace>.<topic>, so one
writer copies a topic at a time, and copies only while topic.conf still
names the table the job was proposed for; a topic that left it ends the
job without failing it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy only into the table whose UUID topic.conf recorded

A table dropped and replaced at the topic's table name still carries
the name, and may carry the topic's property if its creator copied it.
The broker records the UUID of the table it created or adopted in
topic.conf, so the writer checks it before planning and again before
each commit attempt, and stops rather than append the topic's offsets
to a table that is not the one the topic holds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep keyless and valueless messages in a topic table

The table becomes a topic's only copy once copied logs are deleted, and
the writer dropped what compaction drops: every message without a key
or without a value. Those are data; a Kafka record with a null key is
one. The only control entry the log holds is a publisher's close
marker, which the broker stores without its Ctrl, as an entry with
neither key nor value. IsControlMarker names exactly that, IsControlEntry
keeps its wider rule for compaction, and the writer skips markers only.

A keyless message gets a null _key. A skipped marker's offset stays
below the partition's offset in the map, so the table records it as an
offset that held no message rather than a gap left to fill.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: change a topic's table under its table writer's lock

A configure that left a table checked it for snapshots, then saved
topic.conf. The table writer checks topic.conf before each commit, so a
detach saved between that check and the commit's CAS left a table
holding the topic's data with no topic. The broker now takes the
writer's filer lock, mq.table.<namespace>.<topic>, before the release
check and keeps it through the topic.conf save, so it sees what the
writer committed, and the writer sees the change before committing.

The wait is bounded at 15 seconds: a configure behind a long copy is
Unavailable and retried rather than holding the configure RPC. The lock
key moves to topictable so the broker and the worker share it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: make a topic table's record columns optional

A field's is_required became a required column, so a message missing
that field could not be written and the table writer stopped at its
offset. Once copied logs are deleted the table is the topic's only copy,
so every message needs a row. Record fields now map to optional columns
at every level; the system columns stay required. Adopting a table still
refuses one whose record columns are required, since it could not take
such a message.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a message its topic's record type cannot hold in _value

A schematized topic's tombstone, or a value that is not a RecordValue
of its type, stopped the table writer at its offset, and once copied
logs are deleted the table is the only copy. Every topic table now has
an optional _value column. A message whose value is empty, does not
parse, carries bytes a RecordValue does not have, names a field the
table lacks, or holds a value its column cannot take gets null record
columns and its raw bytes in _value. A decoded message leaves _value
null. A row is checked whole before any column takes it, so a fallback
leaves no partial row behind.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's history into its table in bounded runs

A run read every sealed offset past the table's map and committed only at
the end, so a topic attached with a long history could not finish within
the job's one-hour timeout: each attempt rewrote the same files, removed
them on cancel, and the map never moved. A run now stops at a file boundary
once it has written 4 GiB and commits the offsets its files cover; the next
detection picks up the rest.

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

* mq: decode a record read back from compacted parquet into its columns

logstore's parquet reader hands back a schematized row as its RecordValue,
which still holds the file's _ts_ns, _key and _offset columns. The row
writer took those for fields outside the table, so every message the copy
read from mq.topic.compact's parquet landed as raw _value with null record
columns. Those three fields are the entry's own and are now passed over.

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

* mq: map a repeated field already typed as a list to one list

The Kafka protobuf and JSON Schema decoders describe a repeated field with
both a ListType and IsRepeated, and their values are one ListValue deep.
mapField wrapped the list type again, so the column became list<list<T>>
and every message with a non-empty repeated field fell back to raw _value.
Avro gives the item type with IsRepeated, which still gets wrapped once.
MQ's own parquet schema already ignores IsRepeated on a list type.

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

* mq: keep a decimal past its column's precision in _value

rescaleDecimal checked only that the rescaled value fit 128 bits, so an
unscaled value from 10^38 up to 2^127 was written into the decimal(38,18)
column, which engines then read as an overflow or null. The value is now
checked against the column's precision, so such a message keeps its raw
bytes in _value like any other value the record type cannot hold.

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

* mq: bound a published decimal before rescaling it

A DecimalValue's scale, precision and bytes come from the publisher,
and rescaling to the column built 10^|18-scale| before checking
anything, so one message with an extreme scale could hold a worker's
CPU and memory on every retry of the copy. A scale or precision beyond
the column's 38 digits, or a magnitude longer than 32 bytes, cannot fit
decimal(38, 18) and is refused before any arithmetic; the message keeps
its row with its bytes in _value like any other value its column cannot
take.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's files when its commit's outcome is unknown

A commit whose update of the table entry failed without an answer, a
reset connection or a deadline, may still have been applied by the
filer. The run then deleted its data files and manifests, and
commitWithRetry its new metadata file, leaving a committed snapshot
pointing at files that were gone.

Such a failure is now errCommitOutcomeUnknown, and commitWithRetry keeps
the metadata file for it. The topic table writer reads the table again:
a snapshot it built that is in the current lineage is a commit, kept and
reported as one. Otherwise, or when the table cannot be read, the files
stay for orphan removal, since an update still in flight could land
after the read. Only a refused commit, a conflict or a stopped run,
deletes them.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: count a partition's rows after its last flush

copyPartition returned total and flush() in one statement, and Go does
not order reading total against calling flush, so the rows of the last
file could be left out of the count. The last flush now runs first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: report the rows a topic table commit kept

A run's rows_written was every row it staged, though a commit attempt
drops the files of a partition another writer already moved, and a run
that commits nothing reported its staged rows all the same. It is now
the record count of the files the committed snapshot added.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: wait for a topic's table writer outside topicConfLock

A configure that moved a topic off its table waited up to 15 seconds
for the table writer's lock while holding topicConfLock, which every
configure, lookup cache miss and rebalance of every topic takes, and a
caller that gave up kept waiting.

The configure now reads topic.conf first and, when the request moves
the topic off the table it names, takes the writer's lock before
topicConfLock, the order the writer keeps since it never takes
topicConfLock. The wait ends when the caller's context does, and a grant
that arrives after that is released. A configure that finds the table
changed under topicConfLock without holding the writer's lock is
Unavailable and retried.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound the topic.conf read a table change starts with

The read that decides whether a configure must wait for the table
writer runs before topicConfLock, and so before the 30 second bound
lockTopicConf puts on calls made under it. A caller without a deadline
then hung on a filer that took the read and never answered. The read
now gets the same bound of its own, still outside topicConfLock.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep what an unanswered maintenance commit may reference

Compaction, delete rewrite and manifest rewrite delete everything they
wrote when their commit fails. When the failure is an update of the
table entry that went unanswered, the filer may have applied it, and
the table then points at data files, manifests and a manifest list that
were just deleted. Those are now left for orphan removal on
errCommitOutcomeUnknown, as the topic table writer already does;
conflicts and other definite failures still clean up. Snapshot expiry
deletes nothing before its commit succeeds and needed no change.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: test a topic table retry that keeps only one partition's files

A run whose commit loses to a writer that copied only one of its
partitions keeps the other partition's file. The test checks that the
retry reports only that file's rows and that each offset lands once.

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

* mq broker: wait for the detach's refused lock request in the table lock test

A fixed sleep did not show the detach had reached the table lock, so a
late goroutine let the lookup pass with nothing waiting. The fake filer
now counts refused lock requests and the test waits for the first one.

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

* mq broker: check the table writer's lock before saving a table change

A configure that moves a topic off its table holds the writer's lock
from its release check through the topic.conf save, but never looked at
it again. A lease that lapsed meanwhile, its renewals failing, may
already be the writer's, which can then commit to the table the
configure is about to detach. The configure now checks that it still
holds the lock right before the save and is Unavailable otherwise.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: check a topic table copy's lock and topic last before committing

Each commit attempt checked the lock, topic.conf and the table's owner
before writing its manifests and manifest list, and nothing after, so a
lease that lapsed or a detach that landed while they were written went
unnoticed. The attempt now checks again once they are written, the last
step before commitWithRetry saves the metadata file and updates the
table pointer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: read a topic's conf with the topic table job's context

The table writer and detection read topic.conf with ReadConfFile, which
takes no context, so a filer that took the read and never answered held
the job, its worker slot and its renewed table lock, and held up
detection, past any cancel. They now read through
ReadConfFileWithMetadata with the job's or the detection's context, so
a cancelled job ends and lets its lock go.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:29:34 -08:00
github-actions[bot] 228dadd5c0 docs: regenerate star history chart 2026-12-02 03:54:58 +00:00
Chris LuandClaude Opus 5.5 3f2f625822 s3: publish bucket events to each notification target's MQ topic (#13244)
* mq: report when a published message is acknowledged

Publish now returns a channel the publisher closes once the broker acks
that message, including an ack that arrives on a later stream after a
resend. A caller that has to know its message is stored, such as the S3
gateway answering a request only after its event is durable, can wait on
it with its own bound; callers that do not care ignore it.

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

* s3: build bucket event records in the AWS shape

An Event is what one operation did to one object; Record turns it into
an eventVersion 2.7 record for one rule, and Message wraps that record
in the Records envelope a consumer receives. The key is form-encoded per
path segment as AWS does it, size and eTag are left off removals, and
the sequencer is the filer's commit stamp as 16 hex digits, so one key's
sequencers compare as strings in commit order. The s3:TestEvent message
is built here too.

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

* s3: publish bucket event records to each target's MQ topic

The Publisher runs one worker per enabled target. The worker creates the
target's topic, s3.notify-<target> with 4 partitions and 7 days of
retention, then hands records to the MQ publisher keyed by bucket/key so
one object's events stay in one partition in order. Setup retries with
backoff, so a broker that is down or still taking the balancer lock after
a cold start delays records instead of losing them. A removed or
disabled target's worker stops; its topic is left for retention to age
out, since a forwarder may still be draining it.

Publish queues every record and waits up to 2 seconds, or until the
request ends, for all of them to be acked, and reports whether they
were. A record not acked by then stays queued and is still sent; the MQ
publisher resends it across leader changes. Each target's queue holds
10000 records; past that, and for records whose target has no worker, a
record is dropped. Acked, late and dropped records, the queue depth and
the wait are exported as metrics.

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

* s3api: start a bucket event publisher with the gateway

The gateway creates one event publisher and syncs it with the target
registry whenever the registry loads or changes, so each enabled target
gets its topic and worker. The publisher bootstraps from the broker the
command started beside the gateway, passed in as MqBroker once it bound,
and from every broker the masters list, so a gateway running without its
own broker still finds the cluster's. Broker connections use the
grpc.msg_broker TLS section. Shutdown stops the workers.

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

* s3api: send the test event before storing a notification configuration

Unless x-amz-skip-destination-validation is true, PUT notification
publishes an s3:TestEvent to the topic of every target the configuration
names, in parallel, and fails with InvalidArgument listing the
destinations whose topic did not ack it within the publisher's 2 second
wait. Nothing is stored in that case. The registry checks still run
with the header, and an empty configuration sends nothing.

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

* s3api: publish ObjectCreated events for PUT and POST

A PUT, including a "dir/" marker, publishes ObjectCreated:Put and a POST
upload ObjectCreated:Post, after the filer commit and before the
response, once per matching rule of the bucket's configuration, waiting
for the acks within the publisher's bound. A failed write publishes
nothing and a slow or absent broker never fails the request.

The sequencer is the filer's stamp of the commit. putToFiler records it,
from the routed ObjectTransaction or the lock path's CreateEntry, with
the committed size, into the request so the handler finds it; the marker
write and a create recovered after an ambiguous route return none, and
take the gateway's clock instead.

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

* s3api: publish ObjectCreated events for copy and multipart completion

CopyObject, including a metadata-only copy onto itself, publishes
ObjectCreated:Copy, and CompleteMultipartUpload publishes
ObjectCreated:CompleteMultipartUpload, both after the commit and before
the response; a copy that keeps the connection alive publishes before
its final answer.

The write wrappers these use dropped the transaction response, so they
now return the filer's commit stamp: routedMkFile, writeMultipartObject,
routedVersionedFinalize, routedMultipartFinalize, routedSelfCopy and
finalizeCopyDestination. Writes that go off the owner, through mkFile,
still return none and the event takes the gateway's clock.

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

* s3api: publish ObjectRemoved events for deletes

DeleteObject and DeleteObjects publish ObjectRemoved:DeleteMarkerCreated
when a delete without a version id leaves a marker in place of the key,
in a versioning-enabled or suspended bucket, and ObjectRemoved:Delete
for any other delete, including the delete of a marker by its version
id. The record carries the marker's or the deleted version's id.
DeleteObjects publishes one event per key it deleted and waits for all
of them at once.

The routed delete wrappers now return the filer's commit stamp:
routedDeleteSpecificVersion, routedDeleteNullVersion,
routedDemoteNullVersion and createDeleteMarker; deleteMutationResult
carries it to the handler. A suspended delete uses the stamp of the null
version's delete, since the marker write after it returns none. Deletes
on the lock path go through DeleteEntry, which has no stamp, and take
the gateway's clock.

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

* mq: report the ack of a published record too

PublishRecord now returns the same ack channel as Publish, so a caller
publishing to a topic with a record type can wait for its record to be
stored. Both go through doPublish, which registers the waiter for every
message.

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

* s3: carry bucket events as schematized records

A notification topic now has a record type, EventRecordType, the single
source for its flat snake_case columns: the event, requester, bucket and
object fields, the commit stamp as sequencer, and multipart columns for
later. event_time, event_name and bucket_name are required, the rest
optional, and changes to it are additive only. The topic is configured
with it, with bucket_name and object_key as key columns and the schema
format left empty as for the other schematized topics, and records go
out through PublishRecord.

The record holds raw values: the object key unencoded, the sequencer as
an int64, and nulls where a value is absent, such as size and eTag on
removals. Render turns records into the AWS JSON a destination receives,
the Records envelope with eventVersion 2.7, a form-encoded key and a hex
sequencer, or the test event message for an s3:TestEvent, so forwarders
produce exactly the body the gateway used to publish.

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

* s3: shut a stopped target's publisher down even while it is blocked

With the broker away long enough to fill a partition's unacked buffer,
the worker blocks inside PublishRecord. Removing, disabling or closing
the target only cancelled the worker's context, which the blocked worker
never looked at, so the publisher and its queued records lived on and
resumed sending once the broker came back. Stopping a target now shuts
its MQ publisher down directly, which releases the blocked publish, and
does it in the background so Sync and Close do not wait for the flush. A
publisher that finishes setting up after the stop is shut down at once,
and a worker that dequeues a record after the stop drops it.

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

* s3api: publish nothing for a retried multipart completion

A CompleteMultipartUpload retried after the object committed is answered
from that commit and writes nothing, yet the handler still published an
ObjectCreated:CompleteMultipartUpload, with size 0 since no commit was
noted. AWS sends the event once, for the completion that created the
object, so the handler now publishes only when the request itself
committed.

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

* s3api: take an event's principal from the authenticated identity only

With auth off, the gateway keeps the s3-account-id header the client
sent, and an event's principal_id fell back to it, so any client could
name itself as the requester in the record a destination trusts. The
principal is now the identity name authentication put in the request
context, or anonymous.

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

* s3api: turn notifications off instead of exiting on a bad broker TLS config

The event publisher loaded the grpc.msg_broker client TLS with
LoadClientTLS, which exits the process on a config it cannot use, such
as a cert without its key, so a broker-only TLS mistake took the S3
gateway down even with no notification targets. It now loads it with
TryLoadClientTLS and, on an error, logs it and runs without a
publisher: object writes publish nothing and a notification
configuration's test event fails. It never falls back to an insecure
connection.

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

* s3: count a record dropped while its request waits only as dropped

A record dropped while a request waited for it, by a PublishRecord error
or its target being stopped, was counted dropped where it was dropped,
and then late when the request's wait ran out, which it also sat
through in full. Each queued record now carries a done signal that both
its ack and its drop close, so the wait ends as soon as the record's
fate is known and the drop is not counted again as late. Late still
counts a record that was neither acked nor dropped when the request
answered.

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

* mq: let a caller cancel starting a topic publisher

NewTopicPublisher returned only once a partition lookup succeeded, and
retried the lookup for as long as the broker refused it, with nothing a
caller could stop it with. It now takes a context that bounds the start:
the topic configuration runs under it, and cancelling it stops the
lookup loop and returns an error. A publisher already returned is not
affected. Existing callers pass context.Background().

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

* s3: stop a removed target's publisher that is still starting

A target's MQ publisher was started without the worker's context, so a
target removed while its partitions had no leader kept its publisher
looking them up, and its worker waiting, until a lookup succeeded. The
worker's context now bounds the start, so removing or disabling the
target ends both.

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

* s3: bound each broker's ConfigureTopic during a target's setup

Setup asked each broker in turn to configure the target's topic with
the worker's context alone, so a broker that accepted the call and never
answered held the worker there for good. Each broker now gets 10
seconds before setup moves on to the next, and a stopped worker does not
ask the rest.

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

* s3api: stamp a suspended delete's event with its marker write

A suspended-bucket delete removes the null version, then writes the null
delete marker and points latest at it. Its DeleteMarkerCreated event
took the stamp of the first step, so a write landing between the steps
got a later sequencer although the marker it lost to is what remained.
The event now takes the stamp of the pointer write, the delete's last
commit.

To get it, MkFile, the gateway's mkFile and
updateLatestVersionInDirectory return the CreateEntry stamp, and
createNullDeleteMarker returns it. createDeleteMarker's unrouted path
and writeMultipartObject off the owner now return their write's stamp
too instead of none.

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

* mq: bound each broker's ConfigureTopic when a publisher starts

NewTopicPublisher configures the topic again before its lookups, with
no deadline per broker, so a broker that accepted the call and hung
held the start until the caller gave up, even with a healthy broker
next in the list. Each broker now gets 10s before the next is tried.

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

* s3api: sequence a key's events only with stamps from its owner filer

The previous change stamped a suspended delete's DeleteMarkerCreated
with the null marker's pointer write, but that write goes to the
gateway's default filer, not the key's owner. Filer clocks differ, so a
delete could get a smaller sequencer than the PUT before it, and a
consumer deduplicating on the sequencer would drop it as stale.

Routing the marker write to the owner would move the suspended delete
onto the transaction path, a change to the write itself. Until then the
event goes back to the stamp of the null version's routed delete on the
owner, and gateway clock when the delete is not routed. The same
reasoning applies to the other stamps that change began returning from
off-owner writes, a delete marker or a multipart object written through
mkFile, so those return none again, and MkFile, mkFile and
updateLatestVersionInDirectory go back to returning only an error.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count each queued record once as acked or dropped, and late apart

A drop counted the record as dropped and then closed its done channel,
so a request whose wait ran out between the two still saw it pending and
counted it late in the same counter. Each queued record now has a
terminal outcome, acked or dropped, set once by compare-and-swap, and
notification_records_total counts that outcome alone, so every lost
record shows as dropped exactly once.

Late moves to its own counter, notification_records_late_total, counted
once per record when its request stops waiting on it before it is acked
or dropped; that record is still counted acked or dropped when it
settles.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3api: publish the event of a completion recovered after its commit

When a finalize committed but returned an error, completeMultipartUpload
answered from committedCompletion without noting the commit, so the handler
published no ObjectCreated:CompleteMultipartUpload. A retry is answered as
a replay and publishes nothing either, so the event was lost although the
object exists. The recovery now notes the commit when the stored object
holds this attempt's parts, stamped by the gateway clock as the filer's
stamp is not known. One answered from another attempt's commit stays
silent.

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

* s3api: sequence a recovered completion's event with its entry's commit stamp

A completion whose finalize committed but returned an error is answered
from the stored object, and its event took the gateway clock. The stored
entry carries CommitTsNs, the meta log stamp the committing filer gave
the write, from the same sequence as the stamps the routed write paths
return, and peers that replicate the entry keep it. The event now takes
that stamp, and falls back to the gateway clock only for an entry
written by a filer that predates it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:53:18 -08:00
Chris LuandClaude Opus 5.5 2cde975c25 mq: read, list and purge the ranges a repartition retires (#13249)
* mq: seal a partition's fence when a repartition drains it

Draining a partition shut it down and answered at once: its last window was
still being flushed, and its fence was left unsealed. A publisher still
holding the old assignment could then load the range again on its leader at
the same epoch and append to a range the topic no longer lists, so nothing
could treat a removed range as complete. The drain now waits for the last
flush, waiting out a retirement already pending too, and seals the fence
before it answers; a drained range its leader does not have loaded has its
stored fence sealed as found.

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

* mq: serve a sealed range a repartition removed from its files

A repartition drops the old ranges from the topic, and a fetch for one was
answered partition not found, so whatever a consumer had not read from it
was out of reach. A fetch naming a generation and range the topic no longer
assigns, whose fence is sealed, is now served read-only by any broker:
a stopped log buffer over the range's files, with its log start and
high-water mark read from them, answers through the same stateless read as
a live partition, out-of-range included. A reader is reused for 30 seconds,
so a purge elsewhere shows soon. An unassigned range whose fence is not
sealed may still take writes and keeps the old answer.

The test filer can now keep what is uploaded to it, so flushed windows read
back.

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

* mq: list a topic's retired ranges in the partition lookup

LookupTopicBrokers takes include_retired and then also answers
retired_partitions: each sealed range of an earlier generation the topic no
longer assigns that still holds data, with its log start and high-water
mark, read from the range's files. A consumer can find what a repartition
left behind and fetch it. Unsealed ranges are left out, since they may
still take writes.

The test filer lists the directories an entry's path implies, as the filer
does.

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

* mq: purge retired ranges past retention

The retention pass hands each partition with expired files to its leader,
but it walked only the topic's current assignments, so a range a
repartition retired kept its files forever. The balancer now purges each
sealed retired range itself, deleting its expired files under the sealed
fence as read. As for a live partition the newest file stays, so the range
keeps its high-water mark and a read below the raised log start is out of
range. The purging broker drops its cached reader of the range.

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

* mq: the offset scan of a partition's files stops with its caller

Retired fetches and listings, the retention pass and a follower take-over
now pass their context to the filer scan, so a cancelled lookup or a broker
shutting down does not wait on a filer that stops sending entries.

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

* mq: drain a repartition's old ranges only after saving the new topic.conf

A repartition drained the old ranges before saving the topic.conf that
replaces them, and a drain now seals them. When that save failed, the
ranges topic.conf still assigned were sealed: their leader could not take
their fence again, and with every broker healthy nothing moved the epoch on,
so the topic took no more writes. The old ranges are now drained after the
save, so a failed save leaves them assigned, unsealed and writable.

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

* mq: leave a drained range's fence to a holder still renewing it

A drained range its leader had not loaded had its stored fence sealed as
found. If a follower had taken that fence over and was still storing the
records it acked, the seal replaced its token, so its remaining writes
failed the fence check and those records never reached the range. The drain
now seals a found fence only once nobody has renewed it for fenceSealWait,
the same test a new leader applies; a holder still renewing it seals it
itself when done, and the drain waits for that.

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

* mq: seal a range drained while its broker shuts down

Once a broker shutdown has started it retires every partition itself, so
removing one for a drain reports false, and the drain answered success
without sealing the range. It now waits for the shutdown's last flush of the
partition and seals the fence like any other drain.

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

* mq: read retired ranges without a log buffer, dropping old readers on access

Each retired range's reader was a stopped log buffer, which still allocated
the buffers and windows a writer needs, and cached readers past their time
were dropped only when another was created. A retired range is now read
through ReadFlushedMessagesAtOffset, the stateless disk read with its chunk
cache and nothing else, answering out-of-range and end of partition as a
live buffer does; the disk read helpers take the read function and cache
instead of a buffer. Readers past retiredReaderTTL are dropped on every
lookup.

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

* mq: bound the retention pass over retired ranges

The pass over a topic's retired ranges ran under the broker's own context,
so a filer that stopped answering its listing or offset scan held the
balancer's retention loop for good. Each topic's pass over its retired
ranges now has generationPassTimeout, as handing expired partitions to
their leaders does. The test also covers a fetch of a retired range
returning with its caller.

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

* mq: a drain seals a stale fence only as it read it

A drained range its leader had not loaded is sealed once its fence has gone
fenceSealWait without a renewal. The seal required only the fence's token,
which a renewal keeps, so a holder that renewed between the drain's read and
its seal still had the fence sealed under it, and its remaining writes failed
the fence check. The seal now requires the entry as read, as a new leader's
take does, and a drain that loses that race looks again.

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

* mq: finish the drains a stopped balancer left behind

A repartition saves the new topic.conf and then drains the old ranges. A
balancer that stopped in between left them unsealed, and nothing came back
to them: repair looks only at topic.conf, and retired reads, listing and
retention skip unsealed ranges, so their records were out of reach. The
balancer's periodic pass now also looks for range directories that
topic.conf no longer names and whose fence is unsealed, and asks the
broker holding the fence to drain the range, which flushes what it holds
and seals it. A holder that does not answer is drained by the balancer
itself, which seals the fence only once nobody has renewed it for
fenceSealWait. Each topic's pass is bounded by generationPassTimeout.

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

* mq: finish a predecessor's drains on taking the balancer lock

The pass that finishes drains a stopped balancer left behind ran only with
the retention loop, so after a balancer restart its old ranges could stay
unsealed, and unreadable, for up to five minutes. A broker that finds
itself the balancer now runs the pass once right away in the background,
bounded per topic as the periodic one is, so the wait is down to the
fenceSealWait rule.

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

* mq: report a drain's error on the test goroutine

Two drain tests ran the drain, which fails the test on error, in a
goroutine of their own, where failing only ends that goroutine and leaves
the test waiting or passing on what it saw. The drain's error now comes
back over the channel the test already waits on, and the test fails there.

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

* mq: drain a repartition's replaced ranges outside the topic.conf lock

A repartition drained the replaced ranges while it still held topicConfLock,
under the lock's 30-second deadline, and the drain now waits for each
range's last flush and seal. A slow flush held every cache-miss read of
topic.conf behind the lock, could run the shared deadline out and leave a
range unsealed, and left the new ranges' assignment to a context that had
already expired. The new ranges are now assigned under the lock, and the
replaced ones drained after it is released, with a deadline of their own
sized for a flush and a seal that may wait out fenceSealWait. A range the
drain does not get to is finished by the balancer's pass over orphaned
ranges.

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

* mq: move a retired read past offsets no stored entry holds

A read of a retired range at an offset no stored entry holds, below the
high-water mark, answered no records with the same next offset and no end
of partition, so a consumer asked for that offset again forever. Such a
stretch is a gap in the offsets or entries the log could not place. The
read now looks for the lowest stored offset after it and reads from there,
and when none is held up to the high-water mark it answers the end of the
partition at the high-water mark. Below the log start the read is still
out of range.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: serve a client only the partition generation it names

A partition is found by its range alone, so a fetch naming an older
generation of a range the topic still assigns, not sealed and so not read
as retired, was answered from the live partition of the newer generation:
the client read records of a generation it never asked for, at offsets that
mean something else there. A client that names a generation now gets only
that one: one that is not the assigned generation, or not the one loaded,
is refused with the partition not found a removed unsealed range gets. A
client that names none still matches by range. A publisher refused this way
looks the topic up again, as it does when the balancer is ahead of the
cached topic.conf, and the unflushed-message query and the flush
notification check the generation too.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: decide orphaned ranges under the topic.conf lock from the stored conf

The pass that finishes unfinished drains took topic.conf from the cache and
listed the stored ranges without the topic.conf lock. A balancer just
elected with a stale cache, or a repartition saving its new generation
between the read and the listing, made current ranges look orphaned, and
they were drained and sealed. The pass now takes topicConfLock, reads
topic.conf from the filer, lists the stored ranges and decides under it,
then drains what it found once the lock is released; a repartition cannot
assign a generation that is already gone, so the decision holds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: drain only the partition generation a drain names

A drain found the loaded partition by its boundaries alone. A topic
repartitioned 1 -> 2 -> 1 has its first range and its current one on the
same boundaries, so finishing the first one's unfinished drain removed and
sealed the current range instead. A drain naming a generation now takes a
loaded partition only of that generation; otherwise it seals the named
generation's stored fence, as for a range its leader has not loaded.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: leave an orphaned range's own drain time when its holder stalls

Finishing an orphaned range's drain asks the broker holding its fence
first and drains the range itself when that fails. The holder's call had
the whole per-topic deadline, so a holder that took the call and never
answered used it up, and the drain here then ran on an expired context and
did nothing. The holder now gets half the time that is left, keeping the
rest for the drain here.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: end an unflushed query a broker would redirect to itself

A broker still holding an older generation of a range it now leads under
a newer one refuses a query for the newer generation, looks the range up,
finds itself as the leader, and redirected the query to itself, which did
the same again until the caller gave up. When the lookup names this broker
the query now ends with an error saying the generation is assigned here but
not loaded; a lookup naming another broker is still followed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: refuse a loaded generation the topic no longer assigns

After a split the old range stays loaded on its broker until the drain
unloads and seals it. A fetch naming that generation passed the generation
check, since no assignment shares its range any more, and was served from a
buffer that is neither assigned nor sealed. A loaded partition is now served
by generation only while topic.conf assigns it; the cache is reread once
before refusing, so a broker whose cache predates the assignment that loaded
the partition still serves it. Once the drain unloads and seals it, the
retired reader serves it from its files.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq logstore: retry a parquet reader whose topic.conf read failed

The parquet reader reads topic.conf once, when it is built, and a failed
read left it a reader that finds nothing, for good. A merged offset read
then skipped the compacted offsets to the first log file, and a sealed
partition's reader, finding nothing stored, ended the partition at its high
water mark. The reader is now set up on its first read and again on each
read while topic.conf cannot be read, failing those reads; a topic.conf that
does not exist still means no compacted rows.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a drained range from reloading until its seal lands

A drain unlisted the range once its last flush landed, before sealing its
fence. A publisher whose topic.conf cache still assigned the range to this
broker could load it again in between, take the fence at the same epoch,
and make the seal fail, leaving the range unsealed after the repartition.
The drain now holds the range as retiring until its seal returns, so a
loader waits and then finds the fence sealed. A failed seal releases it,
unsealed and unassigned, for the orphan pass.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: seal a drained range only once all it accepted is stored

A drain sealed the fence after the partition's last flush returned, without
asking whether that flush stored anything. A flush abandoned when a broker
stop ran out its flush budget drops the window and breaks the follow stream
so the follower stores its copy, but the seal could land first, and the
follower, finding the fence sealed, gave up records the leader had
acknowledged. The drain now seals only when the flushed watermark reaches
the last accepted offset; otherwise it leaves the fence to the follower and
fails, and a later drain or the orphan pass finds it sealed by the follower
or seals it once it is stale.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:36:14 -08:00
Chris LuandClaude Opus 5.5 d915787cf1 mq: a topic can name an Iceberg table in a table bucket (#13246)
* mq: add a table option to topic configuration

ConfigureTopicRequest, ConfigureTopicResponse and
GetTopicConfigurationResponse carry a TopicTable: the table bucket ARN,
namespace and name of the Iceberg table that holds the topic's compacted
history. A request without it keeps whatever the topic has; one with an
empty table bucket ARN asks to detach it.

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

* mq: map a topic's record type to an Iceberg table layout

The topictable package lays out the table a topic's compacted history
goes into. Its columns are _partition, _offset, _ts_ns, _ts (a
timestamptz copy of _ts_ns to partition on) and _key, then the record's
fields, or _value for a schemaless topic. Scalars map to their Iceberg
counterparts, TIMESTAMP to timestamptz, records to structs and repeated
fields or list types to lists, with required-ness taken from the field.
A DECIMAL field has no precision or scale of its own, so it takes the
decimal(38, 18) the topic's parquet files already use.

The spec is identity(_partition) and day(_ts), the sort order _partition
then _offset, and the seaweedfs.mq.topic property names the owning topic.
CheckSchema says whether an existing table can hold a topic's rows,
matching columns by name so the ids a table assigns do not matter.

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

* iceberg: create and load a table in process

The create handler splits into planCreateTable, which checks the name,
authorizes the create and builds the first metadata, and
registerCreateTable, which stages the metadata file and registers the
table, with stage-create still handled between them in the handler.
Server.CreateTable runs both for a caller inside the cluster, and
Server.LoadTable answers what a load does, sharing the GetTable call and
the metadata parse with the handler. A server-side component that needs
its own table now gets the same location, metadata file, exclusive
staging and cleanup as a REST client, rather than writing metadata by
hand.

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

* mq broker: keep a topic's table in topic.conf

ConfigureTopic stores the requested table with the rest of the topic's
configuration, so it survives restarts and moves to another balancer. A
request that does not name a table keeps the stored one, including one
that changes the partition count, and an empty table bucket ARN detaches
it. GetTopicConfiguration returns it.

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

* mq broker: create or adopt a topic's table on ConfigureTopic

When a configure names a table, or changes the schema of a topic that
has one, the balancer loads the table through the Iceberg catalog the
broker now keeps over its filers. A missing table is created through the
catalog's own create path with the topic's layout and the
seaweedfs.mq.topic property; the table bucket and namespace must already
exist. An existing table is accepted only if that property names this
topic, its location is inside its table bucket, and its columns can hold
the topic's rows, so a topic never takes over a table it did not create
and a schema change the table cannot follow is refused.

The broker creates the table with no caller identity, as trusted
cluster tooling, so the table is owned by its namespace's owner like any
other table there. Deleting a topic only removes /topics and leaves the
table.

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

* mq broker: refuse to leave a topic table that holds data

A configure that detaches a topic from its table, or points it at
another one, first loads the current table, and is refused while that
table has any snapshot: its history would be left with no topic to read
or trim it. A table that is still empty, or that its owner has dropped,
can be left, and stays where it is with its property. Detaching a table
that holds data is left to an explicit command.

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

* mq broker: pass the table catalog's answers through the filer accessor

The filer accessor treats any error as a failed filer: it records the
failure, asks the next filer and wraps the last error with %v. A catalog
answer such as NoSuchTable then reached ConfigureTopic as an opaque
string, so a missing table was reported instead of created. The catalog
now goes through an adapter that returns the catalog's own answers
unwrapped and leaves failover to real filer failures.

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

* mq broker: a table hidden by its policy still holds the topic's history

GetTable answers NoSuchTable both for a table that is gone and for one a
policy denies the caller, so a topic whose table carried snapshots under
a policy denying GetTable could detach as if the table had been
dropped. When the catalog says the table is missing, the broker now
looks for its record in the filer with the new s3tables.TableRegistered,
which finds what GetTable finds before policy, and refuses to leave a
table that is registered but unreadable.

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

* mq broker: fail over the table catalog's internal errors

The adapter between the table catalog and the filer accessor passed
every S3TablesError back as a successful filer call. An InternalError is
what the catalog answers when its own read of the filer fails, so a
broken filer was recorded healthy and no other filer was asked. Only
the catalog's refusals pass through now; an internal error goes back to
the accessor, which marks the filer failed and tries the next one.

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

* mq: name a table's owning topic by its path under /topics

The seaweedfs.mq.topic property was <namespace>.<topic>, and topic names
may hold dots, so a.b/c and a/b.c wrote the same value and either could
adopt the other's table. The value is now <namespace>/<topic>, the
topic's directory under /topics: two topics that write the same value
already share one topic.conf, so they are the same topic.

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

* mq: reserve the day partition field's name in a topic's table layout

The spec partitions by day(_ts) under the name _ts_day, and Iceberg only
lets a partition field share a column's name when it is that column's
identity. A topic with its own _ts_day field mapped fine and then failed
the table create with an invalid partition spec. Schema now refuses the
name up front, with the system columns, saying it is reserved.

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

* mq broker: let the table catalog fail over to every discovered filer

The broker's filer accessor lists only the current filer, so the
failover the catalog adapter relies on had nowhere to go: an internal
error from the current filer failed the catalog call even with another
healthy filer discovered. The catalog now gets an accessor of its own
over every filer the broker has discovered, the current one first, read
under the lock that guards them. The broker's shared accessor stays on
the current filer, so topic.conf, offsets and the subscriber coordinator
keep reading one filer as before.

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

* mq broker: a topic leaves a table that no longer names it

A table dropped and replaced under the same name by one that does not
carry the topic's property holds none of the topic's history, so its
snapshots no longer keep the topic from detaching, switching tables, or
following a schema change.

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

* s3tables: keep tableMetadata's doc comment on tableMetadata

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

* mq broker: walk the table catalog's filers in order, current first

FilerClientAccessor shuffles the filers it is given, so the catalog's
create, load and registration calls each went to a random discovered
filer even while the current one answered. A filer with its own store
may not yet hold what another just wrote. Try the current filer first
and move on to the others only when it fails, as the S3 gateway does.

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

* Revert "mq broker: a topic leaves a table that no longer names it"

The property alone does not show the table was replaced: a
set-properties commit on the same table changes it and keeps the
snapshots, and the topic would then leave its history behind. Telling a
replacement apart needs the table's identity stored with the topic.

This reverts commit ddeb10a89b.

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

* mq broker: tell a replaced topic table from its own by UUID

A topic could not leave a table that was dropped and replaced at its
name by an unrelated table holding data: the snapshot guard refused to
detach or switch, and the ownership check refused to adopt. A changed
seaweedfs.mq.topic property does not prove a replacement, since a
set-properties commit keeps the same table and its snapshots.

TopicTable now carries the Iceberg table UUID, which the broker records
in topic.conf after it creates or adopts the table; a request cannot set
it. Requests are compared by bucket ARN, namespace and name only. When
the topic leaves its table, a loaded table whose UUID differs from the
recorded one is a replacement and is let go without the snapshot guard.
A matching UUID, or a topic.conf written before the UUID was recorded,
stays under the guard. Taking a table at the name still goes through
the ownership and schema checks.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:48:29 -08:00
Chris LuandClaude Opus 5.5 a8f13e7db2 filer: keep a PUT under /etc inline like a POST (#13241)
* filer: keep a PUT under /etc inline like a POST

The write handler marks /etc paths (and saveInside=true) to be stored as
inline content, but only the multipart POST path honoured it. A plain PUT
went through the chunk uploader, which keeps content inline only below
saveToFilerLimit, 0 by default, so `curl -T x.json http://filer/etc/...`
stored chunks and the loaders that read /etc files from inline content saw
nothing.

Both paths now share one saveInside write: read the body, check
Content-Md5, store it as the entry's content. An append to a chunked file
is refused for PUT as it already was for POST, and an offset write is
refused for both instead of being treated as a whole-file write.

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

* filer: skip the saveInside PUT digest checks under fips140=only

GODEBUG=fips140=only refuses MD5: the filer neither checks Content-Md5
nor reports Content-MD5, and crypto/md5 panics. The bad-digest test is
skipped there, and the inline-store test checks the digest only when MD5
is available while always checking the content is inline with no chunks.

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

* filer: answer a malformed write offset with 400

A negative, non-numeric or overflowing ?offset, and an offset with
op=append, were plain errors that the write handler answered with 500,
while a positive offset to inline content got 400. Both the inline and the
chunk path now parse it through one helper whose error carries the
ErrMsgInvalidOffset prefix, mapped to 400. offset=0 stays a whole write.

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

* filer: charge a saveInside PUT its whole body like a POST

A PUT stored inside the entry is now buffered whole by saveInsideEntry,
but uploadCharge still charged it by chunks, so -concurrentUploadLimitMB
no longer bounded the memory it holds. It is charged as the POST is: its
declared length, at most the whole budget, or the whole budget when the
length is unknown.

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

* filer: bound a body stored inside the entry at 16 MiB

A saveInside or /etc upload is read into memory whole, and nothing capped
it: one PUT or POST could grow the filer's memory without bound, as the
upload charge limits concurrency rather than bytes. The read now stops at
16 MiB, far above any config file, and a larger body is answered 413 with
nothing stored, whether or not its length was declared.

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

* filer: keep inline storage to entries inside /etc/

The /etc check was a bare string prefix, so a PUT to /etcd-backup/snap.db
or /etcetera took the saveInside path and a large body was refused with
413 instead of chunked. Match /etc/ as a directory for the write, upload
charge and zip extract paths.

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

* filer: bound a zip member kept inline like a saveInside upload

A zip member extracted under /etc/ (or with saveInside=true) is read into
memory whole, but was bounded only by the 1 TiB archive limit. Refuse a
member over saveInsideMaxBytes, as a PUT or POST body is.

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

* filer: keep a multipart POST to the bare /etc directory inline

A POST to /etc with a file name lands the file inside the /etc directory,
but the /etc/ prefix check missed the bare path and stored it as chunks.
Match /etc itself as well as entries under it.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:46:59 -08:00
d715c4e28f mount: buffer a write in memory when the swap file cannot take it (#13205)
* mount: buffer a write in memory when the swap file cannot take it

The dirty pages of a random write, or of more files than the memory budget
holds, go to a swap file under -cacheDirWrite (by default -cacheDir). On a
full cache disk the swap file cannot be created, or a write into it fails,
and the FUSE write failed with EIO (#12655; before it the mount panicked or
acknowledged a write it had not kept). The data was still in hand.

Such a chunk now stays in memory. A chunk whose swap write fails is sealed
with what it holds, so its upload keeps that, and the data goes into a
chunk in memory. The file then keeps chunks in memory for a 10s backoff
before it tries its swap file again. The sealed chunk uploads through the
swap read-back of #13198: if its earlier bytes cannot be read back either,
the flush fails, while the data written again into memory still uploads.

Memory stays bounded, as the sequential path bounds it: past 8 writable
chunks in the file, or past the shared memory-chunk ceiling, the file seals
a chunk before it creates another. Sealing waits for an upload slot, so a
writer that outpaces its uploads slows down instead of filling memory.

The #12655 tests made a write fail through an unusable swap directory. They
now make the dirty pages refuse the write directly, and a new test checks
that an unusable swap directory no longer fails it. A pipeline test covers
a sealed chunk whose swap file can no longer be read.

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

* mount: move a refused swap chunk into memory instead of sealing it

When the swap file refused a write, the first commit sealed the swap chunk
with what it held and wrote the data again into a new chunk in memory at
the same index. Two chunks at one index fail in two ways:

- A disk that takes part of an overwrite, as a full copy-on-write disk can,
  leaves the swap chunk with the new first half and the old second half.
  Its upload joins the two under the overwrite's timestamp, and the memory
  chunk uploads the new bytes under the same timestamp. Equal timestamps
  resolve to the chunk the entry lists last, so when the swap upload
  finished last the old bytes came back.
- Sealing the memory chunk while the swap chunk was still uploading
  replaced the swap chunk in the sealed slot. Until its upload finished,
  reads of the bytes only it held found nothing.

Now the swap chunk's ranges are read back into the new memory chunk, each
under its own timestamp, before the write goes in. The swap chunk then gives
back its slot without an upload, so the index keeps one chunk. When the swap
file cannot be read back either, or memory holds the shared ceiling of
chunks, the write stores only what the swap file took and reports a short
write, as master does.

Memory now stays under the shared ceiling of memory chunks. Before, a file
with no chunk of its own to seal allocated a new chunk past the ceiling
anyway, so memory grew with the number of open files writing sparse
chunks. Now that write fails. A file that has a chunk seals it to make room
for the new one, as before. The per-file bound is also checked again after
each seal, since a seal releases the lock.

refusingDirtyPages moves to a test file built on every platform, because
the copy range test also uses it on FreeBSD.

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

* mount: seal a memory chunk at the shared ceiling and recheck both bounds

At the shared ceiling, a file made room for a new chunk in memory by
sealing any one of its writable chunks. A swap chunk left by a refused
write frees no memory when it uploads, so memory went past the ceiling by
one chunk for each file in that state. At the ceiling a file now seals
one of its memory chunks, and if it has none the write fails.

Sealing releases the lock, and other writers may create chunks meanwhile.
The per-file bound was checked again after a seal made for it, but not
after a seal made for the shared ceiling. One loop now checks both bounds
again after every seal.

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

* mount: drop an empty swap chunk the swap file refused at the shared ceiling

At the shared ceiling, a swap chunk created for a write that the swap file
then refuses cannot move into memory. It was left in place, holding
nothing. Such chunks count against the file's bound, but nothing can seal
an empty chunk, so after enough refused writes a later write found nothing
to seal and created a chunk past the bound anyway. The empty chunk is now
dropped, giving back its slot and its write budget. A write that still
finds nothing to seal at the bound fails instead of going past it.

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

* mount: seal a memory chunk of the file before moving a refused swap chunk at the ceiling

At the shared memory ceiling a new chunk seals one of the file's memory
chunks and carries on, but a swap chunk whose write the swap file refused
failed the write instead. That is the first write after every backoff on
a full cache disk, and every write into an existing swap chunk.

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

* mount: keep the per-file bound when a refused swap chunk moves into memory

A file may hold more swap chunks than swapRefusedWritableChunks. When the
swap file refuses a write into a chunk created past that count, moving it
into memory left the file over the bound with every chunk in memory.
Seal another chunk of the file first, as a new chunk does.

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

* mount: write again when a refused swap chunk is sealed during a seal

Moving a refused swap chunk into memory may first seal another chunk,
which releases the lock. If another writer or the flusher sealed the
swap chunk meanwhile, the write failed although a new chunk could take
it. Write into the chunk now at the index instead.

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-12-01 16:01:52 -08:00
Chris LuandClaude Opus 5.5 44b016b991 helm: run the S3 gateway's message queue broker with grpc.msg_broker TLS (#13240)
* helm: pass the S3 gateway's message queue broker port

Every S3 gateway now runs a message queue broker on 17777. s3.mqBrokerPort and filer.s3.mqBrokerPort set the port for the standalone gateway and the filer's, and allInOne.s3.mqBrokerPort falls back to s3.mqBrokerPort when null. A port of 0 renders the off flag, since leaving the flag out would let weed start the broker on its default. The all-in-one inherits through a helper that tells null from 0, which default cannot.

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

* helm: admit the message queue broker port in the NetworkPolicy

Clients and other brokers learn a broker's address from the master and dial the pod directly, so a Service does not help them. Under a default-deny namespace the policy has to admit the port on the s3, filer and all-in-one pods that run a broker, or publishing and inter-broker replication stall.

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

* helm: list the message queue broker port on the S3 pods and Services

The s3, filer and all-in-one pods declare a swfs-mq-broker containerPort when they run a broker, and their Services carry it the way they carry the Iceberg and Lance ports. Brokers are reached by pod IP, so this is for visibility and for anything that addresses the port by name.

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

* helm: document the S3 gateway's message queue broker port

Describe the three port values, that 0 turns the broker off, and that clients reach brokers by pod IP, so under the NetworkPolicy anything outside the release needs its own ingress rule. The chart version is left alone; it moves with the release commits.

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

* helm: leave the broker port flag out when it is weed's default

17777 is already the binary's default and the broker is on by default, so rendering -mq.broker.port=17777 only breaks a release pinned to an image that predates the broker flags. The port flag now appears only for a non-default port and the off flag only for 0; the containerPort, Service port and NetworkPolicy entry still follow the configured port.

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

* helm: give the gateway brokers mTLS through grpc.msg_broker

weed starts the broker beside an S3 gateway on its own only when grpc.msg_broker has a cert and key. With enableSecurity the chart now writes that section with the internal client certificate grpc.s3 already uses, so the brokers serve and dial each other with mutual TLS against the grpc.ca the chart sets, and every pod running a gateway already mounts both.

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

* helm: choose the gateway broker with mqBroker auto, true or false

weed now starts the broker beside an S3 gateway unflagged only when grpc.msg_broker TLS is configured. s3.mqBroker, filer.s3.mqBroker and allInOne.s3.mqBroker (null inherits s3's) pick it: auto passes no flag and so runs it under enableSecurity, true passes -mq.broker=true (-s3.mq.broker=true on the filer) and runs it without TLS when security is off, false passes the off flag. One helper decides the flags and whether the broker runs for all three, and the containerPort, Service ports and NetworkPolicy entry now appear only when it does.

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

* helm: document mqBroker and the broker's TLS default

The gateway broker no longer runs everywhere: describe auto, true and false, that auto means enableSecurity and its mTLS, that true without security serves any client that reaches the port, and that the ports only appear when the broker runs.

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

* helm: test the gateway broker's flags, ports and TLS section

Render s3, filer.s3 and allInOne across auto with and without security, true, false, port 0 and a custom port, plus allInOne.s3 inheriting and overriding the s3 values. Each case checks the broker and port flags together with the containerPort, Service port and NetworkPolicy entry, so a broker that runs with its port blocked fails. Also check that [grpc.msg_broker] is written only with enableSecurity, and that an unknown mqBroker value fails the render.

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

* helm: keep the broker port off the Services

Brokers register with the master under the pod address, and other brokers and publishers find them there and dial the pod, never a Service. The swfs-mq-broker Service port only made a LoadBalancer or NodePort s3, filer or all-in-one Service publish the broker outside the cluster, in plaintext with mqBroker true and no security. Drop it; the containerPort and NetworkPolicy entry stay, and the test now fails if any Service carries the broker port.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:49:06 -08:00
Chris LuandClaude Opus 5.5 3ea924d39f filer: take every log fence from the event stamp sequence (#13239)
* filer: take the log fence without registering an in-flight stamp

LogFenceTsNs stamped and released at once, so each fence briefly sat in
the in-flight registry, where a concurrent claim could be capped below it,
and took the registry mutex twice. Draw the fence from the same sequence
under one lock acquisition without registering it. Lookups are about to
take one per read.

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

* filer: fence CreateEntry and UpdateEntry from the event stamp sequence

Both stamped their pre-write fence from the raw wall clock, so after a
backwards clock step the fence could sit below events the acknowledged
state already reflects, including the previous write's event on the same
key. A mount that versions a no-op ack by that fence would then accept an
older event over it. Take the fence from the same sequence the events use,
so it lands above every earlier event and below the write's own.

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

* filer: fence a remote-object cache commit from the event stamp sequence

CacheRemoteObjectToLocalCluster stamped its commit fence from the raw wall
clock under the path lock. After a backwards clock step that fence fell
below events the cached entry already reflects, the same as the old
CreateEntry and UpdateEntry fences. Take it from the event stamp sequence.

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

* filer: fence lookups from the event stamp sequence

fencedFindEntry, behind LookupDirectoryEntry and LookupDirectoryEntries,
stamped its read fence from the raw wall clock under the shared path lock.
After a backwards clock step the fence fell below events the returned
entry already reflects, so a client versioning the entry by it could take
an older event as newer. Draw it from the event stamp sequence instead.

The fence registers nothing in flight, so it never caps flush or delivery
claims; it costs one short critical section on the stamp registry's mutex
per lookup.

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

* filer: keep the stamp sequence above renumbered log positions

The meta log buffer renumbers an event appended out of stamp order past
the last position it holds, and that position is what subscribers see.
Concurrent writers append in whatever order their notify work finishes,
and with the wall clock behind the sequence every renumbered position
lands past the last stamp, so a later fence could sit below an event the
fenced state already reflects. Feed each delivered position back into the
sequence stamps and fences draw from.

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

* filer: draw a lookup's fence after the read

FindEntry can log an event of its own on the path it reads: importing a
remote object under a mount creates the entry, and an expired entry is
deleted. Both stamp above a fence drawn before the read, while the
returned state reflects them. Draw the fence after the read with the
shared path lock still held; a locked writer on the path cannot land in
between.

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

* filer: draw the remote cache commit's fence after its re-read

The re-read can import the object from the remote and log that event; an
entry changed during the download is returned with this fence, which has to
cover the import.

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

* filer: take the exclusive path lock for a lookup that writes

Fenced lookups share the path lock, and FindEntry can write under it: it
deletes an expired S3 object and imports an object from a remote mount,
logging an event either way. A lookup that read the old state just before
could then draw its fence above that event and return the old state, so a
client skipped the event as already reflected.

A fenced lookup now reads with FindEntry reporting such a write instead
of making it, and redoes the read under the exclusive path lock when it
does. The shared lock is released first, so nothing holding it waits on
the exclusive one.

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

* filer: escalate a fenced lookup only when the remote has the object

Refusing the lazy fetch before the remote stat sent every fenced lookup that
missed under a remote mount to the exclusive lock, so concurrent lookups of
one missing key ran their stats one after another instead of sharing one.
A lookup that may not write now stats in a flight of its own and asks for
the exclusive lock only when there is an object to import.

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

* filer: require the live object from the first lookup in the expiry race test

The fence check was skipped when the first lookup errored or found
nothing, so a run that took either path passed without checking
anything. The store hands that lookup its copy before the hook expires
the object, so it always returns the live object; require that, then
compare its fence against the delete.

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

* filer: release the shared remote stat only after every lookup joined it

The test let the stat sleep and assumed all eight lookups joined within
that window, so a lookup scheduled late could start a second, correct flight
and fail the count. The stat now waits on a gate the test opens once the
other seven lookups wait on the in-flight call.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:37:35 -08:00
Chris LuandClaude Opus 5.5 185cefc652 filer: keep the server digest tests passing under fips140=only (#13243)
GODEBUG=fips140=only refuses MD5, and the filer then digests with SHA-256
cut to MD5's size. Tests that compared stored or reported digests against
crypto/md5 or hard-coded MD5 hex panicked or failed there; they now
compute the expected digest with util.Md5, which follows the process mode.
Tests that exercise a client's Content-Md5, which only exists with MD5,
are skipped under fips140=only as the digest test already is.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:36:21 -08:00
0d3f81b771 volume(rs): refuse short JWT keys and skip Content-MD5 under fips.mode strict (#13206)
* volume(rs): refuse short JWT keys and skip Content-MD5 under fips.mode strict

Under fips.mode = strict the Rust volume server now does what the Go
volume server does under GODEBUG=fips140=only:

- At startup it exits when a JWT key in security.toml (any of the eleven
  jwt.signing* and jwt.filer_signing* settings Go checks) is shorter than
  the 14 characters FIPS 140 needs for HMAC keys, naming each one. Outside
  strict mode it warns about each such key but the previous ones.
- On SIGHUP, short current keys keep the keys in effect, and a short
  previous key is dropped, as in Go's Guard.UpdateSigningKeys.
- An upload's Content-MD5 is kept as the client sent it, unchecked, since
  strict mode computes no MD5.

The key rule and its messages live in seaweed-common's jwt_keys, so the
worker can use the same one.

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

* ci: run the fips140only cells in fips.mode strict, check strict refusals

The fips140only cells of the S3 digest matrix set WEED_FIPS_MODE=strict
beside GODEBUG=fips140=only, so the Rust volume server runs in the same
mode as the Go processes. A new job, test/s3/digest_matrix/negative_config.sh,
checks that master, filer and both volume servers refuse a 10-byte JWT key
at startup, that both volume servers keep a mismatched Content-MD5
unchecked, and that S3 answers a request signed with an 8-character secret
with an error.

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

* test: check the strict-mode Content-MD5 rule against both volume servers

TestWriteMD5MismatchKeptUncheckedUnderStrictFIPS starts the volume cluster
under GODEBUG=fips140=only and WEED_FIPS_MODE=strict and checks that an
upload with a mismatched Content-MD5 is stored with the client's value. It
sits in test/volume_server/http, so it runs against the Go volume server and,
with VOLUME_SERVER_IMPL=rust, against the Rust one. The same check leaves
negative_config.sh, which keeps the startup refusals.

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

* volume(rs): say which keys the strict-mode checks cover and what they do

The doc comments of the startup check, the reload rule and the jwt_keys
helpers now say which keys they check and what happens in each mode.

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

* volume(rs): an empty WEED_ variable leaves the security.toml value in place

env_string returned an empty variable as a value, so WEED_JWT_SIGNING_KEY=
replaced the key from security.toml with an empty one: the volume server
then checked no JWTs, and under fips.mode strict a short file key was not
refused, while Go's volume server exits with the same files. Go's viper
ignores empty variables; env_string now does the same for every WEED_
override.

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

* volume(rs): read security.toml with the TOML parser

The line reader missed quoted key names, multiline strings, dotted keys,
inline tables and spaced or quoted table headers, all of which Go's viper
reads, so a short JWT key written that way escaped the strict-mode check
and was not used at all. Settings are now looked up in the parsed table,
case-insensitively as viper does. A file that is not valid TOML is still
read line by line, as before.

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

* volume(rs): prefer the longest literal security.toml key, as viper does

Viper looks a dotted setting up longest name first, so a quoted
"jwt.filer_signing.key" key, at the top or under [jwt], wins over the
nested [jwt.filer_signing] key. The volume server read only the nested
one, so a short literal key passed the strict-mode check here while the
Go servers refused it.

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

* volume(rs): resolve security.toml key case collisions as viper does

Viper lowercases every key of a config file, and when two spellings
collide (key and KEY, or [jwt] and [JWT]) the one that is not lowercase
wins. The volume server matched names case-insensitively but took the
exact spelling first, so a short KEY next to a compliant key passed the
strict-mode check here while the Go servers refused it. The parsed table
is now lowercased the same way before any lookup.

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

* volume(rs): read an array or table security.toml setting as unset

Viper's GetString reads an array or a table as "", so the Go servers
skip a jwt key written as key = ["x"]. The volume server read its TOML
text instead, used it as the key and refused strict-mode startup over
it. fips.mode is still read as text: Go refuses a mode that is not a
string, and so does this server.

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

* volume(rs): keep each lenient security.toml line under its full name

A security.toml that is not valid TOML is read line by line, and those
lines went into nested tables, so a later scalar such as signing = "x"
under [jwt] replaced the [jwt.signing] table and erased its key. The
line reader ignored such lines before, and a SIGHUP reload of that file
would have installed an empty write key. Each line now goes in under its
full dotted name, which the longest-name lookup finds first.

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

* volume(rs): take the FIPS mode from the read that gives the JWT keys

Startup read security.toml once for the JWT keys and again for
fips.mode, so a file replaced between the two reads could pair the keys
of one version with the mode of the other and refuse to start over keys
that version never ran in strict mode with. The mode now comes from the
same parse as the keys; a file that exists but was not read is still an
error.

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

* volume(rs): read a float security.toml setting as Go's GetString does

GetString formats a float with the shortest digits and no exponent, so
key = 1234567890123.0 is a 13-byte key to the Go servers. The volume
server kept the TOML spelling with its .0 and measured 15 bytes, which
passed the strict-mode check the Go servers refuse.

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

* volume(rs): skip array-of-tables sections in a lenient security.toml

A file that is not valid TOML is read line by line, and lines under a
[[jwt.signing]] header went in under the same names as [jwt.signing],
so an empty key there replaced the real one, and a SIGHUP reload would
install it. The line reader now skips such sections up to the next
ordinary header, as the earlier reader did.

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-12-01 15:33:31 -08:00
Chris LuandClaude Opus 5.5 04bbf1ae0f filer: keep the default broker off the debug port (#13242)
weed filer -s3 checked the broker port against the filer, metrics,
read-only, WebDAV, IAM and SFTP ports but not -debug.port, which the
debug server binds before the broker starts. weed server already
includes it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:33:00 -08:00
Chris LuandClaude Opus 5.5 52afabbf1b mq: avoid a deadlock when retiring a partition with a full flush queue (#13225)
* mq: let partition retirement drain a full flush queue outside broker locks

* log_buffer: queue the final flush from ShutdownLogBuffer itself

Every ShutdownLogBuffer caller already waits afterwards with WaitForShutdown
or IsAllFlushed, so queueing the final flush in the background changes no
caller's outcome and lets every caller holding a lock a flush callback needs
avoid the full-queue deadlock, without a second shutdown entry point.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:32:00 -08:00
Chris LuandClaude Opus 5.5 45458336e1 s3: run a message queue broker beside every S3 gateway (#13235)
* mq broker: let an embedding command own the broker's start failure and shutdown

startQueueServer now returns an error when the broker cannot start instead
of exiting, binds its port before creating the broker so one that cannot
serve never registers with the master, and stops when an optional
shutdownCtx is cancelled. Profiling setup moves to weed mq.broker, since an
embedded broker read the standalone command's profile flags. weed mq.broker
and weed server -mq.broker still exit on a start failure.

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

* s3: run a message queue broker beside the gateway by default

weed s3 now starts a broker on -mq.broker.port (17777) once it has reached
its filer, using the masters and filer group the filer reports. The broker
is its own gRPC server: it binds the gateway's -ip.bind, advertises the
address the gateway registers with the master, and joins the cluster like
any other broker. It stops with the gateway. A broker that cannot start,
say because the port is taken, is logged and the gateway keeps serving.
-mq.broker=false turns it off.

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

* server: start the message queue broker with the S3 gateway

weed server -s3 now runs a broker beside its gateway, started by the
gateway once it reaches the filer. -mq.broker=false leaves it out. An
explicit -mq.broker or -mq.agent still starts the broker on its own, and
then the gateway does not start a second one. Only that explicit broker
exits the server when it cannot start; the one that comes with -s3 is
logged, so a host already running a broker on the port keeps its gateway.

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

* mini: run the message queue broker beside the S3 gateway

weed mini now starts a broker with its S3 gateway on -mq.broker.port
(17777, below the Linux ephemeral range), binding and advertising mini's
-ip.bind and -ip like the other services. The port joins mini's port
layout, so a taken port moves to the next free one unless it was given
explicitly. The broker stops with the gateway, before the filer it
flushes to. -mq.broker=false or -s3=false leaves it out.

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

* filer: start the message queue broker with the S3 gateway

weed filer -s3 now runs a broker beside its gateway on -s3.mq.broker.port
(17777), the same way weed server -s3 does: it binds and advertises where
the gateway does, takes the filer's -dataCenter and -rack, stops with the
gateway, and a broker that cannot start is logged while the gateway keeps
serving. -s3.mq.broker=false leaves it out.

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

* mini: list the message queue broker when it is running

The S3 gateway now binds its broker's port before it starts serving, as it
does for the Iceberg and Lance listeners, and records whether the bind
worked. Once mini sees the S3 port answer, the result is final: the
progress board shows the broker ready or failed, and the welcome banner
lists its address only when it bound. With -mq.broker=false or -s3=false
neither shows it.

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

* s3: keep the default broker off the gateway's own ports

The broker binds before the gateway binds its ports, so a gateway started
with -port=17777, -port.grpc=17777 or -port=7777 (gRPC port 17777) lost
its port to the default broker and exited. weed s3, weed server -s3 and
weed filer -s3 now compare the broker port with the gateway's HTTP,
HTTPS, gRPC, Iceberg, Lance and metrics ports first. A default broker
port that clashes skips the broker with a warning; a broker port given
on the command line that clashes is an error.

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

* mini: reserve explicitly set gRPC ports before placing other ports

Mini only kept derived gRPC ports free while it placed the other
services, so the broker's default port could take an explicit
-s3.port.grpc=17777 and push the S3 gRPC server to another port. An
explicit gRPC port is now reserved too: the default broker moves off it,
and an explicit broker port on it is rejected.

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

* server: keep the default broker off the ports of the servers it starts

With -volume.port=7777 the volume gRPC port is 17777, the default broker
port. The volume server binds its gRPC port only after a master answers,
so the broker could take it first and the whole process exited.

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

* mini: keep an explicit gRPC reservation when a derived one moves

When the filer's HTTP port was taken and moved, dropping its old derived
gRPC port also dropped an explicit -s3.port.grpc on the same port, so an
explicit -mq.broker.port could share it.

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

* server: bind the broker beside S3 where the gateway binds

With -ip.bind=0.0.0.0 -s3.ip.bind=127.0.0.1 the broker that comes with
the gateway listened on every interface. It now takes the gateway's bind
and advertised address, as under weed s3 and weed filer -s3.

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

* server: keep the default broker off the volume public port

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

* mq broker: report a bad TLS config instead of exiting

The embedded broker loaded grpc.msg_broker TLS through LoadClientTLS and
LoadServerTLS, which exit on a bad config, so a cert without a key or
without grpc.ca took the whole S3 gateway down. The broker now loads TLS
before binding through the error-returning loaders, exported from the
security package as TryLoadClientTLS and TryLoadServerTLS, and returns
the error like any other start failure: the gateway logs it and keeps
serving, while weed mq.broker and weed server -mq.broker still exit.

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

* s3: start the gateway's broker by default only with broker TLS

Without grpc.msg_broker TLS the broker accepts any peer, so the broker
beside weed s3, weed server -s3 and weed filer -s3 now starts on its own
only when grpc.msg_broker has a cert and key in security.toml. Otherwise
it stays off and the gateway logs one line saying so and that
-mq.broker=true (-s3.mq.broker=true for the filer) runs it without TLS.
An explicit true starts it either way and an explicit false keeps it
off. weed mini, a single-process dev setup, keeps its broker on.

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

* filer: keep the default broker off the ports of the servers it starts

weed filer -s3 checked the broker port only against the gateway's ports,
so with -webdav -webdav.port=17777 the broker could bind 17777 first and
WebDAV then took the whole filer down. The check now also covers the
filer's own HTTP, gRPC and read-only ports, its metrics port, and the
WebDAV, IAM and SFTP ports when those run, as weed server does. A
default broker port that clashes skips the broker with a warning; a
clashing -s3.mq.broker.port is an error before the servers start.

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

* server: keep the default broker off the filer read-only and debug ports

The port check beside -s3 left out -filer.port.public and, with -debug,
-debug.port, so a broker on 17777 could still take a port the filer or
the debug server binds. Both are now in the list. WebDAV, SFTP and IAM
were already covered when enabled.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:53:36 -08:00
Chris LuandClaude Opus 5.5 6b2e22950a s3: bucket notification configuration API and target registry (#13236)
* s3: add the bucket notification target registry

Notification destinations are defined by the operator in
/etc/s3/notification/targets.json and referred to by name from bucket
configurations, so a bucket owner cannot make the server connect anywhere
new. The registry parses and validates that file: unique names that fit in
an ARN segment and an MQ topic name, known types (topic and webhook now,
kafka, aws_sqs, google_pub_sub and pubsub accepted for later), the fields
each type needs, and no unknown keys. A target serves only the buckets its
allowed_buckets globs match, and none when the list is empty. Parse errors
never carry credential values.

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

* s3api: hot-reload the notification target registry

Every gateway reads /etc/s3/notification/targets.json at startup and
reloads it from the /etc metadata subscription it already runs for the IAM
and circuit breaker files. A write reloads it, a delete or rename away
empties it, and a file that does not parse leaves the previous registry in
place so a bad edit does not cut every bucket off its destinations.

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

* s3: parse and validate bucket notification configurations

The full PutBucketNotificationConfiguration document is parsed: topic,
queue and cloud function configurations with their Id, destination ARN,
events and key filter. Event names are checked against the AWS list,
wildcards and names for things that never happen here included, plus the
multipart and retention events this server emits. A filter takes at most
one prefix and one suffix rule, a document at most 100 configurations, and
overlapping rules are allowed. EventBridge stays NotImplemented.

A destination resolves by the last segment of its ARN to a target, which
must exist, be enabled and allow the bucket; the error does not say which
of those failed. A rule without an Id gets one derived from its content, so
every gateway reports the same configurationId for it.

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

* s3: match an event against a bucket's notification rules

Configuration.Match takes an event name such as s3:ObjectCreated:Put and
an object key and returns each rule that covers them, with its
configurationId and target, in configuration order. Category wildcards
cover every event in the category, prefix and suffix are case-sensitive and
checked independently, and an event that several rules cover matches each
of them, as AWS delivers one record per rule. Publishing calls this; it is
a pure function of the stored configuration.

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

* s3api: store bucket notification configurations

PutBucketNotificationConfiguration used to accept only an empty document
and answer NotImplemented for any destination. It now parses the full
document, checks every destination against the target registry for this
bucket, and stores the XML exactly as sent in one Extended key on the
bucket entry through updateBucketConfig, which patches that key alone on
the bucket's owner filer. An empty document removes the key. GET returns
the stored bytes unchanged, so tools comparing ARNs see no diff, and the
bucket config cache carries the parsed rules for publishing to match.

x-amz-skip-destination-validation is parsed and must be true or false. It
only skips the test event, which publishing will send; the registry check
always runs.

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

* s3notification: reject content after the configuration's root element

The stored document is served back unchanged by GET, so anything after the
root other than whitespace, comments or processing instructions is refused.

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

* s3notification: reject unknown elements inside rules and filters

A misspelled Filter, S3Key, FilterRule or Value was dropped by decoding and
left an unfiltered rule; it is now MalformedXML like an unknown root child.

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

* s3notification: URL-decode prefix and suffix filter values

AWS has special characters in filter values percent-encoded and a space
written as +, so reports+2026/ selects reports 2026/a. A value that is not
valid encoding is still matched as written.

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

* s3api: refuse a notification targets file stored in chunks

Only inline content is read, so a targets.json kept in chunks (written by a
mount, for one) read as an empty registry and dropped every target. It is
now refused with a warning and the loaded registry stays.

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

* s3notification: refuse overlapping rules as AWS does

AWS answers InvalidArgument ("Configuration is ambiguously defined") when two
rules share an event type and both their prefixes and suffixes overlap, so an
event for a key matches at most one rule. Such configurations were accepted
and matched every rule.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:45:21 -08:00
Chris LuandClaude Opus 5.5 6a6208e42f mq: a leader-only partition gains a follower, and cold partitions are purged (#13232)
* mq balancer: start a new generation when a partition's follower changes

EnsureAssignmentsToActiveBrokers gave a leader-only partition a follower
once a second broker was live, and replaced a lost follower, but kept the
epoch. A leader starts replicating only when it takes the fence, so a
loaded leader never saw the new follower: its copy at the same epoch was
never retired, and the partition stayed unreplicated, acking from memory,
until something reloaded it. Any change of the pair now bumps the epoch,
so the leader retires its copy after the last flush and reloads under the
new generation with a replicator to the new follower. Re-spelling the same
broker's address still keeps the epoch, so an unchanged pair is not
churned.

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

* mq broker: hand a repaired assignment's new generation to its leader

When the balancer repaired a topic's assignments it only saved
topic.conf. A leader learned of a new generation only when a new publish
or subscribe stream asked for the partition after its own cached
topic.conf expired, so a loaded partition kept serving the old
generation, without the follower it had just been given, for as long as
its clients stayed connected. Once the repair is saved, the balancer now
sends every assignment whose epoch moved to its leader, which retires
the old copy after its last flush and reloads under the new fence,
replicating to the new follower. The handoff runs outside topicConfLock,
since the leader may wait for that flush.

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

* mq balancer: repair every topic's assignments once a broker joins

The balancer repaired a topic's assignments only when a lookup missed
its cached topic.conf. A partition placed while its leader was the only
broker kept no follower after a second broker joined for as long as its
clients stayed connected and never looked it up again. The balancer now
counts brokers joining it and, once settled, repairs every stored topic
after a join, handing any new generation to its leader. A sweep that
fails is retried on the next tick; one that finds nothing to change
saves nothing, so a reconnect does not churn partitions. A repair that
saves topic.conf also drops the balancer's cached copy, which lookups
would otherwise keep answering with the old pair.

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

* mq broker: purge a partition past retention when its leader loads it

Files past a topic's retention were deleted only by the periodic purge,
which visits partitions that are loaded when it runs. A partition loaded
for a short read or write and unloaded once idle could miss every pass,
keeping its expired files. A leader now purges a partition as soon as it
has loaded it, under the fence it has just taken and after seeding its
offsets, so every load deletes what has expired. The purge runs once the
partition is registered, outside the broker's access lock.

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

* mq balancer: load partitions whose files are past retention

A partition that nothing publishes to or reads from is never loaded, so
neither the periodic purge nor a purge on load ever reached it, and a
cold topic kept its expired files indefinitely. Every purge interval the
balancer now lists each topic with retention, works out per partition
what a purge would delete, and hands only the partitions with something
to delete to their leaders. The leader's load purges them under the
fence it takes, so deletes stay fenced. A partition with nothing to
delete, such as one holding only its newest file, is not loaded, so
cold partitions are not churned.

The planning half of purgeExpiredLogFiles moves into expiredLogFiles,
which the purge and the balancer share.

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

* mq balancer: resend a new generation until its leader takes it

After a repair saved a new generation, the balancer told the leader once
and only logged a failure. The repair loop still counted the join as
done, and later sweeps found nothing to change, so a leader whose
publish stream kept its old partition went on acking without the
follower it had been given. Saved generations are now kept as pending,
one per partition with a newer one replacing an older, and the repair
loop hands each due one to its leader, backing off after each refusal,
until the leader takes it or topic.conf has moved past it. A join counts
as repaired only once nothing is pending. Sending runs in the repair
loop, off topicConfLock, which a save now wakes.

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

* mq balancer: hand pending generations to leaders in parallel under one deadline

The repair loop handed pending generations over one at a time, each
with its own 30 second timeout, so a broker that stopped answering held
the loop for that long per partition it led: with a hundred of them,
healthy leaders and later joins waited most of an hour. A pass now reads
each topic.conf once, groups the generations still current by leader
and topic into one request each, and sends up to eight leaders at once
under a single deadline for the whole pass. A leader that does not
answer delays only its own generations, which keep their backoff, and
the pass returns once the deadline passes.

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

* mq balancer: key a pending generation by the partition's full identity

Pending generations were keyed by topic and range alone. A topic
repartitioned away from a range and back gets a new partition for that
range, with a new creation time and epochs starting over, so a pending
generation of the old partition at a higher epoch made the new one look
older and it was never queued. The key now includes the ring size and
creation time, so epochs are compared only within one partition; the old
entry is dropped as superseded when it next comes due.

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

* mq balancer: hand over generations a previous balancer left undelivered

Pending generations live only in the balancer's memory. A balancer that
saved a new generation and stopped before its leader took it lost it:
the next balancer's sweep found topic.conf already repaired, recorded
the join as done, and a leader whose clients kept its old copy served
that generation without its new follower indefinitely. Once settled
under a new lease, the balancer now queues the current generation of
every partition a leader reports loaded and hands them over through the
same batched delivery, so joins are not done until those are taken too.
A leader already on that generation keeps its copy, as an assignment at
the epoch it holds is a no-op, and an unloaded partition is skipped
since it reads topic.conf when it loads.

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

* filer_client: track a filer's backoff atomically

Every call through one FilerClientAccessor records the filer's health,
and those calls run concurrently, but the backoff deadline was a plain
time.Time read and written without synchronization. The broker now reads
topic.conf from background purges and repairs while serving requests
through the same accessor, which the race detector caught. The deadline
is now an atomic Unix-nanosecond value, and the failure time it was
stored beside, which nothing read, is dropped.

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

* mq balancer: keep generations pending when the pass ends before sending them

A batch still waiting for a sender when the pass deadline passed took
the cancellation branch with its error still nil, so its generations
were dropped as delivered although nothing was sent, and their leaders
kept serving the old generation. Such a batch now fails with the pass's
deadline and keeps its backoff, like a batch whose send timed out.

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

* mq balancer: give each leader one sender, not each of its topics

The limit on concurrent sends applied to per-topic batches, so a stalled
leader with as many due topics as there are senders took every slot and
a healthy leader waited out the pass deadline. A pass now groups due
generations by leader; each leader takes one sender and sends its topics
in turn, so a stalled leader holds only its own slot, and its topics not
reached before the deadline stay pending.

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

* filer_client: keep backing off a filer that has failed many times

The backoff doubled with a shift of the failure count, which wraps once
a filer has failed 64 times in a row, so its backoff dropped to nothing
and it was retried on every call. The doubling now stops at 16 seconds
and the backoff stays at 30 seconds after that.

* mq balancer: requeue each broker's held generations once its stats arrive

A new balancer requeued the generations of loaded partitions once per
lease, from whatever stats it had at that moment. A leader that had
connected but not yet sent its first stats looked as if it held
nothing, and since the scan never ran again under that lease, a
generation an earlier balancer saved but never handed over stayed
undelivered. The balancer now records which brokers have reported and,
on each pass, scans the brokers whose first stats arrived since the
last scan under the current lease, queuing their held partitions'
current generations for the same batched delivery.

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

* mq balancer: scan each broker connection, judged by the stats it reported

The handoff scan took the reported brokers' addresses, then looked each
one's stats up again while matching partitions, and marked the address
scanned. A broker that disconnected in between was looked up as holding
nothing yet still marked scanned, so when it reconnected under the same
lease it was never scanned again and a generation it never took stayed
undelivered. The scan now judges each broker by the stats it was
listed with and records connections, not addresses, as scanned; a
reconnect brings new stats and is scanned again.

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

* mq balancer: register each broker connection separately

AddBroker reused the stats already registered under a broker's address,
and a stream's cleanup removed whatever was registered under it. A
broker that reconnected before its old stream ended shared that stream's
stats, and the old stream's cleanup then dropped it from the live set
while the new stream kept reporting, so the balancer treated a live
broker as gone, and the handoff scan, which already counted that stats
object as scanned, skipped the reconnect. Each connection now registers
fresh stats, and its cleanup removes the broker only while those are
still the registered ones.

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

* mq broker: record an assignment only on a connected broker's stats

After handing a partition to its leader, the balancer recorded the
assignment on the leader's stats and, when the leader had none, created
and registered stats for it. A leader not connected to the balancer, as
one still reconnecting or one that only answered the assignment, was
thereby added to the live set without a connection whose cleanup would
ever remove it, and assignments could then pick a broker the balancer
could not see. The assignment is now recorded only when the leader's
connection has registered it.

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

* mq balancer: sweep topics from a listing that reports its failures

The repair sweep, the handoff scan and the retention scan took their
topics from ListTopics, which serves what it can: a failed namespace
listing, a failed topic listing or a failed topic.conf lookup is only
logged. A sweep could therefore see some topics, or none, and still
succeed, recording a join as repaired with topics never looked at.
ListTopics' filer scan is now listStoredTopics, which lists all it can
and reports every failure. The repair sweep and the handoff scan fail
on it, so the join stays pending until a sweep lists every topic, while
an empty listing that succeeded is still complete. The retention scan
purges what was listed and logs the rest. ListTopics keeps serving
partial results to its gRPC callers and only logs the failure.

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

* mq broker: list every namespace and topic, not the first thousand

The topic listing asked the filer for at most 1000 namespaces and at
most 1000 topics per namespace and never asked again, so anything past
the first thousand was missing from ListTopics, never repaired after a
broker joined, never handed over by a new balancer, and never purged
past retention. Both listings now ask for everything, which the filer
pages through itself, as the partition offset scan already does.

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

* mq balancer: forget the scan record of a broker connection that ended

The handoff scan remembered every broker connection it had scanned
until the balancer lease changed. Each reconnect is a new connection,
so a long-running balancer kept one record, holding that connection's
stats, for every reconnect of every broker. Each pass now drops the
records of connections no longer reported; a broker that reconnects
brings new stats and is scanned again either way.

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

* mq broker: give the stored-topic listing a deadline

The shared topic listing ran under the broker's long-lived context, so
a filer that accepted a listing and stopped answering held the repair
loop and the retention sweep indefinitely; ListTopics used to give its
scan two seconds. Each listing now gives up after 30 seconds and
returns the error, so the scan is retried on a later pass.

* mq balancer: give a retention hand-over a deadline

A leader that took the hand-over of a partition past retention and never
answered held the balancer's retention loop on it, so later topics and the
next tick never ran.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:35:34 -08:00
Chris LuandClaude Opus 5.5 a1f3f9aaa1 filer: return the commit stamp from ObjectTransaction (#13234)
* filer: add log_ts_ns to ObjectTransactionResponse

CreateEntry and UpdateEntry return the filer log position stamped under
the path lock; a conditional write through ObjectTransaction had no such
field. Add it as field 4 so callers can order one key's commits the same
way regardless of which RPC applied them.

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

* filer: return the commit's log position from ObjectTransaction

A committed transaction now stamps log_ts_ns under its lock_key lock after
its last mutation, the same wall-clock source CreateEntry and UpdateEntry
use. All mutations of one transaction sit between that stamp and the next
writer's, so one stamp orders the transaction against every other write
of the key. A refused or failed transaction leaves it 0, and a replayed
request returns the stamp recorded with its first outcome. A non-owner
forwards the owner's response unchanged.

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

* filer: stamp ObjectTransaction's log_ts_ns from the meta-log clock

The wall clock can step back between two transactions on one key, or sit
below stamps already bumped past it, giving a later transaction a smaller
stamp than an earlier one or than its own event. Take the response stamp
from the same monotonic allocator the events use, released at once.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:22:45 -08:00
Chris LuandClaude Opus 5.5 42a39099e0 mq broker: keep one request id across filers for a topic.conf save (#13237)
A save that applied but lost its answer was retried on the next filer under
a new request id, refused as changed by its own write, and redone from the
saved topic.conf: a balance move then found the target already leading and
failed after saving. The same id lets the owner replay the recorded outcome.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:19:51 -08:00
5213f4c1b0 worker(rs): write in the filer's digest and send a CRC32C with each upload (#13221)
* worker(rs): write ETags and chunk digests in the filer's digest

The worker's Lance store (weed-worker, and weed-vector, which links it)
wrote MD5 chunk ETags, MD5 object digests and MD5 multipart ETags whatever
the filer's digest (#12913), so a cluster on -digest=sha256 held MD5
digests for every file the worker wrote. It now reads the digest the filer
reports and writes in it, as the Go writers do: SHA-256 cut to 16 bytes
under sha256.

A filer that reports no digest leaves the worker in its own mode, sha256
under fips.mode strict and md5 otherwise, with Go's warning; under strict
mode a filer using md5 is refused, as the Go clients refuse it under
GODEBUG=fips140=only.

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

* worker(rs): send the CRC32C of each upload to the volume server

The worker uploaded chunks with no checksum header, so a volume server
could not tell a chunk damaged in transit from a good one. Each upload now
carries X-Seaweed-Content-Crc32c (#12999) over the bytes it sends, as Go's
uploader does; volume servers check it before storing the chunk, and those
that predate the header ignore it.

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

* worker(rs): read the whole upload request in the CRC32C header test

The test's server read the request once, so a request TCP split before the
checksum header failed the test although the client sent it. It now reads
up to the end of the head, fails on a connection closed before it, drains
the body by its Content-Length, and matches the header name in any case.

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

* worker(rs): digest a chunk's ETag before the volume encryption

Go's uploader records the caller's digest of the bytes it hands to the
volume encryption as the chunk ETag; the worker digested the ciphertext,
so under cipher its chunk ETags and the multipart ETags derived from them
differed from the gateway's.

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-12-01 14:17:49 -08:00
ec1032d642 filer.remote.sync: a source chunk gone for good no longer wedges the write-back (#13220)
* filer.remote.sync: a source chunk gone for good no longer wedges the write-back

An entry whose chunk the volume servers answer 404 for, even with
readDeleted=true, can never be uploaded: the bytes no longer exist in the
cluster. A volume lost with its disk leaves such entries behind (for
example a filer restored from a metadata backup onto a new volume server
while some chunks had not been written back yet). filer.remote.sync
retried the create event forever, every ~2 s, and since a failing event
holds the directory's processed watermark, no later change under the
mount was ever written back again. We hit this in production: one photo's
chunk answered 404 for hours and more than 11,000 later changes waited
behind it.

Now, once the filer confirms the entry is still the one the event
described (the existing supersession check), the upload ends with
errSourceGone when:

- every location answered 404 for sourceGoneGrace (5 min) over
  sourceGoneMinAnswers (3) attempts in a row, or
- the master cannot locate the chunk's volume at all ("failed to locate",
  the whole volume lost with its disk) for sourceGoneLookupGrace (30 min,
  the filer deletion retry's figure for "volume not found").

It logs one ERROR line naming the path, the chunk's fid and the
destination, with a per-process count, and every caller treats the event
as handled so the offset advances. A path found gone is remembered with
its fid (bounded to 10,000), so later events of the same entry are skipped
at once; any other outcome (success, superseded, another error, a failed
supersession lookup) forgets it and starts the grace again, so a volume
server that has not loaded its volume yet, or a stale location, is not
mistaken for lost data.

Only the source decides. The upload body is wrapped in a recorder that
keeps the first error the chunk reader returned, because remote clients
wrap a body read failure in their own errors (the AWS SDK's RequestError
has no Unwrap). The recorder forwards ReadAt and Seek, so s3manager keeps
reading parts in place. A 404, 5xx, timeout or any other error from the
remote itself never reaches the recorder and keeps retrying as before.

A rename of an entry that was written back now deletes the old key only
after the new one is written: when the entry's local data is gone, the old
key keeps the last remote copy (logged) instead of being deleted before an
upload that can never succeed. The gateway's rename path, which deletes
first, does not acknowledge errSourceGone and keeps failing visibly.

util/http:
- GetAuthenticated (the encrypted chunk read) reports a 404 as ErrNotFound,
  as the unencrypted read paths already do, with the same error text;
  readEncryptedUrl wraps with %w instead of %v and treats a 404 as
  retryable, like the plain read, so it tries the other locations.
- A chunk read is ErrNotFound only when no location of the pass failed
  differently (NotFoundEverywhere): a 404 from one replica while another is
  down, answers 5xx or is throttled does not mean the chunk is gone. This
  is applied once in hedgedChunkPass (both RetriedFetchChunkData paths) and
  in the manifest's retriedStreamFetchChunkData loop.

Tests:
- filer_remote_sync_gone_test.go: a plain and an encrypted chunk served 404
  by a test volume server end in errSourceGone on the third attempt and are
  counted once; a remote that answers 404 with readable chunks never does;
  the tracker's grace, answer count, reset, fid change and remembered path;
  the lookup-miss grace; ReaderAt kept by the recorder; a rename keeps the
  old key when the entry is gone and deletes it after the write otherwise.
- TestGetAuthenticatedNotFound; TestRetriedFetchChunkDataNotFoundEverywhere
  (plain direct, plain stream, encrypted; a 404 and a 503 in either order
  is not ErrNotFound).
- Mutation checks: each fails with readEncryptedUrl back on %v, with the
  write error classified instead of the body's read error, with
  NotFoundEverywhere dropped from hedgedChunkPass, with the old key deleted
  first, and with the recorder hiding ReadAt.
- go vet and go test of weed/util/http, weed/command, weed/filer and
  weed/replication/... pass; weed/util/http also with -race.

* filer.remote.sync: renames keep the old key until the new one holds the content; gone is per entry; missing volumes opt-in

- A sighting is counted per entry content (the sorted chunk file ids),
  not per failing chunk. An uploader reads the parts of a ReaderAt body in
  parallel, so the chunk that fails first changes between attempts; keyed
  on it, the grace restarted every time and a large file missing several
  chunks held the offset forever. The tracker's `seen` map is bounded, and
  the log names the first chunk "and N more" instead of every fid.
- On every rename the old key is deleted only after the new one holds the
  content: also when the event's old entry carries no stamp (an upload
  whose stamp a rename in between refused leaves an unstamped copy), and
  in the superseded branch, where the old key is what uploadCurrentEntry
  copies a remote-only entry from. uploadCurrentEntry reports when the
  current entry's data is gone, and the old key stays then. A multipart or
  system path whose old key cannot be deleted no longer skips the stamp.
- A volume the master cannot locate counts only with
  -sourceGoneVolumeMissing=<duration> (default 0: never): a volume server
  that is down or in maintenance looks the same, and an entry written off
  is not retried. It suits a deployment whose master and volume server run
  as one process.
- filer.remote.gateway's rename writes the new key first, deletes the old
  object after, and keeps it when the source data is gone.

Tests: TestRetriedWriteFileSourceGoneAcrossChunks (two lost chunks read in
turn), TestSupersededRenameUploadsCurrentEntry "uncached between the check
and the upload" and "current entry's chunks gone: the old key stays",
TestRenameOfGoneEntryKeepsTheOldKey "old entry unstamped",
TestSourceGoneGraceFor (lookup miss off by default, on with the flag);
each fails with its fix undone. The test remote's DeleteFile removes the
object, as a real remote does.

* filer.remote.sync: evidence kinds apart, a gone entry counted once, the copy owns its source's cleanup; gateway keeps the old object on a superseded rename

- Lookup misses and 404s no longer share one run of sightings
  (sightingKey = content + grace): with -sourceGoneVolumeMissing set, a few
  minutes of "failed to locate" followed by one 404 met the 404 grace with
  the misses' start and answers.
- observe reports whether this call found the entry gone; a replayed event
  of an entry already gone is skipped without another log line or count.
- A superseded rename whose current entry is remote-only leaves the old key
  to completeRemoteOnlyRename, which removes its source only while it is
  the object the stamp describes; an unconditional delete after it could
  remove a replacement.
- filer.remote.gateway: a superseded rename keeps the old object (logged)
  instead of deleting it before the superseding event has written the new
  key.

Tests: TestSourceGoneTrackerCountsOnceAndKeepsEvidenceApart,
TestSupersededRenameUploadsCurrentEntry "the old key replaced during the
copy"; each fails with its fix undone. The gateway change has no test of its
own (its rename path needs a reachable filer).

* filer.remote.sync: drop -sourceGoneVolumeMissing, a lookup miss keeps retrying

A volume the master cannot locate looks the same whether it was lost or
its server is down, so no default can write such an entry off safely, and
a flag for the one-process layout is not worth carrying. Only a 404 from
every location counts as gone; a lookup miss retries as before.

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

* filer.remote.gateway: a superseded rename settles its old object

A rename the filer has moved past kept the renamed-from object for good,
so every rename followed by a delete or a rewrite before the gateway
reached it left an orphan on the remote. Settle it the way
filer.remote.sync's uploadCurrentEntry does: copy from it when the entry
has become remote-only, and otherwise delete it, since it no longer holds
the entry's content.

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

* filer.remote.sync, filer.remote.gateway: a superseded rename copied from a later rename's source settles its own old key

When the entry became remote-only through another rename onto it, the copy
reads that rename's source and removes it, and nothing read or removed the
event's own old key any more. Delete it then, in both commands.

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

* filer.remote.gateway: reset cached remote clients after the superseded-rename test

A cached client kept the previous run's recorder, so the test failed under
-count above one.

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-12-01 14:15:37 -08:00
Chris LuandClaude Opus 5.5 3363f4a318 mq: disk and parquet reads stop when asked, resume inside earlier files, and order new stamps after stored ones (#13230)
* mq logstore: stop a disk read when the callback is done

GenLogOnDiskReadFunc ignored the isDone the per-entry callback returned, so it
kept fetching and delivering every later entry, chunk and file, and the merged
read then went on into the parquet files. The chunked offset read and the query
scanner's close path both return true and expect the read to stop. The reader
now stops at that entry, skips the remaining chunks and files, and returns done
with a position just past the entry: the next offset for an offset read, its
time for a timestamp read. The merged read returns there instead of reading
parquet.

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

* mq logstore: stop a parquet read when the callback is done

The parquet reader also ignored the callback's isDone and delivered every
remaining row of every compacted file, and the merged read cleared any done it
reported. It now stops at that row and skips the remaining files, which it
lists before reading instead of reading inside the listing. Its done now means
only that the callback asked to stop, so the merged read passes it on; the
no-op readers and a file starting at or after stopTsNs no longer report done,
which the merged read used to clear anyway.

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

* mq logstore: read parquet files named before a timestamp resume

A parquet file is named after its first source log, and that log can start
seconds before rows the file holds, so listing parquet files from the resume
second skipped a file named earlier that still held later rows. The reader now
keeps the same sparse logFileIndex the log reader uses and lists from the last
mark before which every file ends before the resume time, deciding each file
by its ts_max.

Rows are not in time order once windows flushed across a reload are compacted
together, so stopping at the first row past stopTsNs dropped later rows still
inside it. Each row is now kept or skipped on its own, and the returned
position is the latest row delivered rather than the last row looked at.

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

* query: take MIN and MAX of _ts from the files' recorded time range

MIN and MAX of _ts without column statistics were computed from file names,
which are only the start second of a file's first source log: MIN rounded down
to that second and MAX was the start of the latest file rather than its last
row. Each file's stats already carry ts_min and ts_max as MinTimestampNs and
MaxTimestampNs, so those are used when set, and names only for files that
record no range.

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

* mq broker: stamp a loaded partition's messages after the newest stored one

Within one LogBuffer timestamps only increase, but a new buffer starts LastTsNs
at 0, so a leader whose clock is behind the previous leader's stamped new
messages earlier than what was already stored, and a subscriber resuming by
timestamp from the last stored message dropped them. OffsetRange now also
records the newest ts_max of the partition's log and parquet files, and loading
a partition seeds LastTsNs with it, so the buffer bumps new messages past it.

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

* mq logstore: read parquet rows at the stop time

The log reader treats stopTsNs as inclusive, delivering an entry at it and
reading a file whose first entry is at it, but the parquet reader stopped at a
row equal to it and skipped a file starting at it, so the same bounded read
returned that message from a log file and dropped it once compacted. Both
checks are now inclusive.

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

* mq logstore: drop a debug print from the disk read

A disk read bounded by stopTsNs printed the stop time and the first entry past
it to stdout on every such read. It was a leftover debug line.

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

* mq logstore: start an offset read of parquet files at the offset

An offset read of the parquet files delivered every row from the first one on,
and the stateless fetch fills a disk chunk with a callback that stops after a
chunk's worth of entries outside it. Now that the reader honors that stop, a
fetch at 1000 from a partition stored only in parquet stopped after rows 0-999
and returned nothing. An offset read now skips files whose recorded range ends
below the offset or that record none, reads the rest in offset order, and skips
rows below the offset before they reach the callback. It returns the offset
after the last row delivered, not a timestamp position.

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

* mq logstore: read parquet files first in a merged offset read

The merged read took the live log files first and, now that it honors the
callback's done, returned without reading parquet when the callback stopped.
The stateless fetch stops after a chunk's worth of entries outside the chunk it
fills, so with offsets 0-999 only in parquet and 1000-1999 in log files, a fetch
at 0 stopped on the log files' entries and never reached parquet.

Compaction turns the oldest windows into parquet, so an offset read now takes
the parquet files first and the log files after: the lower offsets arrive
first, and since each source skips what lies below its start, a bounded caller
only stops on entries past what it wants. Compaction leaves a parquet file's
source logs in place until retention removes them, so the log files are read
from the offset after the last one parquet delivered, and each offset is
delivered once. Timestamp reads keep their order.

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

* mq logstore: serve merged offset reads from log files where they exist

A merged offset read took parquet first and the log files from the offset after
the last row parquet delivered. Compaction keeps a parquet file's source logs
until retention removes them and drops messages with no key or no data, so that
skipped those messages although their logs were still there, and delivered
compacted rows in place of the messages as written.

The log reader now lists its files before reading them, and an offset read
finds the lowest offset the listed log files record. Parquet serves only the
offsets from the requested one up to that, and the log files everything from
there, so each offset is read once and from a log file whenever one holds it.

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

* mq logstore: read schemaless parquet rows back as their published bytes

Compaction stores a schemaless message's bytes in the _value column, but the
parquet reader handed out the whole row marshaled as a RecordValue, with _key,
_ts_ns and _offset wrapped around it, so a consumer reading compacted offsets
got different bytes than it would from the log files, and the query engine
showed that wrapping as the value. A schemaless topic's rows now carry the
_value bytes as Data; schematized topics keep the marshaled row.

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

* mq logstore: fail a read that needs parquet when its reader cannot be set up

A topic whose schema cannot be laid out as parquet left the parquet
reader nil, and a merged read that reached parquet called it and
panicked. Such a read now returns the setup error; skipping the parquet
rows silently would hide stored messages.

* mq logstore: a stopped log read returns the last delivered time

A later-named log file can hold earlier messages, so the latest time a
stopped read delivered can be past one it never reached.

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

* mq logstore: compact a group's rows in offset order

Source logs list by name, which sorts out of offset order under clock
skew, so a compacted file could hold offsets 2,3,0,1. An offset read
delivers a file's rows as stored and then reports a next offset past
ones it never delivered.

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

* mq: floor a reload's stamps by the newest legacy log file name

Log files record ts_max only since this release, so after an upgrade a
reload saw no newest time and seeded the stamps at zero. A log file that
records no times is named by its first message, so its second still
bounds the newest stored time.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:14:02 -08:00
Chris LuandClaude Opus 5.5 e84c3f9ada mount, filer: a content change clears the stored content MD5 (#13238)
* mount: a content change clears the stored content MD5

Attributes.Md5 is the whole content's MD5: the S3 and WebDAV ETags and
WebDAV's oc:checksums report it. A write, a size change, a grown
fallocate, an O_TRUNC open or a copy_file_range into the file kept it, so
those reported the old content's MD5 and an ETag that did not change.

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

* filer: AppendToEntry clears the stored content MD5

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

* mount: copy_file_range clears the MD5 once it buffers bytes

A cancelled copy or a later read error returned before the clear, leaving
the bytes already buffered under the old MD5.

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

* filer: an empty AppendToEntry keeps the content MD5

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:22:56 -08:00
484e16e30c webdav: keep X-OC-Mtime and report oc:checksums (#13226)
* webdav: keep X-OC-Mtime and report oc:checksums

ownCloud and Nextcloud sync clients, and rclone's webdav backend in those
vendor modes, send a file's modification time in X-OC-Mtime and read its
hash from the oc:checksums property. Without them every upload gets the
upload time as mtime and clients can only compare sizes, so syncs re-upload
unchanged files.

- PUT stores X-OC-Mtime (Unix seconds, fractions dropped) as the entry's
  mtime, at create and at commit, and answers "X-OC-Mtime: accepted"
- a file created and written front to back stores its content MD5; any
  other write clears it, so no stale MD5 outlives a partial rewrite
- PROPFIND reports oc:checksums ("MD5:<hex>") for files whose MD5 is known;
  PROPPATCH is still refused

Checked with rclone (vendor=owncloud): sync keeps mtimes, md5sum matches
local files, including an 8-chunk file.

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

* webdav: only report an inline MD5 for whole inline content; test commits

- contentMd5 hashes inline content only when it is the whole file
  (filer.ETagOfInlineContent): content next to chunks, or shorter than the
  file size, is only part of it and must not be advertised as its checksum
- test a PUT that crosses a buffer flush end to end: the committed entry
  carries the X-OC-Mtime and the MD5 of the whole body
- test that writing into an existing file clears its stored MD5

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

* webdav: ignore a NaN X-OC-Mtime

int64 of NaN is implementation-specific (the most negative value on amd64,
the largest on riscv64), so a NaN header could store an arbitrary mtime.

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

* webdav: group the oc test imports

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

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-01 13:16:48 -08:00
Chris LuandClaude Opus 5.5 c8cd1a7d77 volume: refuse a batch delete while a replica is offline (#12311)
* volume: refuse a batch delete while a replica is offline

BatchDelete now applies the replica check the HTTP delete path already
uses: when the master lists fewer replicas than the volume's copy count,
the delete is refused with 503 instead of applied to the replicas that
remain. The caller retries, so the replica that was offline still gets
the delete once it returns.

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

* filer: retry deletes refused for an offline replica

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

* volume(rust): refuse a batch delete while a replica is offline

Mirrors the Go volume server: batch_delete checks that the master lists
every replica of a replicated volume before deleting, and answers 503
with the replica count error otherwise.

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

* filer: move exhausted deletion retries to dead letter queues

A deletion that still fails after the backed-off retries is no longer
dropped. It moves to a dead letter queue retried after 24 hours, then to a
second one retried after 48 hours, and is dropped only if that fails too.
The id stays in the durable deletion ledger the whole time, so a restart
replays it instead of losing it.

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

* volume: report a low-disk volume as read-only but deletable

A volume is read-only while its disk is low on space, but it still
applies deletes; only noWriteOrDelete refuses them. The heartbeat set
readOnlyCanDelete from the operator mark alone, so the master listed a
low-disk replica as refusing deletes and the replica count check
rejected every delete on its volumes, on the healthy replicas too.

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

* volume(rust): report a low-disk volume as read-only but deletable

Mirrors the Go heartbeat: readOnlyCanDelete is set whenever the volume
is read-only without no_write_or_delete, which includes low disk space.

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

* filer: retry deletes a low-disk replica could not record

A low-disk volume now counts as deletable, but appending the tombstone
can still fail with no space left on device. Treat that as retryable so
the deletion stays queued instead of being dropped after the other
replicas applied it.

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

* master: keep under-replicated volumes out of empty-volume cleanup

The cleanup only looked at the copies the master lists. With a replica
offline the listed copies can be empty and quiet while the missing one
still holds data, and deleting them would leave that copy as the only
one when it returns. Low-disk replicas now report readOnlyCanDelete and
pass the eligibility check, which made this reachable for more volumes.

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

* master: finish a partly deleted empty volume in the next sweep

When one copy's VolumeDelete succeeded and another failed, the vid was
left with fewer copies than its replica placement, so every later sweep
skipped it as under-replicated and the empty copy kept its slot. The vid
now stays marked deleting after a partial delete, and the next sweep
finishes it. The mark is cleared once the vid is gone or stops being an
empty, quiet candidate.

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

* master: keep the cleanup mark while a survivor is only read-only

A partly deleted empty volume lost its deleting mark when the next sweep
found a surviving copy read-only. Later sweeps then skipped the vid as
under-replicated, so the empty copy kept its slot after it became
deletable again. Only a copy that gained data or was written recently
clears the mark now; a read-only or missing copy just postpones the
cleanup.

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

* shell: delete an empty volume only when every copy is empty

volume.deleteEmpty judged each copy on its own, so it removed an empty
copy while another copy still held data or was offline, leaving that
one as the volume's only copy. Low-disk copies now report
readOnlyCanDelete and passed the check as well. Apply the master
sweep's rule: every copy is listed and every copy is empty.

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

* shell: name the copies a partial empty-volume delete leaves behind

Once some copies of a volume are deleted, a rerun of volume.deleteEmpty
skips the rest as under-replicated, and the shell keeps no state to
finish them. Log each copy whose delete failed with the volume.delete
command that removes it once it is empty.

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

* shell: keep the gRPC port in the printed volume.delete command

ServerAddress.String() drops a custom gRPC port, so the printed -node
would dial the HTTP port plus 10000. Print the full address.

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

* filer: let manifest retries pass through the dead letter queues

The manifest retry queue reuses DeletionRetryQueue, so a manifest that
does not resolve now waits through both dead letter queues before it is
deleted alone.

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

* volume(rust): look up a batch delete's replicas over the master's gRPC port

lookup_volume now dials the master's gRPC port, as Go's LookupVolumeIds
does; the replica check and its test follow.

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

* volume: let a batch delete through on a volume grown degraded

A volume the master grew with fewer copies than its placement reports
min_writable_copies in the lookup. Go's replica check already uses it;
Rust now does too, so deletes on such a volume are not refused forever.

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

* volume, shell: let volume.merge write deletes into its merged copy

volume.merge marks the source copies read-only and writes the merged
records, deletes included, into a temporary copy that replaces them. The
batch delete replica check counts only the temporary copy there and
refused every delete, so the merge stopped at its first tombstone.
BatchDeleteRequest.skip_replica_check lets a caller that updates the
other copies itself skip the check; volume.merge sets it.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:14:33 -08:00
Chris LuandClaude Opus 5.5 25b9278d60 mq: conditional topic.conf saves, bounded topic.conf I/O, and mq.balance moves that save their assignment (#13231)
* mq broker: give up topic.conf filer calls with the caller's context

The topic.conf read and save helpers took no context, so a filer that took
the call and never answered kept the balancer inside topicConfLock for good,
and every ConfigureTopic, lookup repair and EndPartitionGeneration queued
behind it on a plain mutex. reportGenerationEnded's per-attempt deadline
could not bound any of it. The helpers now take a context, the RPC paths pass
their request context, and topicConfLock is a one-slot semaphore whose wait
ends with the caller's context. Calls made while holding it are also bounded
by topicConfTimeout, so a caller without a deadline cannot hold it forever.

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

* mq broker: save topic.conf only if it is still what was read

Every topic.conf update is a read-modify-write on the balancer, but the save
was unconditional, so a balancer whose lease ran out between its read and its
save wrote its stale assignments over a successor's newer epoch. topicConfLock
only orders writers within one broker. A failed read in ConfigureTopic could
also recreate an existing topic from scratch.

The read now returns the topic.conf entry, and the save is an ObjectTransaction
requiring that entry unchanged, or the file still absent for a new topic. A
refused save is redone from a fresh read a few times, so a report for an epoch
a successor already ended finds it moved on, and then gives up with
Unavailable for the caller to retry.

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

* mq broker: save mq.balance moves to topic.conf before assigning them

A balance move only told the target to load the partition and the source to
drain it. It never touched topic.conf, so lookups kept sending publishers to
the source, and since partitions are fenced by epoch the target was asked to
lead at epoch 0 and refused before anything moved.

The balancer now runs the move itself: it saves the target as leader at the
next epoch through the conditional topic.conf save, tells the source about the
new epoch so it retires its copy, flushing what it holds under its own fence
and sealing it, and then assigns the target, which takes the fence at the new
epoch. A follower that becomes the leader swaps places with the old leader.

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

* mq broker: keep a retiring leader's fence renewed until it seals

A leader told of a newer epoch, as a balance move's source is, retires its
copy by shutting it down and waiting for its last flush before sealing the
fence, but it did not renew the fence meanwhile. A flush outlasting
fenceSealWait left an aged unsealed fence the new leader could take, and the
pending flush then failed its fence check and dropped acknowledged messages.
The fence is now renewed for as long as the flush takes. Loaders retiring the
same copy at once share one renewal, which the first to return stops before
any seal, so no renewal lands on a sealed fence.

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

* mq broker: save a configure's assignment repair with its update

ConfigureTopic saved the repair of assignments on dead brokers on its own,
then saved the requested schema or retention change against the entry it had
read before that repair. The second save was always refused, so the update
went round a full reread, and a resize first drained brokers for nothing. The
repair is now applied in memory and saved together with the requested change
in one conditional save. A resize replaces the assignments anyway, so it no
longer saves a repair first.

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

* mq broker: report a balance move the target refused

assignTopicPartitionsToBrokers logged each broker that refused its assignment
and returned nil, so mq.balance reported success for a move whose target never
took the partition, after topic.conf had already moved and the source had
retired its copy. It now returns the refusals, and BalanceTopics passes them
to its caller. The saved move stands: a retry assigns the target again, and
the target also loads the partition on first use. ConfigureTopic keeps
logging a refused assignment of a topic it has saved, as before.

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

* mq broker: give up a topic.conf cache miss with the caller's context

getTopicConfFromCache waited for topicConfLock and read the filer under
context.Background(), so a lookup whose caller had already given up stayed
queued behind whatever held the lock and then did up to topicConfTimeout of
filer work for nobody. It now takes the caller's context, which LookupTopicBrokers
and the retention purge pass along and the partition loaders pass as
Background; cache hits are unchanged. A waiter whose context has already ended
no longer takes a free lock either, since a select with both cases ready picks
one at random.

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

* mq broker: require exactly one moved partition in the balance tests

The move tests took the last partition led by the target as the moved
one, so a move that handed both partitions to the target would pass.
They now fail unless exactly one partition moved.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:03:20 -08:00
40bb214b3f s3api: store a re-copied multipart part as a new attempt so the earlier copy's data is freed (#13216)
* s3api: replace a re-copied multipart part in place so the old part's data is deleted

UploadPartCopy into a part number that already held a part removed the
old part entry with isDeleteData=false and then wrote the new one. The
filer deletes the chunks an entry replaced only when it overwrites that
entry, as UploadPart does, so the old part's chunks were left on the
volume servers with no entry referencing them, for every retried or
repeated copy of a part. The same applied to an empty-range copy.

The part entry is now written over the existing one: the filer deletes
the chunks the new entry does not hold, and the part is never missing
between the two writes.

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

* s3api: store each UploadPartCopy as a new attempt of the part instead of replacing it

Replacing a copied part in place deletes the replaced part's chunks while
the upload is open. A CompleteMultipartUpload that listed the part before
the replacement builds the object from those chunks and can commit it
after they are deleted. UploadPart never replaces a part: each upload is
a new attempt with its own name (genPartUploadPath).

copyPartLocation now names each copy the same way, and nothing is replaced
or deleted when a part is copied again. Completion already uses the latest
attempt of each part number and frees the data of the others after it
commits, and abort frees them all, so the earlier copy's data is still
reclaimed, without a window against a completion in progress.

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

* s3api: trim the UploadPartCopy attempt comments

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-12-01 12:32:11 -08:00
Chris LuandClaude Opus 5.5 0872953b81 mount: resolve NFS file handles across a weed mount restart (-nfsExport) (#13020)
* mount: persist a created file's entry at create time under -nfsExport

A file created over NFS gets a handle at create time. With creation
deferred to flush, a mount that stops before the flush leaves no entry for
the next mount to resolve that handle to.

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

* mount: resolve NFS file handles of files an earlier mount had open

With -nfsExport, the mount records on the filer the path of each file it
has open, keyed by inode, and drops the record a minute after the last
close. A "." lookup on a node id the mount does not know reads that
record, so the NFS server can reopen its files after the mount restarts or
another mount takes over. A failed read answers EIO rather than ESTALE.

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

* mount: record NFS handles at open, not on every path refresh

A writeback close flushes after the last release, and the flush refreshes
the handle's path. Recording there renewed the record of a file no longer
open, so it was never removed. Opens and creates now record, and a path
refresh only moves an existing record.

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

* mount: leave writeback creates deferred under -nfsExport

With writeback caching an eager create runs as an async filer RPC that an
unlink does not wait for, so a quick create+unlink could bring the name
back. Writeback mounts already accept losing unflushed files on a crash.

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

* mount: retain a recorded handle path only once it matches the file

A path read from the filer record was retained before the lookup checked
it, so a stale one kept answering ESTALE without reading the record again.
It is now retained right before LookupHandle, and never over a forgotten
inode or path the table already holds.

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

* mount: count NFS handle opens, keep other mounts' records, retry writes

A reopen that attached a new handle before the close registered its
release left a removal pending for an open file; opens are now counted.
Records carry the writing mount's signature, so a delayed removal leaves
a record another mount wrote since. A failed write is retried while the
inode's state is unchanged, and the put runs under the attempt context.

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

* mount: keep one NFS handle registration per mount in an inode's record

Two mounts with the same file open shared one record, so the one that
closed last removed the path the other still had open. Each mount now
replaces or drops only its own registration, and a lookup uses the newest.

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

* mount: name a mount's NFS handle registrations by host and mount directory

A restarted mount drew a new random signature, so it never replaced or
removed the registrations its predecessor left for files it had open.

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

* mount: take turns on an NFS handle record through the lock manager under -dlm

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

* mount: retry an NFS handle record update when its lock is not granted

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

* mount: renew an NFS handle record's lock for the whole update

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

* mount: resolve an NFS handle record to the newest path under the mount root

Another mount rooted elsewhere could hold the newest registration of a
hard-linked inode, hiding this mount's own valid path.

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

* mount: register an NFS handle at the path the mount knows now

A rename could move the inode after an opener read its path but before
the new handle was registered, so the record kept the old path; a stale
opener could also move an existing record back.

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

* mount: keep no NFS handle records with -filer.tokenFile

The filer refuses KvGet and KvPut to scoped tokens, so the records would
only fail: log at startup instead, and keep the in-process handle support.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:31:17 -08:00
f9157933f0 volume: refuse a write the local volume already rejects before forwarding it to the replicas (#13214)
* volume: refuse a write the local volume already rejects before the replica fan-out

ReplicatedWrite runs the local needle write and the replica fan-out
concurrently. When the local volume is read-only (noWriteOrDelete or
noWriteCanDelete), unavailable, or on a disk below -minFreeSpace, the
local leg fails, but the replicas have already stored the needle. The
client writes to a new file id, so the replica copy is referenced by
nothing, and the copies of the volume differ in file count and size
until volume.fsck purges it.

Ask the volume whether it accepts writes (Volume.CheckWritable, the
same check Store.WriteVolumeNeedle applies first) before the fan-out
starts, and fail the request without contacting the replicas. The error,
its metrics and the ErrorWriteRefused rule are those of a failed local
write. A type=replicate request, and a write with no local copy, are
unchanged.

A volume that turns read-only after the check, during the write, still
leaves a replica copy.

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

* volume: observe a write refused before the fan-out in the local write histogram

The local write that the up-front refusal replaces observed the refusal in
the WriteToLocalDisk request histogram next to the error counter. Observe
it there too, so a refused write is counted as before. The replication
metrics do not record it, since it no longer reaches the replicas.

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

* volume(rs): refuse a write the local volume already rejects before forwarding it to the replicas

Mirror the Go up-front check: when the local volume refuses writes, the
replicated upload fails with the local refusal and never spawns the
replica fan-out, so no replica keeps a needle nothing references.

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-12-01 12:03:04 -08:00
Chris LuandClaude Opus 5.5 f65234685a filer.sync: check the stream bottleneck test by peak jobs in flight (#13233)
TestConcurrencyIneffectiveOnStreamBottleneck compared the wall-clock
rates of separate runs at concurrency 32 and 512 and failed on a loaded
32-bit runner when one run took 1.6x longer than the other. The ratio
measured runner load, not the processor.

Record the most jobs that ran at once instead. While it stays below the
smallest limit, the limit never holds back an event, which is why a
larger -concurrency cannot help a stream-limited sync.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:01:24 -08:00
MapleWhiteZZZandMapleWhiteZZZ 76cae100de filer: leave the manifests an update keeps unread when finding its garbage (#13224)
MinusChunks finds the chunks an update drops by resolving every manifest of
the old entry and of the new one. A manifest both entries list is the same
needle on both sides: all it holds is held by both, so none of it can be
dropped, yet it was read from a volume server twice on every update. A file
whose older chunks are folded into manifests paid that on each chmod, utimes,
setxattr and append.

Manifests listed on both sides are now taken out of both lists before the
others are resolved. They are read only when something else the old entry
holds might still be held through one of them, and then subtracted, so the
result is the one resolving everything gives. An attribute change or an
append that keeps the manifests reads none of them, and a kept manifest
that cannot be read no longer fails an update that drops nothing.

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
2026-12-01 12:00:31 -08:00
Yip LeoandClaude Opus 5.5 0b0f54381d s3api: list every entry of the upload directory when completing a multipart upload (#13219)
prepareMultipartCompletionState read the upload directory with one
listing of MaxS3MultipartParts+1 entries and ignored whether more
remained. The directory holds one entry per attempt of a part, as each
UploadPart gets its own name, so an upload with many parts and some
retries can hold more, and the parts that sort after the first page were
never found: completion answered InvalidPart for parts that exist. The
cleanup listing of an already committed completion was capped the same
way.

listUploadEntries lists the directory page by page until the listing
reports its last entry, and both listings use it. The completion test
filer now pages like the filer, which its map-order listing had hidden.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:59:35 -08:00
Yip LeoandClaude Opus 5.5 e8fef6bdfd mount: fail a read of dirty pages that cannot be read back from the swap file (#13215)
Dirty pages that weed mount buffers in the swap file (non-sequential
writes, or when the memory chunks run out) also serve reads until they
upload. SwapFileChunk.ReadDataAt logged a read error and stopped,
returning only how far it had read; UploadPipeline.MaybeReadDataAt and
DirtyPages.ReadDirtyDataAt passed that offset up. The mount read path
then served the rest of the range from the stored chunks or from zeros,
and the read returned OK. A read error on the cache disk, or a swap file
truncated by an outside cleanup, is enough: the application reads back
bytes it was told were written and gets other bytes, with no error
anywhere. This is the read-side twin of #13198, which made the upload
of those bytes fail.

PageChunk.ReadDataAt, UploadPipeline.MaybeReadDataAt and
DirtyPages.ReadDirtyDataAt now return an error besides the offset. A
swap chunk that cannot read back an interval overlapping the requested
range returns it, wrapping the new ErrDirtyDataUnreadable and the read
error (a short read is io.ErrUnexpectedEOF). Intervals outside the range
are not read, so a read that does not touch the lost bytes still
succeeds. MemChunk cannot fail. The read handler and copy_file_range
turn the error into EIO. Read does not refresh the filer entry and retry
for this error, since the entry has no say over bytes that only exist in
the swap file.

A failed read does not mark the handle failed. Reads of other ranges and
writes keep working, and the upload path already records the failure
when it cannot read the same bytes, so flush, fsync and close return EIO.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:58:05 -08:00
30d7f484aa s3api: delete the chunks a failed CopyObject or UploadPartCopy wrote (#13217)
* s3api: delete the chunks a failed CopyObject or UploadPartCopy wrote

A copy writes new needles for the destination before any entry
references them. copyChunks and copyChunksForRange returned on the
first failed chunk without waiting for the copies still running, and
nothing deleted the chunks already written. The running copies went on
to write needles after the request was over; the written ones were never
referenced. The same happened when the copy succeeded and the later
write of the entry failed or a destination precondition refused it, and
in the per-chunk loops of the SSE copy paths.

The concurrent copies now go through copyChunksConcurrently: no further
copy is started after a failure, every started copy is waited for, and
the chunks the others wrote are deleted with deleteOrphanedChunks. The
sequential SSE loops delete what they wrote when they fail part-way. A
chunk a failed copy returned is not kept anywhere, so nothing is left
for volume.fsck.

CopyObject and UploadPartCopy delete the copied chunks when a
precondition or the lock refuses the write, or when the write of the
entry fails and no filer holds an entry at that path that references
them: a failed write can have committed (the answer lost), and chunks
deleted under a stored entry would break the object. An answer the
lookups cannot settle keeps the chunks. Chunks the source entry also
holds (the SSE-KMS same-key rotation hands them back) are never deleted.

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

* s3api: keep a failed copy's chunks when any entry exists at the destination

After a failed write of the destination entry, the copied chunks were
deleted when the first entry the lookup found did not hold them. That
entry can be an older one on one filer while the copy's own entry
committed on another, for example a part written to a filer the routing
failed over to, so the delete could reclaim chunks a stored entry holds.

Delete them only when no filer holds an entry at the path and every filer
answered, as putToFiler does. A copy that fails over an existing object
therefore still leaves its chunks.

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

* s3api: keep a copy's chunks when its failed write may still commit

A write of the destination entry that fails without the filer's answer
(a transport failure, a timeout or a cancel) can still be running on the
filer. A lookup that finds no entry then proves nothing: the write can
commit after it, and an entry would reference the chunks the cleanup
deleted.

Keep the copied chunks after such a failure without a lookup; these are
the errors filerErrorToS3Error keeps retryable for the same reason. The
lookup now runs only after the filer answered the write with an error.

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

* s3api: keep a copy's chunks whenever its write of the entry fails

A failed write of the destination entry can have committed with its
answer lost, or still commit: after a transport failure, or when a
failover replay that another filer refused hides an ambiguous first
attempt. A lookup cannot tell these apart, and chunks deleted under a
stored entry break the object, which is worse than the leak.

CopyObject and UploadPartCopy therefore keep the copied chunks when the
write fails. They still delete them when the lock or a precondition
refuses the write, or the old part cannot be removed, before any entry
write is attempted.

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

* s3api: size the copy-owned chunk set without adding slice lengths

CodeQL flags the summed capacity hint as a possible allocation overflow;
the map grows as needed anyway.

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-12-01 11:57:00 -08:00
Chris LuandClaude Opus 5.5 3809cfe4cf mq: fetched messages carry their log offset (#13229)
* mq: carry the log offset on fetched messages

FetchMessage answers with DataMessages that have no offset, so a client
can only number them by position from its start offset. That is wrong as
soon as the stored range has a hole or an entry the log cannot place.
DataMessage gains an optional offset; presence tells a broker that sets
it apart from one that predates it.

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

* mq broker: send each fetched message's log offset

FetchMessage dropped the offset of every log entry it read, leaving clients to number the messages by position. Each DataMessage now carries its LogEntry offset, including -1 for an entry the log could not place.

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

* mq/kafka: number fetched records by the broker's offsets

The gateway numbered the records of a fetch as start offset plus position, and moved the next fetch past them by count. A hole in the stored range, such as offsets 10, 11 and 13, put record 13 at 12 and fetched it again at 13. Records now take the offset the broker sends, the batch offset deltas and the next offset follow those offsets, and an entry the broker reports at -1 is left out rather than given a guessed offset. A broker that sends no offsets is still numbered from the start offset.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:51:08 -08:00
Chris Lu abd2587f9e s3api: send user metadata headers in lowercase (#13228)
GET/HEAD returned user metadata as X-Amz-Meta-<key>. AWS sends
x-amz-meta-<key>, and older aws-sdk-kotlin releases match the prefix
case-sensitively, so they saw no metadata at all. Airbyte's S3
destination reads ab-generation-id that way at the end of an Overwrite
sync, treats a missing id as generation 0, and deleted the files it had
just written.
2026-12-01 11:36:58 -08:00
Chris LuandClaude Opus 5.5 d6dee41f00 ec: do not place shards on a volume server in maintenance mode (#13227)
* master: report a volume server's maintenance mode in DataNodeInfo

Planners that work from VolumeList had no way to tell a volume server in
maintenance mode from any other, so they kept choosing it as a target.

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

* admin: give a volume server in maintenance mode no free capacity

It refuses new data, so EC encode and balance planning must not pick it as
a destination; it stays listed so it can still be a source.

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

* ec_balance: never move shards to a volume server in maintenance mode

It refuses every shard copy, and right after an evacuate it is the emptiest
server, so the planner kept targeting it.

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

* shell: count no free EC shard slots on a volume server in maintenance mode

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

* ec: report the volume server's error when it refuses a shard upload

A refused ReceiveFile ends the stream, so Send returns only io.EOF and the
job logged "failed to send file content: EOF" instead of the reason.

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

* ec: test that a refused shard upload reports the server's error

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

* shell: never plan EC shard moves onto a volume server in maintenance mode

Zero free slots alone did not keep it out: a shard the planner moves off
the node credits a slot back, and a later move could take it.

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

* ec: test that ReceiveFileSendError reports a refusal in the response's Error field

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

* ec_balance: move the maintenance-target test to the end of the file

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:06:18 -08:00
76aa922d06 shell: let fs.du print subdirectory totals and list directories in parallel (#13212)
* shell: let fs.du print subdirectory totals and list directories in parallel

fs.du prints one total and walks the tree one directory at a time. Finding
where the data of a large bucket sits takes one fs.du per directory, each a
full walk, and every listing waits on the filer and its store in turn.

-depth N also prints the total of each directory down to N levels below the
given one, like du -d N. Directories come in du's order: each one after the
directories below it, siblings by name, and the given directory's total
last, as before. One walk now gives the whole breakdown.

-concurrency N lists up to N directories at a time. A subdirectory gets a
goroutine of its own while the limit allows one and is walked in place
otherwise, so memory grows with depth and concurrency, not with the number
of directories. filer_pb.TraverseBfs is not used because it remembers every
directory it visits and queues whole levels: on a tree of 200k directories
it held 49 MB more live heap than this walk at the same speed, and weed
shell often runs in a small container. A directory's listing is complete
before its subdirectories are walked, so no listing stream stays open while
a subtree is walked.

A directory that cannot be listed used to drop out of the totals silently.
It is still left out, but the command now fails at the end with the number
of such directories and the first of them. fs.du took its last argument as
the path, or the current directory when that argument started with a dash,
so "fs.du /dir -depth=1" would have walked the current directory. Flags now
go before the path, and anything else is an error. With a prefix
(fs.du /dir/name_prefix) and no -depth, the directories the prefix matches
are no longer walked, because nothing below them is printed.

The defaults, -depth=0 and -concurrency=1, print what fs.du printed before.

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

* shell: fs.du walks a page of subdirectories before listing the next one

fs.du collected the names of all subdirectories of a directory before it
walked any of them, so a directory with millions of subdirectories held
millions of names. It now lists 1024 entries at a time and walks the
subdirectories of a page before it asks for the next page. A directory
holds at most one page of names, and still no listing stream stays open
while its subdirectories are walked. On one directory with 200k
subdirectories the walk holds 0.5 MB of live heap with -concurrency=1 and
2.5 MB with -concurrency=5.

When a page of a listing fails, the pages before it still count and the
failed page is dropped. The help and the error said that such a directory
was left out of the totals; they now say that the totals are incomplete.
When the given directory itself cannot be listed, fs.du cancels the walks
under way and waits for them before it returns the error.

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

* shell: fs.du tests refuse a listing the way a failing filer store does

An Unavailable without details makes pb close the shared connection, so the
listings running beside the refused one failed with "the client connection
is closing" and the error named another directory (6 of 30 runs with -race).
A store error reaches the client as Unknown and leaves the connection up.

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

* shell: fs.du lists directories in parallel without a -concurrency flag

The walk prints the same totals in the same order at any concurrency, so
there is nothing for a user to choose: list up to DefaultMaxParallelization
directories at a time, like the other shell commands that fan out.

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-12-01 11:01:37 -08:00
Chris LuandClaude Opus 5.5 13d9f3b104 mini: run weed-vector and weed-worker by default, continuing without either if missing (#13207)
* mini: start weed-worker with the vector engine

With -vector, mini now also starts weed-worker, the Lance maintenance
worker that builds vector and metadata indexes, finding it the way it
finds weed-vector: beside weed, then on PATH. -vector.worker=false leaves
it out and -vector.worker.binary names another binary.

The Lance Namespace trusts the worker only by a token derived from
jwt.filer_signing.key. A cluster with that key hands it to the worker
through security.toml as before. Without one, mini makes a key for the
run, gives it to the worker in its environment, and lets the namespace
accept it while no cluster key is set. The filer and the other services
are unaffected, so unauthenticated filer writes keep working.

* mini: run the vector engine by default, without failing when it is missing

-vector now defaults to true, so a plain weed mini starts weed-vector and
weed-worker whenever they are installed. Both binaries are looked up
before ports are reserved; one that is not found is logged and left out,
and mini runs without it. A vector engine that fails to start is logged
the same way instead of shutting mini down. -vector=false still leaves
vector search out.

* mini: clear the vector state a previous in-process run prepared

prepareMiniVector returned early without clearing the paths and key an
earlier run in the same process had set, so a rerun with
-vector.worker=false still started that run's weed-worker.

* mini: pass the [grpc.worker] certificates to weed-worker

weed-worker takes its admin TLS only from --tls-ca, --tls-cert and
--tls-key, not from security.toml, so behind an admin secured with
[grpc.admin] the worker mini started dialed in plaintext and never
connected. Mini now passes the certificates its Go workers dial admin
with, chosen as security.LoadClientTLS chooses them.

* mini: find weed-worker without new flags

Drop -vector.worker and -vector.worker.binary. weed-worker is looked up
beside weed, then beside the weed-vector mini starts (so an explicit
-vector.binary also locates it), then on PATH; -vector=false leaves both
out.

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

* docker/s3vectors: keep mini from starting a second engine and worker

The demo runs weed-vector and weed-worker in their own containers. With
-vector on by default, mini in an image that ships both binaries would
start another engine and worker beside them.

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

* mini: look for weed-worker beside a relative -vector.binary

filepath.Join drops the "." of ./weed-vector, so the sibling candidate
became a bare name and LookPath searched PATH instead. Resolve the
directory first.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:58:00 -08:00
Yip LeoandClaude Opus 5.5 82a435c468 mount: list a directory from the filer when the cache disk cannot hold it (#13204)
* mount: list a directory from the filer when the cache disk cannot hold it

A listing builds the directory into the mount's local metadata cache, a
leveldb store under -cacheDir, and serves it from there. Once that disk is
full the build fails at its first write, and the listing failed with it:
readdir returned EIO for every directory the mount had not cached, and for
one whose cached listing a refused event had just dropped (#13141). Files
could still be opened, read and written; only listing them broke.

A build the store refuses now reports a LocalStoreError, and the listing
reads the directory through from the filer, the way it already does for a
directory too large to cache. Builds then wait out a 10s backoff instead of
re-listing a directory from the filer only to fail at its first insert
again; once the disk has room the next build caches the directory. While
the store refuses, at most 4 listings per mount read through at once, so a
burst of them reaches the filer spread out rather than all together.

The hand-over from a walk served from the cache to one read through from
the filer resumed at the request's offset, so the entries the cached walk
had just put in the same reply were sent again and the client listed them
twice. A directory found too large partway through a walk took that path
rarely; a full cache disk takes it on every request. The direct walk now
resumes past the entries already in the reply.

Lookups needed no change: in a directory the cache does not hold, a lookup
already asks the filer for the one entry.

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

* mount: list unflushed creates and every page when reading a directory through

Listings read through from the filer are now the common path on a full
cache disk. This fixes three gaps in them:

- A file created on this mount is not on the filer until its first flush.
  Until then the local store holds a placeholder for it, which a rebuild
  keeps. A cached listing showed such a file; a listing read through from
  the filer left it out. The read-through now merges in, page by page and
  in name order, the children the local store keeps for a rebuild
  (MetaCache.LocalOnlyChildren, which asks the same pinnedChildFn as the
  rebuild's wipe). Each page takes the ones after its start and up to its
  last name; the last page takes every one past its start. A name the
  filer also has by now is listed once. Directories too large to cache
  read through the same way, so they get the fix as well.
- The filer applies the page limit before the loader leaves out the root's
  hidden system entries (etc, topics). A full page that held one came back
  short, and the listing ended there. The end of the directory is now read
  from the number of entries the filer sent. If a failover reruns a page,
  the loader starts its entries and that count over.
- A walk served from the cache also hands over to the filer when
  refreshing a stale section would list too many entries
  (ErrRefreshRangeTooLarge). That hand-over still resumed at the request's
  offset, so it sent again the entries already in the reply. It now
  resumes where the cached walk reached, like the other hand-over.

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

* mount: keep the rest of a read-through page on the directory handle

A page listed from the filer went onto the directory handle only up to the
entry the reply had no room for. The next request listed the filer again
from there and merged the unflushed creates again, so with small replies
each filer page was listed, and the local store scanned, once per reply.
Now the whole page goes onto the handle, and later requests take what is
left from it, as they do from the cache. The unflushed creates are also
looked up without decoding chunk lists.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:57:29 -08:00
a2a7a589bb filer: keep the content out of S3 config parse errors (#13202)
* filer: keep the content out of S3 config parse errors

protojson's errors quote the token they reject, and in these files that
can be a secret key or KMS key material, so a config that didn't parse
could log part of a key. The error now gives the line and column, the
field's type and name for a value of the wrong type, or says the file
ends early. Syntax errors come from encoding/json, which gives an offset
instead of a quote, so protojson's text is only read for valid JSON.

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

* filer: keep codespell from flagging a parse error test case

Codespell reads `tru` in `{"é": tru#` as a misspelling. `nul#` fails at
the same column.

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

* credential: run the store interface tests on the memory store

The tests took the first registered store, which depends on package
init order: once filer_etc registered first they ran against a filer
that is not there.

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

* credential: keep the content out of static S3 config file parse errors

LoadS3ConfigFile parsed the -s3.config file with protojson directly, so
the filer logged a rejected token such as a secret key. It now uses
ParseS3ConfigurationFromBytes like the other readers of that file.

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-12-01 10:56:25 -08:00
19204293c2 filer: always range-fetch a chunk too big for the reader budget (#13201)
* filer: always range-fetch a chunk too big for the reader budget

A whole chunk view bigger than the reader cache budget only fell back to
a range fetch in random mode. A sequential read, or a read across a
chunk boundary, took the whole-chunk path and failed with "chunk buffer
needs N bytes, exceeding reader cache budget". Prefetch also started
such chunks, which took a slot in the cache and then failed.

readsRange now decides for both read paths, and a chunk that can't fit
the budget is always a range fetch. Prefetch skips it.

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

* filer: test that prefetch skips a chunk over the reader budget

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-12-01 10:55:20 -08:00
Chris LuandClaude Opus 5.5 f9c08ad379 docker: keep resolv.conf readable after dropping to the seaweed user (#13213)
* docker: make resolv.conf and hosts readable before dropping to the seaweed user

A Docker daemon running with a restrictive umask writes the container's
/etc/resolv.conf and /etc/hosts as 0600. The entrypoint then drops to the
seaweed user, which cannot read them, so Go's resolver falls back to
localhost:53 and every peer lookup fails with connection refused, while
nslookup through docker exec (root) still resolves.

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

* docker: warn when resolv.conf stays unreadable to the server user

The entrypoint cannot fix the mode when the file is mounted read-only,
under a user namespace, or when the container starts as a non-root user,
so say why peer lookups are about to fail.

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

* docker: warn about an unreadable /etc/hosts too

Names defined only there stop resolving the same way, and resolv.conf
may be readable while hosts is not.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:53:45 -08:00
Chris LuandClaude Opus 5.5 3beca7d956 mq: resume inside the file holding the resume point, and start offset reads near the offset (#13209)
* mq logstore: resume a timestamp read inside the file that holds the resume point

A disk read by timestamp listed the partition from the file named after the
resume second and dropped every earlier name, so the file that started before
that second but still held messages after the resume point was skipped and
its remaining messages were never delivered. The reader now keeps a sparse
index of the partition's log file names, starts listing at the last mark
before the resume second, and reads the last file starting before that
second along with every later one; its entries up to the resume point are
already filtered by timestamp. This covers names with and without the offset
suffix.

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

* mq logstore: read a log file's offset range in one place

The disk reader decoded offset_min and offset_max inline in three places, by
string literal rather than the mq constants. A single logFileOffsets helper
now reads both, so the reader and the offset index added next agree on what a
file records. No behavior change: the flush writes both attributes together.

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

* mq logstore: start an offset read at the indexed file holding the offset

A disk read by offset listed the whole partition directory on every call and
filtered the files by their offset ranges, so a lagging consumer paid for the
partition's entire history on each read. The reader's sparse index of log
file names now also keeps each mark's first offset, and an offset read lists
from the last mark starting at or before its offset; offsets grow with names,
so no earlier file can hold it. The index is extended by every listing past
the last name it has seen, so after the first read a call lists at most one
stride of files before its own plus the files after it. When no mark with an
offset range is at or before the offset, as with files that record none, the
read still lists from the first file.

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

* mq broker: never name a log file before the newest one in its partition

A log file is named by its window's start second, taken from the writing
broker's clock. A new leader whose clock is behind the previous one's wrote
windows whose names sorted before older files holding lower offsets, so names
no longer followed offsets. An offset read listing from an indexed file then
skipped the new windows, and a read starting below such a file passed over it
without notice; no reader-side check can see a file that sorts before where
it starts listing. The partition fence now carries the newest log file time:
the leader seeds it from the listing it already pages to continue the
partition's offsets, which now also reports the newest log file name, legacy
names included and compacted files, the fence and directories excluded. Each
flush names its window no earlier than that time and advances it. Files
sharing a second still sort by their min offset suffix. Timestamp reads
resuming past the old leader's names now list such windows too, though
entries timestamped before the resume point are still filtered out by
timestamp.

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

* mq: bound a log file by its first message time, not its name

Now that a window can be named after a later second than its messages to
keep names in offset order, the disk reader's stop filter, which dropped
every file whose name second was after the stop time, missed windows whose
messages were inside a time-bounded read. A flush now records the window's
first message timestamp on the log file as ts_min, the attribute parquet
files already carry, and the stop filter compares that when present. Files
without it were written before names could be moved later, so their name
still bounds them.

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

* mq logstore: read every offset candidate, not a binary-searched suffix

An offset read binary-searched its candidate files by offset range and
dropped those before the hit, assuming name order matched offset order. A
directory written under clock skew holds a file that sorts before files with
lower offsets, and the search skipped it even on a full listing. The listing
already drops files whose range ends before the offset, so in an ordered
directory the search removed nothing but offset-less legacy files, which are
filtered per entry anyway. The search is gone.

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

* mq logstore: list from the start once a partition's names leave offset order

An offset read lists from the indexed file starting at or before its offset,
which is right only while names sort in offset order. Directories written
under clock skew before log file names were kept ordered hold files sorting
before files with lower offsets, and a read listing from a later mark passed
over them. The index now remembers the highest offset it has seen in name
order, and once a file starts below it the partition is unordered and every
offset read lists from the first file, as before the index existed.

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

* mq broker: name a takeover's file no earlier than the newest one stored

A follower taking over named its file by its first entry's time, so a
follower whose clock is behind its lost leader's wrote a name sorting
before files holding lower offsets. It now takes the newest stored name
from the listing it already reads for the high-water mark and names
its file no earlier, as a leader's flush does.

* mq: resume a timestamp read in every earlier file holding later messages

A timestamp read kept only the last file sorting before the resume second,
assuming names bound message times. A window named no earlier than the
newest stored file can sort after a file it does not follow in time: a slow
leader's window of older messages took that last place and the file before
it, still holding messages after the resume point, was never read. A flush,
and a follower's takeover write, now also record the window's last message
time as ts_max, the attribute parquet files carry. Of the files sorting
before the resume second, every one whose last message is at or after the
resume time is read; files without it were named by their first message
and keep the old rule.

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

* mq logstore: return the latest time a timestamp read delivered

A timestamp read returned the last processed file's last message time as
its position, and each chunk's result replaced the file's. Files are read in
name order, and a slow leader's window can sort after a file holding later
messages, so the position went back and the next read delivered those later
messages again; a trailing chunk that delivered nothing also reset a file's
time to zero. The position is now the highest time delivered across chunks
and files.

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

* mq logstore: deliver an offset read's files in offset order

An offset read processed its candidate files in name order. In a partition
written under clock skew a file sorts before files with lower offsets, so
its entries were delivered first, and a reader taking only the first few
entries, as the chunked offset read does, got the wrong ones. The files that
record an offset range are now read in order of their first offset, each in
a place one of them held, so files without a range keep their position. In
an ordered partition this changes nothing.

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

* mq logstore: list a timestamp resume from the start once a name was clamped

A timestamp resume listed from the index's last mark before the resume
second. Once a window is named later than its first message to keep names in
offset order, many such windows can share one clamped second, and the marks
among them sorted after an earlier file still holding messages past the
resume point, so that file was never listed and never reached the check of
its last message time. The index now notes a file whose name is later than
its first message, and from then on a timestamp resume lists from the first
file. Partitions without such a name keep using the index.

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

* mq logstore: start a timestamp resume at a mark bounded by message times

A timestamp resume listed from the index's last mark sorting before the
resume second, falling back to the first file once a clamped name was seen.
That still assumed names bound earlier files' messages: windows whose
messages overlap within one second, none of them clamped, could push a mark
past an earlier file holding messages after the resume point, and the resume
skipped it. Each mark now records the latest message time of every file
sorting before it, from ts_max, or for a file without it the end of the next
file's start second, since such files were named by their first message and
ended before the next began. A resume starts at the last mark whose earlier
files all end before the resume time, so the files it skips hold nothing it
still has to deliver, whatever the names or clocks. The clamped-name flag is
gone.

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

* mq logstore: leave an older file unbounded when the next name was clamped

A file without a recorded last message time was bounded by the end of the
next file's start second, on the reasoning that it ended before the next
began. When the next file is a slower leader's window clamped into that
second, its name says nothing about when its messages, or the older file's,
end; the older file was bounded too early, a later mark qualified, and a
resume past it skipped its remaining messages. The next file now bounds it
only when its name is not later than its first message; otherwise the older
file stays unbounded, no mark after it qualifies, and a resume lists from
before it.

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

* mq logstore: fetch by offset through the log buffer over out-of-order names

The out-of-order name tests drove the disk reader directly. A fetch
goes through the log buffer's disk chunk on top of it, so this reads a
few offsets at a time through ReadMessagesAtOffset over a partition
whose names sort out of offset order, and checks each fetch returns
its own offsets.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:52:54 -08:00
Chris LuandClaude Opus 5.5 746cae3895 mq: enforce topic retention (#13210)
* log_buffer: find a fetched offset in a disk chunk by its offset

A stateless read caches disk reads in chunks aligned to 1000 offsets and
picked the requested message by its distance from the aligned start. A
chunk read from disk begins at the first offset stored at or above that
start, so once the partition's oldest files are gone the chunk begins
later and the read returned messages from further on, under the
requested offsets. The message is now found by its offset, and the next
offset follows the last message returned.

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

* mq broker: start a loaded partition's log at its earliest stored offset

A loaded partition reported its earliest offset as 0 and its log start as
the start of its memory, so neither said where the stored data begins. The
log buffer now keeps the earliest offset still stored: a leader seeds it
from the offset ranges on its files when it loads, it only moves up, and
the partition's offset info and log start report it. A stateless read
below it fails with ErrOffsetOutOfRange instead of being answered from a
later file under the requested offsets.

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

* mq broker: purge a partition's files past its topic's retention

A topic's retention was stored but never applied, so a topic that is not
re-partitioned kept every flushed file. Every five minutes the broker now
purges each partition it leads whose topic has retention enabled. It
deletes the oldest run of files whose newest message is older than the
retention, stopping at the first file still retained so the stored
offsets stay contiguous, and always keeps the file with the highest
offset, which a later load continues offsets from. A log file is judged
by when it was flushed and a parquet file by its newest row; a parquet
file is deleted together with its source log files. The partition's log
start is raised before the deletes, and each delete is a transaction
conditioned on the partition's fence token, so a leader that lost its
fence deletes nothing.

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

* mq/kafka: map an unknown broker error to UNKNOWN_SERVER_ERROR (-1)

The gateway's error table gave UNKNOWN_SERVER_ERROR the code 1, which
Kafka uses for OFFSET_OUT_OF_RANGE, and the broker's table carried the
same value for its unknown and publisher-not-found errors. Today the
mapped code only reaches error text, but a fetch path that answers
OFFSET_OUT_OF_RANGE by its Kafka code would make every unknown broker
failure reset a consumer. The code is now -1. The gateway only tests
these codes against 0 and against specific codes, and the cached
assignment is still dropped on the broker's own code 1, so nothing
treated 1 as success or depended on it.

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

* mq: answer a fetch below retention with OFFSET_OUT_OF_RANGE

A read below the earliest retained offset failed like any other read, so
FetchMessage reported a storage error and the gateway answered
KAFKA_STORAGE_ERROR, which a consumer retries at the same offset forever
once retention has purged it. FetchMessage now answers
ErrOffsetOutOfRange with its own broker code, the earliest retained
offset as LogStartOffset, and the requested offset as NextOffset. The
gateway carries it as ErrOffsetOutOfRange and answers the partition with
OFFSET_OUT_OF_RANGE, so the consumer applies auto.offset.reset; a reset
to earliest asks ListOffsets, which reports the retained start through
the leader's range info.

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

* log_buffer: keep a disk chunk's entries in offset order

A disk read filled its 1000-offset chunk with the first 1000 entries
in the order the files listed, and the lookup searches the chunk by
offset. Files whose names sort out of offset order deliver entries out
of order, so the chunk held the wrong offsets and was cached that way.
It now keeps only the chunk's offsets, wherever they come, and sorts
them before caching.

* mq broker: purge a partition's files in offset order

The purge walked a partition's files in name order and stopped at the
first one still retained. Names sort by the start of a window, which can
be earlier than older files' after a reload, so a file holding higher
offsets could be purged ahead of a retained one below it, leaving a hole.
The walk now goes by each file's first offset, taking a parquet file that
records none from its first source, and by name among equals.

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

* mq broker: round a log file's flush time up to bound its messages

A log file without a recorded newest timestamp is judged by its Mtime,
which the filer keeps in whole seconds, so a file flushed later in the
cutoff's second looked older than messages it may hold. The purge now
takes the end of that second as the bound. A recorded newest timestamp
is still used as is.

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

* log_buffer: keep one entry per offset in a disk chunk

A disk read goes through a partition's log files and then its parquet
files, and a parquet file holds the same offsets as the log files it was
compacted from, so a chunk could take an offset twice and a fetch
returned the duplicate as the next message. The chunk now keeps the
first entry for each offset.

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

* log_buffer: reread a cached disk chunk that lacks the fetched offset

A disk chunk can be cached while its later offsets are still in memory.
Once those are flushed and memory moves on, a fetch past the cached part
hit the cache, found nothing, and returned no messages until the chunk
was evicted. A cached chunk that does not hold the fetched offset is now
dropped and read from disk again.

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

* mq/logstore: record a parquet file's offset range from its sources

The compactor took a parquet file's offset range from its entries'
offsets above 0 and recorded it only when the lowest was above 0, so a
file compacted from a partition's first window recorded no range, and one
whose entries started at 0 would have claimed to start at 1. The range
now comes from the source log files' recorded ranges, including one that
starts at offset 0, and is left out unless every source records one.

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

* mq: keep the earliest offset at or below files that record no range

The earliest stored offset was the lowest offset any file records, so a
file that records none, such as a parquet file compacted from a
partition's first window or a log file flushed without a range, was left
out. A reload or a purge could then start the log above offsets a read
can still return, and ListOffsets for the earliest offset left them out.
OffsetRange now takes the whole entry and keeps the earliest offset at 0
while a log or parquet file records no range, except a parquet file whose
listed sources are all present, as their ranges cover it.

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

* mq broker: keep a partition whose files cannot all be placed by offset

The purge ordered a data file that records no offsets, and whose
sources give none, as if it held the lowest, so an expired one could
be deleted while a retained file below its offsets stayed, leaving a
hole. A partition holding such a file is now left alone; only files
written before offsets were recorded lack them.

* mq broker: purge a parquet file only when each of its sources has expired

The purge deleted every source of an expired parquet file along with it,
judging the whole group by the parquet file's newest timestamp. Message
timestamps are not ordered across reloads, so a parquet file can hold an
expired source next to one still retained, and the retained one went
early. A parquet group is now purged only when the parquet file and each
source in it are past the cutoff on their own; otherwise the walk stops
there.

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

* mq/logstore: record a parquet file's lowest and highest timestamps

The compactor recorded a parquet file's timestamp range from its first
and last rows. Message timestamps are not ordered across reloads, so the
last row need not be the newest, and the recorded ts_max could sit below
messages the file holds, making it look older to the retention purge and
to readers that skip files by time. It now records the lowest and
highest timestamps over all rows.

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

* mq/logstore: keep each compacted row's offset in the _offset column

The compaction schema had no _offset column, so a schematized row's
offset was dropped and a schemaless row never carried one, while the
parquet reader expects the column and a fetch places rows by offset. The
compactor now adds the column when the schema lacks it and fills it for
every row, schemaless ones included, when the source files record their
offsets; otherwise it is left null.

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

* mq/logstore: read a parquet file by its own columns and mark unknown offsets

The parquet reader always expected an _offset column and read rows by
column position, so a file compacted before the column existed was read
out of alignment and panicked with an index out of range. A row with no
real offset also read back as offset 0, so a disk chunk, which keeps one
entry per offset, collapsed such rows into one. The reader now uses the
_offset column only when the file has it, trusts it only when the file
records its offset range, and reports any other row with offset -1,
which keeps it out of reads by offset.

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

* mq broker: keep a purge group that reaches past the first retained offset

A parquet file is purged with its sources as one group, and the sources
need not be contiguous: an expired parquet file could list expired files
on both sides of a retained one, so purging the group left a hole above
the retained file. A group now goes only when every offset it and its
sources cover lies below the first offset left behind; the walk keeps the
first group that does not, and the ones after it. A log file whose
offsets a retained parquet file also starts at now stays until that
parquet file goes.

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

* mq/logstore: give compaction test fixtures file ids no other fixture uses

The parquet reader caches chunks in a package-wide cache keyed by file
id, and each compaction fixture numbered its file ids from 1, so one
fixture could read another's cached bytes; with -count=3 a test read a
parquet file from an earlier run and failed. File ids are now numbered
across all fixtures.

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

* mq/logstore: compact legacy log files apart from ones that record offsets

A compaction group could hold a legacy log file without an offset range
next to files that record one, and a parquet file keeps its rows'
offsets only when every source records them, so the ranged rows lost
their offsets and could no longer be fetched by offset. Groups now split
where a file's having an offset range differs from the group's.

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

* mq broker: treat a parquet file's end as unknown when a source is gone

A parquet file that records no offset range took its last offset from
the sources still present, so one whose later source was already gone
looked as if it ended below a retained file and was purged, though it
may hold that source's offsets above the retained one. A gone or
unranged source now leaves the end unknown, and the group stays.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:18:45 -08:00
Chris Lu d63c225d78 mq: replicate each partition to a follower and hand it to a new pair when one is lost (#13203)
* mq: carry offsets, epoch and heartbeats on the follow stream

The follow stream sent the publisher's raw message, so the follower
could not keep the leader's offsets, and nothing named the generation
or told a quiet leader from a dead one. The stream now carries log
entries with their offsets, the epoch and leader in its init,
heartbeats, and the flushed offset; acks report the follower's offset.
EndPartitionGeneration lets a broker of a broken pair report it to the
balancer.

* mq broker: hand a partition's fence between generations

A fence could only be taken by the next leader, at once. A pair that
breaks needs more: the survivor must keep persisting what it holds
before a new leader writes, and a follower must be able to take the
fence from a leader it lost. The holder can now renew the fence,
which tells a new leader it is still persisting, and seal it when it
is done; a new leader takes an earlier generation's fence once it is
sealed or left unrenewed for 30 seconds. Within one generation the
fence moves only from the leader to its follower, and a sealed one
stays sealed.

Sealing writes a new token, so a follower that read the fence before
the seal cannot take it over after; a plain renewal keeps the token,
so flushes under way still match. A stale leader that reloads seals
its old fence once its last flush lands, so the reload does not wait.

* mq broker: ack a publish once the follower holds it

The leader acked a publish as soon as it was in its own memory, sent
the follower the raw message without its offset, learned its follower
only from the publisher's init message (which the Kafka gateway never
sets), and wrote to one follower stream from every publisher at once.

The leader now takes its follower from the partition's assignment when
it loads the partition and streams each entry, with its offset, from
one sender goroutine in offset order; a publish is acked once the
follower acks that offset. Heartbeats and a 5 second silence limit
tell a lost follower from a quiet one, and a broken pair answers the
publisher GENERATION_ENDED. The follower holds the entries the leader
has not stored yet, drops them as flush notices arrive, and the leader
closes the stream gracefully once it has stored everything, when the
partition unloads. A partition with no follower acks from memory as
before.

* mq: give a partition whose pair broke a new pair

Nothing reassigned a partition whose leader or follower was lost while
the other half lived on: the balancer only replaced brokers that had
left its broker set, and only on its own schedule. A broker of a
broken pair now reports the epoch with EndPartitionGeneration, and the
balancer assigns a new pair and the next epoch, preferring brokers
outside the old pair. A report for an epoch that already moved on is
ignored, so both halves can report, and reassignments are serialized.

* mq broker: a leader that loses its follower stores what it holds and ends the generation

When the follower stream broke, the leader kept serving alone, acking
from memory again. A broken pair now ends the generation on the leader:
it stops taking publishes, renews its fence so a new leader waits,
stores everything it holds under that fence, seals it, and reports the
epoch so the balancer assigns a new pair. A follower that cannot be
reached when the partition loads ends the generation the same way.

* mq broker: a follower takes over from a leader it lost

When the follow stream broke, the follower dropped what it held, so
entries the leader had acked but not stored were gone with it. The
follower now moves the fence from the lost leader to itself, unless
the leader sealed it first, reads what is already stored, stores the
entries above that, seals the fence and reports the generation ended.
The leader acks only what the follower holds, so every acked entry is
stored once, and a leader still writing is fenced out.

* mq broker: reload topic.conf when the balancer names this broker leader

A broker made leader by a reassignment could still hold the previous
topic.conf in its 30 second cache, so it either found no assignment
for itself or tried to take the fence with the old epoch, and refused
publishes until the cache expired. A publish that finds either now
drops the cached config and loads the partition again.

* mq broker: stop routing subscriptions through the follower

A subscription dialed the follower named in its init and advanced its
committed position only while that follower stream existed, so a
partition without a follower never saved a consumer position, and a
dead follower failed every subscription. The leader now tracks the
position itself and saves it when the subscriber leaves.

* mq broker: tell a partition's leader its follower when assigning it

The balancer created a topic's partitions on their leaders with only
the partition and epoch, so a partition made that way never knew its
follower and acked from memory. It now sends the whole assignment. Only
the named leader creates the partition; the follower learns of it from
the leader's follow stream, so the old forward of the leader's request
to the follower, which would have made the follower take the fence
too, is gone.

* mq broker: report an ended generation until a settled balancer takes it

A broker reported a broken pair once. When the lost broker was also
the balancer, the report failed and the partition stayed at a sealed
epoch nobody would serve. The report is now retried with backoff until
a balancer takes it, and a balancer takes reports only after its settle
window, so the new pair is picked from every live broker rather than
the few that reconnected first.

* mq: describe the replicated pair in the failover notes

* mq broker: break a pair whose follower stopped reading

The follower's silence was checked in the loop that sends to it, so
once a send blocked on a follower that stopped reading but kept its
connection, nothing checked again and publishers waited on acks that
never came. The check now runs on its own and cancels the stream.

* mq broker: a follower that cannot ack its leader takes over

An ack that failed to send ended the follow stream with an error and
dropped the follower's entries, though they may include messages the
leader had already acked to publishers. A failed ack now takes over
the partition, as a broken receive does.

* mq broker: retry a takeover through filer errors

A follower taking over gave up on the first failed fence or offset
read, dropping the entries its lost leader had not stored, which may
be the only copy left. It now retries until the fence has moved on or
the broker stops.

* mq broker: keep the fence renewed while a survivor persists

A leader that lost its follower renewed its fence once before
storing what it held, and a follower taking over not at all after
moving the fence, so a store that ran past 30 seconds let a new
leader take the unsealed fence, refusing the survivor's write and
dropping what it held. Both now renew every 10 seconds until they
seal.

* mq broker: leave the follower its copy when a retiring leader dropped a flush

A retiring leader closed its follow stream gracefully once its buffer
shut down, which tells the follower everything is stored, but a flush
that failed until shutdown is dropped. With the filer unavailable both
copies of acked messages went. The stream is now closed only when the
flushed offset reached the last one assigned; otherwise it is broken,
so the follower takes over and stores its copy.

* mq broker: order every topic.conf read-modify-write on the balancer

Only the generation handoff held a lock around its read and save of
topic.conf, so a concurrent ConfigureTopic or assignment refresh that
read the old assignments could save them back over the new pair,
after the reporter had been told the generation was taken. All of
them now take the same lock.

* mq broker: stamp a fence write when it lands, not when it was first tried

A fence write took its mtime before retrying, so a renewal that
landed after a long run of store errors was already older than the
seal wait, and a new leader could take the fence from a survivor
still persisting. Each attempt now stamps the time it is sent.

* mq broker: watch a leader's follower only once its partition is listed

The lost-follower watch started before the partition was registered,
so a pair that broke in that gap ended its generation while the
partition could not be removed, and the partition was then registered
and served after its fence was sealed. Both load paths now start the
watch after registering it.

* mq/kafka: answer a produce on an ended generation with NOT_LEADER_OR_FOLLOWER

A partition whose pair broke answers publishes with GenerationEnded
while the balancer hands it to a new pair, which the gateway mapped
to UNKNOWN_SERVER_ERROR: it kept the session and Kafka clients did not
refresh their metadata. It now maps to NOT_LEADER_OR_FOLLOWER, so the
gateway drops the session and clients look the leader up again.

* mq broker: take a stale fence only if its holder has not renewed it since

A new leader judged an earlier generation's unsealed fence stale by
its mtime, then wrote under the token alone. A renewal keeps the token
and moves only the mtime, so a holder that renewed in between, still
persisting what it held, lost the fence and the write that followed.
Taking a fence judged stale now requires the entry as it was read.

* mq broker: bound the seal when a leader cannot reach its follower

A leader whose replica failed to start sealed its fence and reported
the generation under the broker's access lock with no deadline, and a
fence write retries until it lands, so a filer that kept failing held
every partition operation on the broker. The seal now gives up after
the fence take timeout and the generation is reported regardless.

* mq broker: bound each report of an ended generation

A generation report called the balancer with no deadline, so a
balancer that accepted the call and stopped answering held the retry
loop and the partition stayed unassigned. Each attempt now gives up
after 30 seconds and is retried; a repeat after a save that landed
finds the epoch moved on and returns without writing.
2026-12-01 00:56:20 -08:00
Chris LuandClaude Opus 5.5 5c5e282787 mq: a failed fetch keeps the requested offset (#13208)
* mq broker: keep the fetch offset when a read fails

FetchMessage answered any read error with NextOffset set to the log
buffer's start offset and error code 2, which the broker error table
defines as topic-not-found. That start offset is the earliest offset
still in memory, or 0 before the buffer has taken a message, so a client
that followed NextOffset either rewound to the start of the partition or
skipped every offset that lives on disk. A failed read is now reported
as a storage error, mapped to Kafka's retriable KAFKA_STORAGE_ERROR, with
NextOffset left at the requested offset. Offsets below the buffer are
served from disk, so a read error is never out of range.

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

* mq/kafka: retry a failed broker fetch at the same offset

FetchMessagesStateless treated a broker error with code 2 as "offset too
old" whenever the fetch offset was below the response's LogStartOffset,
and silently refetched from LogStartOffset. Brokers sent code 2 for every
read error, and LogStartOffset is only the earliest offset in the
broker's memory, so a failed disk read made the gateway skip everything
stored on disk. The skipped records were then handed to the fetch path
as if they started at the requested offset. Any broker error is now
returned, and the fetch path retries at the offset it asked for.

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

* mq broker: keep the fetch offset when the partition cannot be loaded

FetchMessage answered a partition it could not load with an empty NextOffset, which reads as offset 0, so a client following NextOffset after a failed lookup or a topic.conf miss would rewind to the start of the partition. The response now carries the requested offset, as the read error path does.

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

* mq/kafka: answer unreadable records with KAFKA_STORAGE_ERROR

A broker storage error reached the Kafka fetch path as a plain error. FetchMultipleBatches dropped it, readRecords dropped the fallback's error too, and the partition was answered with no records and error code 0, which a consumer cannot tell from having caught up. The broker code now travels as ErrKafkaStorageError through FetchMessagesStateless and GetStoredRecords, FetchMultipleBatches returns an error that comes before any batch, readRecords returns the error when it found no records, and the partition is answered with KAFKA_STORAGE_ERROR so the client retries at the same offset.

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

* mq/kafka: require the fetch read-error test to reach the broker

TestFetchMessagesStatelessReadErrorKeepsOffset only checked that no fetch went to another offset, so it also passed when the request failed before reaching FetchMessage. It now requires exactly one fetch at offset 10 and an error carrying the broker's read failure, a storage error for code 56.

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

* mq/kafka: keep a storage error when the fallback read also fails

When the batch read failed with a storage error and the fallback read
then failed another way, readRecords returned only the fallback's
error, which maps to no error code, so the fetch answered an empty
success instead of KAFKA_STORAGE_ERROR. Both errors are now kept.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:47:09 -08:00
29c9e9df04 mq: fix races and a deadlock in the subscriber market (#13200)
* mq: fix races and a deadlock in the subscriber market

The balance loop reads consumerInstances, partition slots and each
consumer's AssignedPartitions without m.mu, while subscriber gRPC
streams mutate them under that mutex: a concurrent map read and map
write that the Go runtime turns into a fatal error, killing the
broker.

balanceRequestChan is unbuffered and sent to under m.mu; when the
balance loop finishes a pass and calls Status() (which takes m.mu),
the sender and the loop deadlock and the consumer group freezes.

adjustBusyConsumers indexes AssignedPartitions with a count derived
from a load that includes inflight assigns, which can exceed the
slice length and panic.

Take m.mu around doBalanceLoad, coalesce balance requests through a
buffered non-blocking send, cap the unassign count at the assigned
slice length, update MaxPartitionCount under the lock, and wait for
the balance loop to exit before closing AdjustmentChan.

Add market_concurrent_test.go: consumer churn across balance ticks
with concurrent adjustment confirms, and a minimal repro of the
index-out-of-range panic. Verified with go test -race.

* mq: send market adjustments outside the lock

Address review of the subscriber market concurrency fix.

doBalanceLoad now collects adjustments under m.mu and the balance loop
sends them after releasing it, selecting on stopChan so shutdown can
interrupt a send blocked on a full AdjustmentChan. Holding m.mu across
the blocking send could freeze the group: a stalled subscriber fills
AdjustmentChan, and RemoveSubscriber cannot take m.mu to remove it.

AddSubscriber registers the instance before applying the incoming
MaxPartitionCount, so the setter no longer no-ops for overlapping joins
that reuse an instance not yet in the market.

Add TestMarketBalanceDoesNotHoldLockWhileSending: fill AdjustmentChan
with no reader and check RemoveConsumerInstance still completes while
the loop is blocked sending.

* mq: apply consumer limit atomically and stamp adjustments at send

Address re-review of the subscriber market concurrency fix.

Register the instance and apply the incoming MaxPartitionCount in one
operation under m.mu (AddConsumerInstanceWithLimit), so overlapping
joins that reuse an instance id keep the latest limit on the instance
the market tracks. The previous add-then-set pair left a window where
the limit could land on an untracked or stale instance.

Stamp each adjustment when it is published, not when it is created.
The loop sends after releasing m.mu, so a send blocked on a full
AdjustmentChan could otherwise age the unsent tail past the inflight
TTL; the next pass would expire it and reassign its partition.

Make TestMarketUnassignWithInflightAssigns deterministic: receive the
first pass's six assigns, stop the loop, then call adjustBusyConsumers
directly and assert it unassigns nothing from a consumer that holds no
confirmed partition.

* mq: rebalance after raising a tracked consumer's limit

Address re-review of the subscriber market concurrency fix.

When a join reuses an already-tracked instance id,
AddConsumerInstanceWithLimit updates that instance's MaxPartitionCount
but returned without requesting a balance. The ticker only acts on a
pending request, and the previous one may have already drained, so a
rejoin that raises the limit left the extra capacity idle until some
other event happened to request balancing.

Request a balance in that branch too, so raising a tracked consumer's
limit takes effect on the next pass.

* mq: reconsider capacity on expiry and guard unassign by owner

Address re-review of the subscriber market concurrency fix.

Expire inflight adjustments on every tick, not only when a balance
pass is pending. A confirmed adjustment can linger in inflight until
its TTL and double-count a consumer's load, so a pass triggered by a
raised limit could see the consumer as full and assign nothing. When
expiry frees that capacity, request a pass so the freed or raised
capacity is reconsidered instead of staying idle.

Guard the unassign confirmation by owner. ConfirmAdjustment now passes
the acknowledging consumer into unassignPartitionSlot, which releases
the partition only when it is still assigned to that consumer. A late
or duplicate unassign ack can no longer clear a partition that was
reassigned to a new owner.

* mq: drop confirmed adjustments from inflight load accounting

A confirmed adjustment stayed in inflightAdjustments until its TTL,
so a partition already in AssignedPartitions was counted twice in the
load. An expiry-triggered pass then saw a healthy consumer as over the
average and unassigned its partitions, restarting subscribers that
were already fine.

Remove an adjustment from inflight as soon as it is acknowledged,
under m.mu, and take m.mu for the TTL sweep so the two cannot race.
Expiry now only retries genuinely unconfirmed adjustments. Also skip
unassigning from a busy consumer when no peer has room to accept the
freed partition.

* mq: scope the market fix back to races and the deadlock

The expiry-triggered rebalance and the confirmed-adjustment removal
added in the last two commits chased a pre-existing load-accounting
behavior: a confirmed adjustment lingers in inflight until its TTL and
is counted twice. That is upstream behavior outside this PR's scope,
and triggering passes on it churned healthy partitions.

Restore the focused fix: the balance-loop data race, the balance-request
send deadlock, the inflight unassign panic, the limit write under the
lock, and the shutdown close-versus-send race. Load accounting is left
as upstream has it.

* mq: fold AddConsumerInstanceWithLimit into AddConsumerInstance

AddConsumerInstance now takes the partition limit and applies it under
m.mu, updating the tracked instance when the id is already registered.
The broker was its only production caller.

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

* mq: wait for the adjustment buffer to fill before the lock test

A fixed sleep let RemoveConsumerInstance run before the balance loop
blocked on a full AdjustmentChan, so the test could pass without
exercising a blocked send.

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-12-01 00:19:07 -08:00
e9fa5802e1 volume: keep a low-disk location read-only until free space is back by a margin (#13199)
* volume: keep a low-disk location read-only until free space is back by a margin

The volume server checks each disk location once a minute and sets the
location's low-disk flag from that reading alone. A disk whose free
space hovers at -minFreeSpace (writes use space, deletes and vacuum give
a little back) flips the flag on and off, and every volume on the
location with it. The master hears each flip in a heartbeat, so it keeps
assigning writes to volumes that are about to turn read-only, and the
write fails with a read-only error. Nothing smooths this: the volume
reads the location's flag directly, and the master's volume layout takes
the heartbeat's read-only bit as it comes (its recovery delay and size
band apply to full volumes, not to read-only ones).

A location that went low now stays low until its free space is 1% of the
disk above the limit, for a percentage limit and a byte limit alike
(MinFreeSpace.IsLowFrom). Going low is unchanged. The margin is a
constant, not a flag: what flips a disk at the limit within one check is
a vacuum, a volume copy or the writes of one minute, each about one
volume (30 GB by default) at most. 1% of a multi-TB disk is about that
much, so a swing of that size does not clear the state, while an
ordinary cleanup of a few volumes does. The disk check runs on one
goroutine per location and is the only writer of the flag, so the
previous verdict it reads cannot change under it; readers only load it.

Every consumer of the flag (heartbeat max volume counts, read-only
flags, volume allocation, EC shard placement) reads the same flag, so
they all see the held state. The live checks of volume copy and
preallocation, which read the disk instead of the flag, only ever refuse
more than the flag does.

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

* volume: do not remember a low verdict from a reading without space values

When statfs fails or times out before any good reading is cached, the
disk status has All, Free and PercentFree at 0, and MinFreeSpace.IsLow
calls that low. With the hysteresis, that verdict was remembered, so a
later good reading between the limit and limit+1% kept the location
read-only, where it used to clear it: a disk whose first check timed out
stayed read-only until its free space cleared the margin.

A reading without space values (All is 0) is now judged by IsLow alone,
as before, and does not change the remembered verdict, which lives in
its own atomic field that only readings with space values update. A
failed reading between two good ones leaves the held verdict as it was.

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

* volume(rs): keep a low-disk location read-only until free space is back by a margin

Mirror Go's MinFreeSpace.IsLowFrom: once a location goes low it stays low
until free space is 1% of the disk above the limit, for percentage and
byte limits alike. A failed statfs reading (total 0) already leaves the
flag untouched.

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

* volume: trim the low-disk hysteresis comments

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

* volume(rs): test the low-disk hysteresis with fixed readings

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-12-01 00:17:29 -08:00
Chris LuandClaude Opus 5.5 43556b3a3c mq: publishers re-look up and resend when a partition's leader changes (#13195)
* mq client: dial brokers with the publisher's dial option

The publisher dialed every broker with insecure credentials, and the
per-partition connection added the configured option on top of them, so
a publisher could not reach a broker that requires TLS. That connection
was also never closed. PublisherConfiguration now takes the dial option,
insecure only when none is given, the agent passes its own, and the
partition connection is closed when its publish job ends.

* mq client: resend unacked messages when a partition's publish stream fails

A publisher sent each message once and kept no record of it. Acks were
only logged, a broker error on the stream was written to a field nobody
read, and the scheduler's wait loop broke out of its select instead of
the loop, so after the first stream failure it never looked the
partitions up again. Losing a partition leader silently dropped every
unacked message and stopped that partition for good.

Each partition now keeps its queue and the messages it sent but has not
had acked across streams. When a stream fails, or the broker answers
with an error or error code, the job ends, the scheduler looks the
topic up again with a short backoff, and the replacement stream resends
the unacked messages in order before draining the queue. Acks remove
messages up to the acked timestamp, so timestamps are made strictly
increasing per publisher. A partition holds at most 1024 queued or
unacked messages, and Publish blocks beyond that instead of growing
without bound. FinishPublish and Shutdown stop the input, Publish then
fails, and Shutdown returns once everything queued is acked.

* mq client: bound how long a closed publisher keeps resending

Once its input is closed, a publisher kept retrying a partition until
every message was acked, so Shutdown never returned while no broker
could take the partition, and a publisher that was only finished kept
looking the topic up forever. Resending now stops a minute after
FinishPublish or Shutdown, the open streams are cancelled, and Shutdown
reports how many messages were left unacknowledged.

* mq/kafka: replace a publish session whose call failed or was cancelled

PublishRecord ran Send and Recv in goroutines and returned when the
request context ended, leaving them on the stream. A leftover Recv then
took the ack meant for the next call on that partition, so acks and
offsets drifted apart, and a session whose stream had failed or whose
broker answered with an error stayed cached until the topic was
deleted. A call that fails, is cancelled, or gets an error response now
drops its session and cancels the stream, so the next call opens a
fresh one. PublishRecordValue shares the same path.

* mq/kafka: publish to the partition's current leader

The gateway opened every publish stream on the one broker it was
configured with, and a broker answers a publish for a partition it does
not lead with not-leader, so with more than one broker most partitions
could not be produced to, and none could after its leader moved. The
gateway now opens the stream on the leader named by the partition
lookup it already caches. A not-leader or connection failure drops the
session and the cached lookup and comes back as ErrNotLeaderOrFollower,
so the next attempt finds the new leader.

* mq/kafka: answer a produce that lost its partition leader with NOT_LEADER_OR_FOLLOWER

Every failed produce went back to the client as UNKNOWN_SERVER_ERROR,
which Kafka clients do not retry, so a partition leader change surfaced
as failed sends. A publish that failed because the leader moved or
could not be reached now answers NOT_LEADER_OR_FOLLOWER, and the client
refreshes its metadata and sends again.

* mq client: let the flush timeout cancel a stalled partition lookup

A lookup after a stream failure used context.Background, so a broker
that accepted LookupTopicBrokers and never answered kept the scheduler
inside it after the flush timeout, and Shutdown never returned. Lookups
now run under a context cancelled when the publisher stops, and each
broker attempt is bounded so a stalled one does not hold up the next.

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

* mq client: stop each test publisher and release held acks on cancel

A test that never shut its publisher down left the scheduler retrying
lookups against the stopped fake broker for the rest of the package run,
and a fake ack worker held on the gate could not exit when its stream
was cancelled.

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

* mq client: do not restart a partition whose stream finished during the switch

A re-lookup that moved a partition's leader cancelled its stream and
waited for it, then started a new one. If that stream had just finished
cleanly, the replacement ran for a job already counted as done, and the
scheduler could exit with it still running.

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

* mq client: count only data messages as unacknowledged at Shutdown

The count added the in-flight list and the queue length, so the close
marker FinishPublish queues counted as a lost message: an empty
publisher whose marker went unacked reported one unacknowledged message.
Every data message holds a slot until it is acked, so the slots are the
count.

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

* mq/kafka: let a produce's deadline bound opening its publish stream

Opening a session ran under the gateway's own context and waited for the
leader's hello, so a leader that took the init and never answered held
the produce, and every produce to that partition queued on the creation
lock, past their deadlines. Setup now also ends when the caller's
context does, without invalidating the assignment for a caller timeout,
and the stream outlives the call once open. A call whose context ended
while it waited for a dropped session no longer opens another one.

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

* mq/kafka: cancel the held publish only once the broker holds its data

The test cancelled on a 200 ms timer. A slow session setup let that
deadline pass before the data went out, leaving the first stream open
for the next call, which then waited on the held ack.

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

* mq/kafka: fetch and read offsets from the partition's leader

Produces go to the leader, but fetches and the high water mark and log
start offset reads still went to the gateway's own broker, which answers
partition not found for a partition it does not lead. Reads now use the
leader the assignment lookup returns, as the publish path does.

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

* mq agent: report unacknowledged messages when a publish session closes

ClosePublishSession returned success right after FinishPublish, which
only queues the close marker, so a message the brokers never acked was
lost without an error. The close now waits for Shutdown, which returns
once everything is acked or reports what was not after the flush
timeout, and no longer holds the session map lock while it waits.

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

* mq/kafka: look the leader up again after a read it cannot serve

Reads used the cached assignment until its TTL, so after a leader died or
gave the partition up, every fetch for the next 30 seconds went to it.
A connection failure or a partition-not-found answer from the leader now
drops the cached assignment, unless the caller's own context ended.

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

* mq client: leave a Publish still waiting to enqueue out of the Shutdown count

Publish takes a slot before it checks that the input is open, so a
Publish paused between the two still held its slot when Shutdown
counted, and Shutdown reported a message the caller was then told was
rejected. Each job now counts the data messages it accepted and has not
had acked.

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

* mq/kafka: cancel the silent-leader publish once its hello is withheld

The test cancelled on a 200 ms timer, which could fire before the call
opened a stream; the retry then opened the withheld stream with no
deadline and hung the suite. It now cancels once the fixture holds the
hello and bounds the retry.

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

* mq: retain the original publisher payload for replay

* mq agent: flush accepted records when the publish stream closes

* mq client: isolate bootstrap RPCs by publisher credentials

* mq/kafka: honor publish cancellation during lookup and partition waits

* mq/kafka: read a partition's offset range from its leader

GetHighWaterMark and GetEarliestOffset asked the gateway's configured
broker, which answers from its own log buffer. Publishes now go to the
partition's leader, so a non-leader gateway broker reported a high water
mark that missed the leader's unflushed records. Send the range query to
the leader and drop the cached assignment when that broker fails.

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

* mq agent client: bound the wait for the agent to finish a session

CloseSession waited in Recv until the agent answered EOF. An agent
blocked enqueueing to a partition whose broker stopped acknowledging
never reads the close, so it never starts its bounded flush and the
close hung. After two minutes, cancel the stream: the agent then stops
accepting and flushes, and the close reports the timeout.

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

* mq agent: wait for both closers to reach the flush in the close test

The duplicate-close test slept 100 ms to let the second close start. A
late goroutine then found the session already removed and the test
failed. Wait until both closers are inside finishPublisher instead.

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

* mq: answer a partition's offset range only from its leader

A broker answered GetPartitionRangeInfo from its offset manager even
after the partition moved away, so the gateway kept reading the old
leader's range until its assignment cache expired. The broker now checks
ownership the way FetchMessage does, and the gateway drops the cached
assignment when the range request fails.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:34:45 -08:00
github-actions[bot] 29eebd7bb2 docs: regenerate star history chart 2026-12-01 07:21:20 +00:00
Yip LeoandClaude Opus 5.5 e3e3bacf10 mount: read an open file's extended attributes under its entry lock (#13194)
* mount: read an open file's extended attributes under its entry lock

getxattr and listxattr on an open file read the Extended map of the
handle's live entry with no lock, while setxattr and removexattr change
that map in place. Go ends the process on a concurrent map read and
write, so weed mount exits with "fatal error: concurrent map read and
map write" (GetXAttr) or "concurrent map iteration and map write"
(ListXAttr), and every file open on the mount returns ENOTCONN. The
kernel asks for security.capability on each write(), so a program that
writes a file while another process sets or removes its attributes
reaches this.

The entry's own lock, LockedEntry.RWMutex, is the one every other
writer of the handle's entry takes: truncate to zero, the metadata
merges of a flush, SetEntry and the acknowledged-attribute retention.
setxattr and removexattr changed the map under the handle lock and
entryLock only. They now also take the entry lock, in the documented
order after those two, and re-read the handle's entry under it, as
SetAttr does, in case SetEntry swapped it. GetXAttr and ListXAttr read
the handle's current entry under the entry's read lock and copy what
they return before releasing it. The read lock is a leaf: it waits for
no other lock and does not wait for the handle lock, so a getxattr is
not held up by a write in progress.

TestXAttrReadsAgainstSetAndRemoveOnOpenFile and
TestXAttrReadsAgainstTruncateToZeroOnOpenFile abort the test binary with
the fatal errors above without the change, and all three race tests
report data races under -race.

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

* mount: remove the attributes the xattr race test sets

The writer of TestXAttrReadsAgainstSetAndRemoveOnOpenFile set even
keys and removed odd ones, so every RemoveXAttr found no key and
returned ENOATTR before deleting anything. Each name is now set and
then removed, and both calls must succeed. With RemoveXAttr's entry
lock taken out, -race reports its delete against GetXAttr's read.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:13:23 -08:00
Chris LuandClaude Opus 5.5 24951dbfe7 mq: one offset assigner per partition, continued from disk (#13191)
* mq: assign publish offsets inside the partition's log buffer

A publish took its offset from the offset manager under one lock and
appended it to the log buffer under another, so two publishers on one
partition could append offsets out of order. The buffer now assigns the
offset under its own lock when the entry asks for one, and an entry
that already carries an offset moves the buffer's next offset past it
instead of bumping it by one.

* mq: give the entry that rolls a window over to the new window

Both append paths widened the window's offset range before checking
for a rollover. The sealed window then claimed the entry that started
the next one, and the new window's range started without it, so a
window holding only that entry was flushed as offsets 0..0 and readers
skipped it. The range is now widened after the rollover.

* mq: seed a partition's offsets from all of its own files

A loading partition continued its offsets from the highest offset
recorded on disk, but the scan listed without a limit, so the filer
returned only its default page (1000 entries under weed server and
mini) and offsets below the real maximum were handed out again. It also
read the newest version directory rather than the partition's own, and
a filer error left the partition counting from 0.

The broker and the Kafka gateway now share mq.ReadOffsetRange, which
lists every file, the broker reads the partition's own directory, and
a partition whose stored offsets cannot be read is not loaded, so the
publish fails and is retried.

* mq: reload a partition only after its retired copy has flushed

Idle cleanup and a drain retire a partition and return while its last
flush is still queued. A publish right behind them created a new copy,
which read the stored offsets before that flush landed and handed out
its offsets again. Loading a partition now waits for a retired copy of
the same range, outside the broker's access lock that the flush takes.

* mq broker: report a partition's high water mark from its buffer

The range reported to the Kafka gateway took the larger of the offset
manager's count and the buffer's, so it followed the manager's
checkpoint rather than what the partition had assigned. It now comes
from the loaded partition's buffer, which assigns the offsets, or from
the ranges stored on disk when this broker has not loaded the partition.

* mq: drop the offset manager's assignment, checkpoint and subscription code

Publish offsets now come from each partition's log buffer and its high
water mark from that buffer or the stored ranges, so the separate
assigner, its checkpoint.offset writer and the offset subscription
layer built on it have no callers left. Only consumer-group positions
remain in BrokerOffsetManager. Existing checkpoint.offset files are left
alone; readers already skip them.

* mq broker: recheck a retiring partition under the lock when assigning

AssignTopicPartitions waited for a retiring copy before taking the
access lock, so a drain in between could retire the partition and the
assignment then seeded a replacement before that flush landed. The
check now runs under the lock, which is released only to wait.

* mq topic: mark a partition retiring before it leaves the list

RemoveLocalPartition took the partition out of the active list before
recording it as retiring, so a replacement loaded in between saw
neither and read the stored offsets before the last flush landed. The
partition is now recorded as retiring first.

* mq topic: gate the retired-flush test on a channel instead of a sleep

The test relied on a 200ms flush delay to observe the partition as
pending, which a paused test goroutine could outlast.

* mq topic: remove a partition by its instance under one lock

RemoveLocalPartition looked the partition up, marked it retiring and then
removed by range in separate steps. A second remover of the same copy could
take out a replacement loaded in between, leaving it neither listed nor
retiring, and a removal that found nothing still left a stale retiring entry.
Callers now pass the copy they hold; it is marked retiring and taken out of
the list under the partition lock, and only if it is still listed.

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

* mq broker: look a partition up once per assignment pass

The retirement wait checked one lookup and the load used a second one, so
idle cleanup retiring the partition between them let the assignment load a
replacement from stored offsets before the retired copy's last flush landed.
The wait and the load now use the same lookup.

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

* mq broker: let a cancelled assignment leave the retirement wait

AssignTopicPartitions waited for a retired copy's last flush without watching
its request, so while that flush kept failing a cancelled call still held its
handler. WaitRetired now takes a context and returns its error, leaving the
retirement pending; the publish and subscribe loader keeps waiting as before.

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

* mq topic: share one flush signal per retirement

A cancelled WaitRetired left its goroutine blocked on the retired
buffer's flush, so repeated cancelled assignments piled up goroutines
until that flush finished. The retirement now owns one channel, closed
after its last flush, and every waiter selects on it.

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

* mq broker: load the assigned generation for any request of its range

Subscribe and fetch pass the partition from the request, and the loader
built the local partition from it after matching only the range. A stale
or zero generation then scanned a directory the broker was not assigned,
found no offsets, and registered a partition that restarted at zero over
stored data. The loader now takes the assignment's partition.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:29:27 -08:00
Yip LeoandClaude Opus 5.5 de76148f54 mount: fail the flush when dirty pages cannot be read back from the swap file (#13198)
* mount: fail the flush when dirty pages cannot be read back from the swap file

Dirty pages that weed mount buffers in the swap file (non-sequential
writes, or when the memory chunks run out) are read back when they
upload. SwapFileChunk.SaveContent ignored the error of that read: an
interval it could not read in full was uploaded short, or not at all,
and flush, fsync and close still succeeded. The writes the application
had been told succeeded became a hole in the stored file, with no error
anywhere. A read error on the cache disk, or a swap file truncated by an
outside cleanup, is enough.

SaveContent now hands the upload a reader that fails with the read
error. The upload fails like any other failed chunk upload: the handle
records it, rejects further writes, and flush, fsync and close return
EIO without publishing the entry. The remaining intervals of that chunk
are not saved, since the handle cannot flush cleanly. The chunk, its
write budget and its swap slot are released as before.

The test in weed/mount cuts the swap file after the write was
acknowledged: on master fsync returns OK and the filer is never told.
The pipeline tests cover a closed and a truncated swap file, and a swap
file cut inside the second of two intervals.

SwapFileChunk.ReadDataAt, which serves reads of pages not yet uploaded,
still logs a read error and returns what it has read so far; that is
left for a follow-up since it needs an error path through the read side.

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

* mount: require a failed fsync to leave the filer entry unchanged

TestFsyncFailsWhenSwapFileCannotBeReadBack accepted any filer entry
backed by stored bytes that left out the lost range, so an entry
published with the readable interval (the original 256 bytes plus the
"A" write) would also have passed. It now records the filer's entry
before the writes and requires the same entry and the same 256 bytes
after the failed fsync.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:55:31 -08:00
Yip LeoandClaude Opus 5.5 265b3aae0f mount: take the two handle locks of CopyFileRange in one order (#13197)
CopyFileRange locked the destination handle exclusively and then the
source handle shared. Two copy_file_range calls in opposite directions
between the same pair of files (A to B and B to A, which coreutils cp
issues by default) each held their destination and waited for their
source, and neither could go on. Every operation that needs either
handle's lock then waits behind them: reads, writes, flush, release,
and the invalidation of the handle by a metadata event. The processes
using the two files hang until the mount is restarted.

The two locks are now taken in ascending FileHandleId order, whichever
of the two handles is the destination; the destination is still locked
exclusive and the source shared. A copy whose source and destination are
the same handle takes the one lock exclusive, as before. CopyFileRange
is the only place that holds the fhLockTable locks of two handles at
once, which the nested lock order comment in filehandle.go now says.

The test queues the first copy behind a handle lock held by the test and
starts the opposite copy while it waits; the lock order is the only
thing that lets both finish. It fails on master with both copies parked
in the lock queue.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:54:37 -08:00
Chris LuandClaude Opus 5.5 9cea13b9fc mq broker: fenced flushes, one file per window (#13192)
* mq: number partition leaderships with an epoch

A partition assignment named its leader but nothing told one leadership
from the next, so a broker that lost a partition could not be told apart
from the one that replaced it. BrokerPartitionAssignment now carries an
epoch that the balancer bumps whenever it picks a different leader,
including the first leader of a new partition, so a fresh allocation starts
at epoch 1. Follower changes and re-spelled addresses of the same leader
keep the epoch.

* mq broker: take a partition fence before leading a partition

Nothing stopped a broker that had lost a partition from writing to it, so
two brokers flushing one partition overwrote each other's files. Each
partition directory now holds a .fence entry naming its writer and the
assignment epoch. A broker generating a partition as leader reads the fence
and rewrites it with one filer ObjectTransaction, routed to the fence's
owner filer and conditioned on the fence being absent or unchanged since
the read, before it reads the partition's existing offsets. A fence stored
at a higher epoch or sealed is refused, and the partition is not served
when the fence cannot be taken. The broker keeps the fence entry as stored
so later writes can present it. Topic configuration now passes each
assignment's epoch to the broker it assigns.

* mq broker: flush each window to its own fenced file

A flush uploaded a chunk on every attempt and appended it to the chunk list
of the file named by the window's start second with an unconditional
CreateEntry. A lost response duplicated the window, every retry orphaned
the previous chunk, and two brokers writing one partition overwrote each
other's chunk lists. Each window now becomes a new file named by its start
second and its first offset, uploaded once and written with one filer
ObjectTransaction conditioned on the partition fence the broker holds. Only
the transaction is retried, under a single request id, so a replay cannot
apply twice. buffer_start now records the window's first offset instead of
the next-offset counter. A failed fence condition means another broker
took the partition: the window is dropped, later windows drop without an
upload, and the publish path answers not-leader so publishers move on.

The follower's stream-end write of its leftover windows now goes through
the same fenced writer, which refuses it because a follower holds no
fence. That write only ever produced offset-less duplicates of what the
leader flushed, so the follower now drops those windows.

* mq: read flushed windows named with an offset suffix

Flushed windows are now named by start second and first offset, which the
readers did not expect. The disk reader dropped every file whose name
sorted after the stop second, which a window starting in that very second
now does, and log compaction parsed the whole name as a time and skipped
the new files. Both now look only at the start-second part, so files with
either naming are read. The partition fence that sorts first in a listing
is skipped by the disk reader and the query engine's live-log scans, and
topic truncation keeps it.

* mq broker: retry a recorded flush failure under a new request id

The filer records a failed mutation under its request id and replays it for
two minutes, so retrying the same id stalled the partition's flush. Putting
the same window entry again is harmless, so a recorded failure now retries
under a fresh id; a lost response still retries under the same one.

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

* mq broker: hold the partition fence by a token, not a read-back entry

Taking the fence read the written entry back through the broker's filer,
which may lag the fence's owner filer; a successful take then looked lost
and the new leader did not load. The fence entry now carries a fresh token
as its etag, and later writes require that etag on the owner, so nothing
is read back.

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

* mq broker: bound the fence take's filer calls

A partition is loaded under accessLock, and the fence take's lookups and
transaction had no deadline, so a filer that accepted a call and never
answered held every partition operation on the broker. A take that runs
out of time leaves the partition unserved for a later attempt.

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

* mq: name compacted files and skip compacted windows by their source logs

Now that several windows can start in one second, compaction named
every output after its first message's second, so groups starting in
the same second overwrote each other, and it skipped any window whose
start second was not after the newest compacted row, so a later window
in that second was never compacted. A parquet file is now named after
its first source log, which is unique, and a window is skipped when a
parquet file lists it as a source; the start-second rule remains only
for windows named by their second alone.

* mq broker: reload a partition whose fence another broker took

A partition that lost its fence stayed registered until its last
client left, and both partition load paths reused it, so a broker made
leader again at a newer epoch kept answering not-leader, or wrote
until its next flush was refused. A fenced partition is now dropped
and the partition loaded again under the current assignment's epoch.

* mq broker: reload a partition held under an older epoch

A copy whose fence was taken is reloaded only once a refused flush marks
it lost. Until then a broker made leader again at a newer epoch kept the
copy and accepted publishes that the next flush dropped against the other
broker's fence. A copy whose fence epoch is older than the assignment's is
now reloaded too. Its last flush lands under its own fence before the
reload reads the stored offsets.

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

* mq: start a new compaction group only after the current one has a file

A first log file larger than the group size left an empty first group, and
naming a parquet file after its group's first log then indexed past the end.

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

* mq: remove a partition by its instance, not its range

A publisher or subscriber of a copy that was replaced removed the partition
by range on its way out, which shut down the replacement instead. Removal
now takes the copy itself and leaves a copy that has replaced it.

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

* mq broker: keep a stale copy registered until its last flush lands

A reload removed the stale copy and then waited for its last flush without
accessLock. A concurrent lookup or assignment found no copy, took the new
fence first, and the pending flush was refused and its window dropped. The
copy is now shut down where it is registered, so every loader finds it and
waits for the same flush, and it is removed only afterwards.

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

* mq broker: refuse an assignment once a reload waited out a shutdown start

The stopping check ran before the stale-copy reload, which releases
accessLock while the copy flushes. A Shutdown starting then left the retired
copy in place and the assignment reported success for it.

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

* mq broker: bound the concurrent reload test's waits

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

* mq: describe fenced writes and the follower loss window in the failover notes

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

* mq broker: release the upload gate when the reload test times out

A first upload starting just after the deadline check stayed blocked on the
gate, so the test server's Close waited on it and cleanup hung.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:52:47 -08:00
Chris LuandClaude Opus 5.5 d4910b70cf s3api: classify the GetPart part key in the route-key test (#13193)
s3api: classify the GetPart part key as an uploadId modifier

The GetPart route added a `part` query key that TestRouteQueryKeysAreClassified
did not know, failing the s3api tests on master. `part` only narrows an
uploadId request from ListParts to GetPart, like partNumber does for
UploadPart, so it must not count toward the ambiguity guard: counting it
would reject every `?part&uploadId` request.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:47:33 -08:00
Chris LuandClaude Opus 5.5 139c1d6d04 mq broker: survive startup, non-balancer brokers, and restarts (#13181)
* mq broker: turn a panic in an RPC into an error

The broker's gRPC servers had no recovery, so a nil dereference in any
handler took the whole process down. Once the broker runs inside
another server, that process is the host.

* mq broker: guard the filer set

The master's peer updates and the startup peer listing both write the
filers map and currentFiler from different goroutines, and every filer
call reads currentFiler. Two writers on the map at startup is a fatal
concurrent map write.

* mq broker: answer balancer requests before the balancer lock exists

The balancer lock is created only once the broker has found a filer,
while the gRPC server already serves. Every lookup, configure, publish
and balance request dereferenced it, so an early request crashed the
broker. Those requests now answer Unavailable until a balancer is
elected.

Ownership is the lock's unexpired lease instead of the owner name it
last saw, so a broker whose renewals have failed stops acting as
balancer once the lease runs out. A lapsed lease can still name this
broker, so proxying refuses to send a request to itself.

* mq broker: follow the filer lock ring

The balancer lock client was seeded with the first filer the broker
found and never given the ring, so it kept dialing that filer after it
left and no broker could become balancer. The broker now takes the
master's lock ring updates the way S3 gateways and mounts do, and the
master sends brokers the ring snapshot on connect.

* mq: never pick a partition's leader as its follower

pickBrokersExcluded ignored the leader it was told to exclude. With one
broker, the first assignment repair made that broker its own follower,
and it then replicated every publish to itself.

A dead follower that has no replacement is now dropped and counted as a
change, so the cleared name is saved; picking the leader had hidden
that.

* mq: keep a partition's leader unless a live broker replaces it

The repair cleared the leader of any partition whose leader it did not
see, even with no broker to take over, and the cleared assignment was
cached. With an empty broker set every leader went blank. A leader now
moves only to a live broker, the only live follower is promoted when it
is all that is left, and a follower that names its own leader is
replaced.

* mq broker: only a settled balancer repairs assignments

Every broker repaired topic assignments on a cache miss, but only the
balancer tracks which brokers are live. Any other broker saw an empty
set, cleared the topic's leaders, and could not load a partition it
did own, so a publish to it dereferenced a nil partition.

A newly elected balancer also waits 30 seconds, long enough for every
broker to notice the change and reconnect, before it treats a broker
it has not heard from as gone.

* mq broker: refuse a publish for a partition not assigned here

When the balancer named this broker as leader but its own copy of the
topic config did not, the partition lookup returned nil and the
publish dereferenced it. It now answers not-leader, and the publisher
looks the partition up again.

* mq broker: compare the publish leader as an address

The leader check built "ip:port" with Sprintf and compared strings,
while broker addresses are joined with JoinHostPort. On IPv6 the
brackets never matched and every publish was refused as not-leader.

* mq broker: flush partitions on stop

The broker had no Stop. Its loops ran on context.Background, and the
standalone command registered nothing for SIGTERM, so every restart
dropped the publishes still in the open flush window.

Stop now cancels the broker's loops, releases the balancer lock, and
waits until every partition has flushed. The command calls it on
interrupt before stopping its gRPC servers. The startup peer listing,
which blocked the constructor until a master answered, now runs in the
background with the balancer election.

* mq topic: flush partitions added or retired while stopping

Shutdown took one snapshot of the partition list, so a partition a
publish created after the snapshot was never flushed, and one that idle
cleanup had just retired was not waited on. Adding a partition now
fails once Shutdown starts, Shutdown waits out an idle cleanup pass in
progress, and every retired partition is waited on until its last
flush.

* mq broker: release the balancer lock once on stop

Stop and the balancer election could both release the lock when a stop
landed just as the lock was published, and a second LiveLock.Stop
closes its channel again and panics. Each path now takes the lock out
with Swap, so only one releases it.

* mq broker: forget the buffered ring version on a master change

Before the balancer lock client exists, the broker keeps the last ring
it got. A master change then reset nothing, so the client attached with
the old master's version and refused the new master's lower one.

* mq broker: restart the settle window when the balancer lease is regained

The window started when the lock owner's name changed. A balancer that
lost a renewal and got the lease back still had the same name, so it
skipped the wait and could repair assignments before brokers
reconnected. The window now counts from the first sight of the lease's
generation, which changes on every fresh acquisition and stays put on
renewal.

* mq broker: expire configs cached while the balancer settles

A balancer reading a topic during its settle window skipped the repair
and then cached the config for the full 30 seconds, so a dead leader
was served well past the window. Those entries now expire at the
settle deadline.

* mq topic: wait for drained partitions on shutdown

A partition removed by a drain or by its last client leaving was shut
down but not tracked, so a stop right after a resize could exit before
its final flush. Every removal now retires the partition through the
manager, and Shutdown waits on the set of retiring partitions instead
of a WaitGroup that a late removal could Add to while Wait ran.

* mq broker: update the settle window's lease and start together

The lease generation and its start were two atomics written one after
the other, so a concurrent reader could pair a regained lease's new
generation with the old start and see the window as already over. They
are now read and written under one lock.

* mq broker: refuse an assignment while stopping

A partition assigned after shutdown started was shut down, but the
handler still answered success, so the balancer recorded an assignment
this broker never installed. It now answers Unavailable.

* mq topic: signal a subscriber to stop only once

Shutdown leaves partitions registered, so a drain that arrives while the
broker flushes shuts the same partition down again, and closing a still
registered subscriber's stop channel a second time panicked.

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

* mq broker: bound flush retries once stopping

Stop waits for every partition's last flush, and a flush retried a failing
write forever, so a broker whose filer or volumes were unreachable never
exited on SIGTERM. In weed server it also held back the filer and volume
shutdown hooks, which run after it. Like the filer's metadata log, a flush
now gives up 15s into Stop and drops the window instead.

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

* mq.broker: flush before closing the localhost listener too

The localhost server's stop hook was registered after the broker's, so it
ran first and cut loopback clients before the partitions flushed.

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

* mq topic: gofmt local_manager.go

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

* mq broker: end a shutdown flush stalled in a filer call

The shutdown budget was checked only after a failed append returned, and
the entry lookup and update ran under context.Background(), so a filer
that accepted the call and never answered still held Stop open. Flushes
now append under a context that Stop cancels once the budget runs out,
as the filer does for its metadata log. Every window after a dropped one
then drops too, so a later success cannot advance the watermark or tell
the follower to discard a window that never reached the filer.

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

* mq topic: leave a partition to Shutdown once it starts

RemoveLocalPartition detached a partition before registering it as
retiring, so a Shutdown snapshot taken in between missed it and returned
before its last flush. Once Shutdown starts, removal now reports false and
the partition stays registered for Shutdown to retire, as idle cleanup
already does.

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

* mq broker: refuse an assignment for a hosted partition while stopping

Only a new partition was refused once Shutdown started. A partition the
broker already hosted stays registered after Shutdown retires it, so its
assignment was acknowledged although the broker no longer serves it. Both
paths now answer Unavailable.

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

* mq broker: expire a settling balancer's config from when it was validated

The expiry was computed when the config was cached. A lookup that skipped
validation just before the settle deadline and cached the config just after
it kept the unrepaired assignments for the full TTL. The expiry now counts
from the time of validation, so such a config expires at the deadline.

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

* mq broker: stop waiting on an upload once the flush budget ends

Cancelling the flush context ended retries and the filer metadata calls,
but not a volume assignment or upload already in flight. Those ran on
their own timeouts and retries, so a filer or volume server that never
answered held Stop past the budget, for minutes in the worst case. The
upload now runs on its own copy of the window, and the flush stops
waiting for it when the context ends.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:21:23 -08:00
394e9d247e mount: keep assignment proofs until the filer stores their chunks (#13186)
* operation: return the assignment proof of an upload

A filer serving a scoped token returns an assignment proof with
AssignVolume and stores a new chunk in an entry only when the request
presents that proof in chunk_auth. UploadWithRetry dropped it, so a
client had no way to commit the chunks it uploaded.

UploadResult.AssignAuth now carries the proof of the assignment the data
was finally stored under. A proof from an assignment the upload abandoned
after a failed attempt is never returned. The field is not serialized and
stays empty when the filer sends none, so existing callers are unchanged.

* mount: keep assignment proofs until the filer stores their chunks

A mount with a scoped filer token was refused whenever it wrote new
chunks: the filer asks for the assignment proof of every chunk the stored
entry does not hold, and the mount never kept it.

The mount now keeps the proof of every chunk it uploads and attaches the
proofs of the chunks a request names to each create, update and append
it sends, over the mutation stream and over unary calls, on every
attempt. A proof is released only once a filer acknowledged an entry that
names the chunk, or a manifest that holds it. A failed, refused or timed
out commit releases nothing, since it may have been stored: the retry
still carries the proof, and a filer ignores proofs for chunks it holds.
Proofs are stateless, so a commit retried on another filer of the cluster
is accepted there.

The store is bounded. When it is full an upload waits for commits to make
room before it is assigned a file id, and fails after a minute instead of
evicting a proof a pending commit still needs. Only proofs well past their
expiry, which a filer refuses anyway, are dropped to make room.

Without a filer token the mount keeps no store: its requests and chunk
lists are as before. A token without path grants is given no proofs, so
nothing is attached either.

* mount: keep chunk lists flat with a filer token file

A filer serving a scoped token stores no new chunk in an entry that holds
manifests, so once a mount folded a file's small chunks into a manifest,
every later write to that file was refused. A mount with a filer token now
keeps chunk lists flat; mounts without one fold as before.

* mount: test the unscoped-token path with a signed token

GenJwtForFilerScope returns an empty token when it is given no path
grants, so both cases of TestUnscopedMountRequestsCarryNoProofs ran a
tokenless mount. Sign an unscoped filer token instead and check that it
is not empty, so the test covers a mount holding a token the filer issues
no proofs for.

* mount: fold chunk lists unless the filer scopes the mount's token

A mount with -filer.tokenFile kept every chunk list flat, also when the
token is an unscoped one the filer issues no proofs for. Such a mount
stopped folding chunks into manifests, so its small-chunk runs were never
folded and, on FoundationDB, a file past about 1000 chunks no longer fit
its entry. Keep lists flat only while the current token has path grants
or a method list, which the filer scopes; fold as before otherwise.

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-30 18:18:29 -08:00
aeca7a9a8a master: keep writes available when the replica placement cannot be satisfied (#13178)
* master: keep writes available when the replica placement cannot be satisfied

With a placement such as 200 on exactly three data centers, losing one data
center stops all writes: every volume misses a copy and leaves the writable
list, and volume growth cannot find three data centers.

Add master.replication.degraded_growth_min_copies (0 = off). When the
topology no longer has enough data centers, racks or servers for a placement,
the master grows volumes with fewer copies, never below that number. A lack
of free space never triggers it.

These volumes keep the requested placement in their super block and are
writable while the master flags them as degraded; lookups report the copies
they need, so volume servers accept writes to them. Once the topology can
hold the placement again the flag is cleared: they turn read-only until
volume.fix.replication adds the missing copies. The flag is in memory only,
so a master restart has the same safe effect.

Refs #13177

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

* master: tighten degraded volume growth after review

- A degraded volume is writable only with exactly the copies it was grown
  with: losing one turns it read-only, so a copy that comes back has missed
  no write, and it is not writable before all its copies are registered.
- Use the first relaxed placement the topology can hold and stop there when
  it lacks free slots, so full disks never drop more copies.
- Try every relaxed placement, ordered by copies, then data centers, then
  racks (011 can fall back to 010, not only 001).
- Data nodes in maintenance mode do not count when checking the topology.

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

* master: tie degraded writability to the original servers

- A degraded volume is writable only on exactly the servers it was grown
  on: a replacement copy no longer stands in for a missing original one.
- Lookups report the degraded copy count only in that exact state, so a
  volume server never relaxes its check when the layout would not.
- When a relaxed placement fails to find slots, try the other placements
  with as many copies (for example in the requested data center) before
  giving up, still never dropping copies for lack of space.

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

* seaweed-volume: copy min_writable_copies into the master.proto copy

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

* seaweed-volume: let a degraded volume replicate with the master's min_writable_copies

Mirrors getRemoteReplications: lookup_volume also returns the lookup's
min_writable_copies, and do_replicated_request uses it instead of the
placement's copy count when it is lower.

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

* seaweed-volume: test the degraded replicated write through the admin router

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

* master: grow degraded volumes without a setting

Degraded growth no longer needs master.replication.degraded_growth_min_copies:
it always applies when the topology cannot hold a placement, never below two
copies. Lookups skip the degraded scan until a volume was grown degraded.

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

* master: leave refused servers out of the degraded slot search

findDegradedSlots cleared option.refused, so a retry could pick the server
that just refused the allocation. Search without the refused servers first
and fall back to them only when nothing else fits, as findAndGrow does.

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

* master: document that a degraded volume losing every copy stays read-only

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

* admin: warn about under-replicated and misplaced volumes on the dashboard

The dashboard health line now counts the volumes volume.fix.replication would
repair, using the same placement checks, so volumes grown degraded while a
data center is down show up until they are repaired.

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

* master: spread degraded copies over racks and servers when data centers are missing

A 200 volume with a single data center left found no degraded placement:
only per-dimension reductions were tried, and 100 needs two data centers.
Try every placement with fewer copies and no more data centers, so the
remaining copies go to other racks or servers.

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

* master: report min_writable_copies only for the locations it is returned with

LookupVolume read the locations and the degraded minimum in two steps, so
a replica set change in between could pair the minimum with locations it
does not hold for. Count the minimum only when the returned locations are
exactly the servers the volume was grown on.

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-30 16:05:54 -08:00
Chris LuandClaude Opus 5.5 5815d13881 mount: keep in-place updates at a listed entry's commit stamp (follow-up to #13152) (#13189)
* mount: keep an entry whose in-place update is already reflected

A listed entry carries its own commit stamp, so the update event that made
it arrives at exactly that stamp. The removal half passed the strict check
while the write half was fenced, and the entry was deleted and tombstoned.
An in-place update is one change: when its write is fenced, so is the
removal of the same path.

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

* mount: report a cached entry's own commit as its version

FindEntry still versioned a listed entry at the listing floor, below the
commit it carries. An open handle compares invalidations against that
version, so a delayed event the cache fenced out could still replace the
handle's content with the older state.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:05:41 -08:00
Chris Lu 501cf6b760 mq: read a recorded offset range that ends at offset 0 (#13190)
The broker and the Kafka gateway each scanned a partition's files for
the high water mark and counted a maximum only when it was above 0, so
a partition holding one message still read as empty. Both now share
mq.OffsetRange, which tracks whether a range was found apart from its
value.
2026-11-30 16:01:39 -08:00
4830ae5e96 feat: set GOMEMLIMIT from cgroup memory limit via automemlimit (#13188)
* feat: set GOMEMLIMIT from cgroup memory limit via automemlimit

* weed: set the memory limit before dispatch and report it through glog

The blank import ran memlimit.Set in an init with slog.Default, so every
weed command, including weed version and weed shell, wrote to stderr
outside glog, and macOS and Windows printed "failed to set GOMEMLIMIT:
cgroups is not supported" each time. Call memlimit.Set before running the
command instead, and log the resulting limit or a bad AUTOMEMLIMIT value
next to the transparent huge page line of long-running commands.

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

* mount: log the -memoryLimitMB override and document the automatic limit

weed mount now starts with 90% of the cgroup memory limit unless GOMEMLIMIT
is set, so -memoryLimitMB=0 no longer means unlimited inside a container.
Say so in the flag help and log the override, which replaces the limit the
startup line reported.

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

---------

Co-authored-by: Rajesh Kannapalli <rajesh.kannapalli@broadcom.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:45:12 -08:00
Song Bian 54f0c7ca5b fix(filer): clip chunk group reads at EOF (#13182) 2026-11-30 15:43:10 -08:00
Song Bian 81b83b155f fix(mq): copy flush buffers before queuing follower data (#13183)
* fix(mq): copy flush buffers before queuing follower data

* fix(buffered_queue): release references after dequeue
2026-11-30 15:33:06 -08:00
df2fa630c1 mount: fence events below a cached entry's own commit stamp (#13152)
A listing snapshot capped at the peers' delivery watermark can trail
entries already in the store. A delayed event older than the listed
version then rolled the entry back, e.g. a completed file to its empty
create, until the newer event arrived. A live entry now counts as
versioned at least at its CommitTsNs.

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:28:08 -08:00
0d09c87281 fix(master): handle capacity changes during volume placement (#13185)
* fix(master): handle capacity changes during volume placement

* topology: test capacity changes during placement deterministically

The maintenance-toggling loops ran for seconds and could pass without
reaching either guard. Drain the secondary rack or data center right
before its slot draw, and feed PickNodesByWeight a node whose reported
capacity changes between reads. Each case fails on the code before the
fix.

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-30 15:27:12 -08:00
d807dbfcbc fix(s3): preserve logical part layouts on multipart completion (#13184)
* fix(s3): preserve logical part layouts on multipart completion

* s3api: accept a multipart part that is entirely a hole

UploadPartCopy of a range that overlaps no source chunk stores a part
with no chunks but a non-zero size. Completion rejected any chunkless
non-last part as empty, so the upload failed with InvalidPart even
though the part copy succeeded. Reject only parts whose logical size is
zero; the all-hole part now completes as zeros at its position.

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

* s3api: refuse a multipart completion made only of holes

When every completed part is a hole, the object gets a positive size
and no chunks, and GET answers it with InternalError as a data
integrity failure. Reject that completion with InvalidPart instead of
committing an object that cannot be read. Uploads that mix hole-only
parts with data parts still complete.

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-30 15:14:20 -08:00
Chris LuandClaude Opus 5.5 480a1baa20 s3api: GetPart, reading parts of in-progress and completed multipart uploads (#13174)
* s3api: GetPart reads one part of a multipart upload

GET /key?part&partNumber=N&uploadId=X serves the latest attempt of an
open upload's part, or the bytes that part became in the object a
completed upload assembled, including a version that is no longer
latest. x-amz-multipart-upload-status says which. A Range counts
within the part, and a whole part answers 200 even though a completed
part is served as a range of the object.

The route sits ahead of ListParts and claims any ?part request, so a
missing partNumber is InvalidArgument rather than a listing, and the
request resolves to s3:GetObject, not the ListParts grant.

* s3api: reading an open upload's part needs s3:GetIncompleteUpload

AWS gates GetPart on an upload that has not completed behind
s3:GetIncompleteUpload on top of s3:GetObject, so a plain read grant
does not start exposing data its writer has not committed yet. The
action is its own legacy grant too; Read alone does not carry it, Admin
does. A completed upload's part needs only the read grant, plus
s3:GetObjectVersion when it lives in a version.

* s3api: a GetPart request carrying ?uploads is not a multipart listing

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

* s3api: GetPart answers a completed empty part with an empty 200

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:09:19 -08:00
Song BianandMaster ac2efbac01 fix(buffered_queue): synchronize enqueue with input closure (#13168)
Check isClosed while holding the queue mutex so the check and insertion are atomic with respect to CloseInput. This prevents a producer from successfully enqueueing after a consumer has exited a closed, empty queue.

Add concurrent enqueue, close, and drain coverage with a bounded wait, plus checks for both sequential close orderings. The concurrent regression reproduces the original data race and stranded item under the race detector.

Co-authored-by: Master <Master@node0.8m510.lpad-pg0.utah.cloudlab.us>
2026-11-30 13:48:52 -08:00
Chris Lu 10381075f3 mq: record the offset range of a partition's first window (#13180)
The flush wrote offset_min/offset_max only when minOffset > 0, using 0
as "no range given". A partition's first window starts at offset 0, so
its file never got a range. A restarted broker derives the high water
mark from those ranges, so a partition whose data was all in its first
file read as empty.
2026-11-30 13:39:52 -08:00
Chris Lu 51d591e060 cluster: read a LiveLock's owner atomically (#13179)
The renewal goroutine rewrites the owner on every attempt while other
goroutines read it through LockOwner. The MQ broker reads it on every
request it proxies to the balancer.
2026-11-30 13:38:41 -08:00
Tiago PosseandClaude Opus 5.5 0964dd7713 filer: put a finished download on the budget's idle list before waking readers (#13147)
A download closed done and then moved its reservation to the budget's
idle list, so a reader woken by done could ask the budget for room
before the chunk it had just read was evictable.
TestReaderCacheBudgetLendsScratchToHedges failed this way about 1 in
1000 runs under -race ("hedge buffers did not evict the idle chunks").
The download now completes in the budget first.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:30:56 -08:00
Tiago PosseandClaude Opus 5.5 411e9a8542 filer: keep a copy of the entry in the path-specific test store (#13146)
The stub store kept the caller's entry, which the path translator changes
back after the insert, so TestNameInAPathSpecificStoreCreatedTwiceIsCountedOnce
raced with a lookup under -race.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:29:50 -08:00
68072eff8a webdav: set mtime when a file is created (#13144)
* webdav: set mtime when a file is created

OpenFile created the entry with Mtime 0 and only Close after a Write set
the real time, so an empty PUT, or one truncating a file to empty, left
it at 1970. The "new entry" marker for a failed first upload is now a
field on the file.

* webdav: keep a failed upload from removing another writer's version

With every new entry carrying an mtime, a failed first upload removed
whatever the path held at the first Write, including a version another
writer stored after this open created it. The open now records the
commit stamp of the entry it created, and the first Write keeps the
removal only when the loaded entry still has that stamp.

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

* webdav: check the entry's commit stamp when the upload fails

The first Write's lookup left a gap: a version another writer stored
after it was still removed by a later failed flush. Flushes only append
chunks locally, so the stored entry keeps the create's stamp until
Close; the failed flush now reads it then and removes it only while it
still has that stamp.

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-30 13:27:33 -08:00
guagucai 53206f16be fix: reject NaN minimum free-space percentages (#13153)
Signed-off-by: guagucai <guagucai@outlook.com>
2026-11-30 13:25:40 -08:00
Song Bian 0025e7177f fix(filer): preserve chunk ordering on 32-bit systems (#13175) 2026-11-30 13:24:21 -08:00
1a2be918bf s3api: reset the circuit breaker when its config is deleted (#13148)
* s3api: reset the circuit breaker when its config is deleted

The delete handler parsed an empty file, which always fails, so the old
limits stayed in place. It now loads an empty config.

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

* s3api: read and swap the circuit breaker limits under its lock

A config change or delete replaced Enabled and the limitations map while
requests read them without a lock. The swap now holds the breaker's
write lock, and requests read both under the read lock that
loadCounterAndCompare already took for the counters.

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-30 13:14:34 -08:00
Chris LuandClaude Opus 5.5 c637d60dfc filer.sync: keep an informational replay cursor on the source, and let the log purge honor it (#13176)
* filer.sync: save the sync position on the source filer as a replay cursor

The position stays authoritative on the target. The source copy holds the
last position the target checkpoint stored (a fresh sync without one holds
just before the first event it received) and is rewritten hourly while the
sync runs, even when the position does not move.

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

* filer.sync: do not replicate the sync cursors of the source

A target never holds cursors that describe the source's log. A rename into
or out of the cursor directory replicates the ordinary side.

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

* metadata log purge: keep the logs a filer.sync still needs

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

* filer.sync: describe the sync in its source cursor

The source cursor is informational: besides the position it records the
source and target filers and paths, exclusions, host, version, when the
sync started, whether the position is a target checkpoint, and the
processed and failed event times, for display in admin tools. The
target checkpoint stays authoritative.

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

* filer.sync: save the first sync cursor when the first event arrives and retry failed saves

A fresh sync only saved its cursor on the next minute tick, and a failed
save still pushed the next attempt out by an hour, leaving the purge
without a cursor while the sync replayed old log days.

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

* filer.backup: do not seed the source's sync cursors in the initial snapshot

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

* metadata log purge: say that a position not saved for 7 days stops holding the log

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

* filer.backup test: lock the recording sink for concurrent snapshot workers

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

* filer.sync: leave the sync cursors out of the metadata log gap check

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:09:23 -08:00
bcd678271e mount: authorize filer calls with a pre-issued token file (#13118)
* security: filer token source read from a file

FilerTokenFile is the token source of a client that holds a pre-issued
filer token rather than a signing key. It reads the file on every call,
so an atomic replacement that keeps size and mtime takes effect on the
next attempt, and trims surrounding whitespace. A missing, unreadable,
empty or malformed file fails the call: there is no fallback to anonymous
or admin authority, and errors name the path but not the contents.

FilerTokenClaims decodes a token's claims without a key, and
FilerTokenGrantCovers compares two grants, so a client can plan
reconnects before expiry and know when a replacement narrows what it
may see.

* mount: -filer.tokenFile authorizes filer calls with a pre-issued token

A mount that should not hold a filer signing key can now present a
token issued for it. -filer.tokenFile (or -o filer.tokenFile=) names the
file; it is read for every filer gRPC attempt, so a replaced file takes
effect on the next call or retry without a restart, and a missing or
empty file fails the call locally.

The source reaches every filer client the mount builds: the startup
handshake, each attempt of WithFilerClient, the volume location client,
the SSE-S3 reader's configuration call, the peer registrar dial and the
lock client. It is attached per call, never to the cached channel, and
never to master, volume or peer mount RPCs.

The filer refuses MountRegister, MountList and distributed locks to
scoped tokens, so the mount refuses to start when -filer.tokenFile is
combined with -peer.enable or -dlm instead of failing at run time.
Server-side copy_file_range signs its filer HTTP request with the HTTP
key, not this token, and is unsupported with it.

Without the flag the mount behaves as before.

* mount: resubscribe metadata with a replaced filer token

A metadata subscription keeps the authority it opened with, so a mount
reading -filer.tokenFile would follow with the old token until the filer
ended the stream at expiry, and every such end took the gap path that
distrusts all cached listings.

SubscribeMetaEvents now takes the credentials of each attempt. The mount
opens each subscription with the token current at that moment and
watches the file; once it holds a different token the attempt ends and
the follow resubscribes at once from its checkpoint. This planned
resubscribe is not a gap: cached listings stay, unless the new grant may
show less than the old one or either token cannot be decoded, in which
case they are read again so nothing the old grant showed outlives it.

The filer walk treats a resubscribe like a stopped follow, so the same
attempt is not replayed on the next filer. Without a token file nothing
changes.

* mount: hand the mutation stream over to a replaced filer token

The mutation stream keeps the token it opened with, and a filer refuses
to send on a scoped stream once that token has expired. A mutation
applied at that moment loses its reply, the mount reads that as a
transport failure, and the unary fallback sends it again.

The stream now opens with a snapshot of the token source. Before
admitting a request it checks the source: when the file holds another
token, or the stream's token would expire before a reply could come
back, the stream is retired. New requests wait while the admitted ones
are answered, the stream is half-closed so the filer finishes it, and a
successor opens with the new token. The waits give up only after
filerRPCWait without a response, so a rename that keeps answering is not
cut short. A request is never resent by the handover: one still
unanswered when the wait gives up fails as on any lost stream, as
before.

A token too close to expiry to open a stream with is refused before
anything is sent, so the request goes out once as a unary call, which
the filer checks when it starts. Without a token file nothing changes.

* mount: review fixes for the filer token file

- A distrust of cached listings now also discards the directory builds in
  flight, in the meta cache's apply loop: such a build publishes nothing,
  its entries are wiped and the visit lists the directory again, so a
  listing read under a grant that has since narrowed is never cached after
  the distrust. The cached flags are reset again in the loop, after any
  build that completed before it.
- Retiring the mutation stream runs in the background, and a request that
  waits for the retirement gives up on its own context, unadmitted.
- With a token file and no filer signing key, server-side whole-file copy
  is not tried: its filer HTTP request would go out unsigned and fail as
  ambiguous. The copy streams through the chunk path instead.
- On Windows the token file is opened with delete sharing, so a renewer
  can replace it by rename while a read holds it open; the missing-file
  test checks os.ErrNotExist instead of Unix wording.

* mount: review fixes for the mutation stream handover

A request admitted to the mutation stream with just over one RPC wait
left on its token could wait behind a slow send until that margin was
gone; its reply could then be refused at expiry and the request was
resent over unary. The send loop now checks the margin again right
before sending and holds back a request that no longer has it, which is
safe to send over unary because the filer never saw it. A sent request
whose reply is lost while the token has one RPC wait or less left now
fails with EIO instead of a transport error: the filer may have applied
it, so it is not resent. Losses with the margin intact fall back to
unary as before.

A newly opened stream now admits its first request through the same
checks as an open one, so a token file replaced, or a token that neared
expiry, while the stream opened is caught before anything is sent.

A retirement keeps a cancel handle for its stream. Close uses it, so
unmount no longer waits for admitted requests to be answered, and a
waiter that gives up on a retiring stream stops it as it would stop an
open one, so a request still queued there is never sent after that
waiter fell back to unary. An ordinary rotation still drains admitted
requests.

* mount: drop kernel listings when the filer token's grant narrows

A replacement token whose grant may not cover the old one already
distrusts the mount's own cached listings. The kernel kept its own copy:
OpenDir sets FOPEN_CACHE_DIR | FOPEN_KEEP_CACHE, so a directory still
reachable under the new grant was listed again from the page cache with
names the new grant may hide, until something else invalidated it.

On a narrowed or undecodable grant the mount now also notifies the
kernel for every directory inode it holds, from the subscription
goroutine as the metadata apply path already does, so the next readdir
reaches the mount. A readdir already under way on an open handle still
finishes from what it read.

* mount: drop kernel listings after a subscription gap too

distrustCachedListings serves both the narrowed-grant path and the gap
path. A gap can lose the very events that would have dropped the kernel's
cached listings one directory at a time, and with FOPEN_KEEP_CACHE on
OpenDir the kernel then serves those listings on every reopen. Move the
kernel drop into distrustCachedListings so both paths get 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-30 13:02:28 -08:00
05d9242f3c s3api: answer NoSuchBucket to a denied authenticated request on a missing bucket (#13139)
* s3api: optionally answer NoSuchBucket to a denied signed request on a missing bucket

## Problem

AWS S3 answers 404 NoSuchBucket to an authenticated caller that is denied on a bucket that does not exist. SeaweedFS answers 403 AccessDenied. S3-compatibility test suites run by data platforms (which create, probe and clean up buckets with a scoped key) flag the difference, and a client that maps 404 to "create it" or "skip it" takes the 403 for a permissions problem instead.

Answering 404 tells every authenticated identity whether a bucket name exists, which a multi-tenant deployment may not want, so the default stays 403.

## Fix

A new option, off by default: `-s3.noSuchBucketWhenDenied` on `weed server`, `weed filer` and `weed mini`, `-noSuchBucketWhenDenied` on `weed s3` (`S3ApiServerOption.NoSuchBucketWhenDenied`).

With it set, `refineDenial` extends `refineDenialForBucketName` (400 InvalidBucketName) with the NoSuchBucket answer, in `Auth`, `AuthPostPolicy` and the POST policy handler:

- only after authentication succeeded with a signature or a token (signed, presigned, V2, streaming signed, streaming-unsigned with a signed header, JWT). The anonymous identity keeps 403 under any auth type, so an anonymous caller still learns nothing about which buckets exist;
- a bucket-level PUT (CreateBucket, configuring a bucket) keeps 403, as AWS answers a refused create;
- the lookup goes through the bucket config cache, which the authorization path has usually just filled, so a denied request rarely costs a filer lookup; a failed lookup is "unknown" and keeps 403;
- an allowed request never looks a bucket up.

`Auth` now keeps the auth type it used to discard; the POST policy handler, which verifies the form signature itself, passes `authTypeSigned`.

With the option off nothing changes.

## Tests

`weed/s3api/auth_no_such_bucket_test.go`:

- `TestRefineDenialThroughAuth`: through `iam.Auth`, a signed caller denied on another identity's existing bucket gets 403 and on a missing bucket 404 (GET, PUT, a signed streaming-unsigned PUT); a bucket-level PUT stays 403; the caller's own bucket is allowed with no lookup.
- `TestRefineDenialAnonymousLearnsNothing`: anonymous requests answer 403 for a missing and an existing bucket alike and never drive a lookup.
- `TestRefineDenialRules`: presigned and JWT callers, failed authentication, allowed requests, a missing bucket name, a failed lookup, and the option off (no lookup wired) all keep their answer.
- `TestPostPolicyDeniedNoSuchBucket`: a verified browser POST form denied on a missing bucket answers NoSuchBucket; a bad signature stays SignatureDoesNotMatch; an existing bucket stays AccessDenied.

`TestRefineDenialThroughAuth`, `TestRefineDenialRules` and `TestPostPolicyDeniedNoSuchBucket` fail without the NoSuchBucket answer. `go vet` reports nothing in the touched files; `go test ./weed/s3api/ ./weed/command/`: ok. `go build ./weed`: ok.

* s3api: count streaming-unsigned as signed only with a SigV4 or JWT credential

A client-certificate identity that streamed its body unsigned answered
NoSuchBucket on a denied missing bucket, while the same request without
the body-encoding header answered 403.

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

* s3api: tell the anonymous identity by name, without the unlocked pointer read

isAnonymousIdentity compared against iam.identityAnonymous without iam.m,
racing a configuration reload. The configured anonymous identity always
has the anonymous name and account, which the check already covers.

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

* command: keep allowBackslashInKeyUsage's doc comment on its const

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

* s3api: answer NoSuchBucket to a denied request on a missing bucket by default

AWS S3 answers it this way, so drop the -s3.noSuchBucketWhenDenied flag
and always wire the bucket lookup.

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

* s3api: answer NoSuchBucket to a client-certificate identity too

The AWS answer now goes to every authenticated identity, so it no
longer depends on how the caller authenticated. The anonymous identity
keeps 403, as anonymous object reads mask a missing bucket.

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

* s3api: fold the NoSuchBucket answer into refineDenialForBucketName

One refinement for the bucket a denied request names: 400 for a
malformed name, 404 for a missing one. The anonymous read paths keep
their answer, since the anonymous identity never gets the 404.

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-30 13:00:01 -08:00
Chris LuandClaude Opus 5.5 2b0bff0135 filer.sync: warn when the source metadata log no longer covers the sync (#13143)
* filer.sync: warn when the source metadata log no longer covers the sync

A sync replays the source's metadata log from its saved position, or from
the oldest log file when it has none. Once older log days are purged, a
position older than the log silently skips the purged changes, and a fresh
sync never copies entries whose last change was purged, so the target ends
up incomplete without any sign of it.

At start, compare the position with the oldest log file the source keeps;
for a fresh sync, look for a child of the source path whose last change
(commit time, or mtime for entries without one) predates the log, and log
a warning naming it.

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

* filer.sync: skip excluded and multipart upload entries in the log gap check

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

* filer.sync: run the log gap check without delaying the subscription

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:56:31 -08:00
50f7c73101 s3 backend: HTTP/1.1 client defaults for disable_http2 (#13126)
* s3 backend: HTTP/1.1 client defaults for disable_http2

## Problem

`disable_http2` (#11897) keeps the cloud tier's S3 client on HTTP/1.1, so every tier upload and range read gets a connection of its own. The rest of the client still has the defaults sized for one multiplexed HTTP/2 connection:

- Go's idle pool keeps only 2 connections per host, so a burst of concurrent range reads redials TLS for almost every request once the burst is over and the next one starts;
- the wait for response headers is the 60 s bound every tier client has;
- the SDK retries 3 times.

On a Ceph RGW-based S3 service, HTTP/2's small flow-control window held tier uploads at 18 MB/s and made 24 concurrent cold scans take 52 s each; on HTTP/1.1 they took 3.7 s each, but only with a larger idle pool, a shorter header bound and more retries for the 503 SlowDown answers that the extra parallelism draws.

## Fix

With `disable_http2 = true` the tier client also gets:

- an idle pool of 100 (`MaxIdleConns` and `MaxIdleConnsPerHost`);
- `ResponseHeaderTimeout` of 30 s;
- `MaxRetries` 5, so the SDK's retryer backs off on 5xx, SlowDown and throttling.

`max_connections` and `idle_connection_timeout_seconds` apply as before. Without `disable_http2` the client is unchanged. The scaffold `master.toml` mentions the defaults.

## Tests

`TestS3BackendHTTP1ClientDefaults` in `weed/storage/backend/s3_backend/s3_sessions_test.go`: with `disable_http2` the transport has the idle pool and the 30 s header bound, and the client 5 retries; without it (and with `max_connections` set) the client keeps the SDK's retries, the default idle pool and `s3ReadTimeout`. It fails without the change.

`go vet ./weed/storage/backend/s3_backend/` and `go test ./weed/storage/backend/s3_backend/`: ok. `go build ./weed`: ok.

* s3 backend: keep the larger idle pool for every tier client

A tier client on a plain http:// endpoint, or on a TLS service that offers
no HTTP/2, speaks HTTP/1.1 without disable_http2 and had the same 2 idle
connections per host, so each burst of concurrent reads redialed. HTTP/2
keeps one connection, so the pool size does not change it. The header
bound and retries stay with disable_http2.

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-30 12:53:24 -08:00
dependabot[bot]andChris Lu faffb0d291 build(deps): bump github.com/jackc/pgx/v5 from 5.10.0 to 5.13.0 (#13164)
Bumps [github.com/jackc/pgx/v5](https://github.com/jackc/pgx) from 5.10.0 to 5.13.0.
- [Release notes](https://github.com/jackc/pgx/releases)
- [Changelog](https://github.com/jackc/pgx/blob/master/CHANGELOG.md)
- [Commits](https://github.com/jackc/pgx/compare/v5.10.0...v5.13.0)

---
updated-dependencies:
- dependency-name: github.com/jackc/pgx/v5
  dependency-version: 5.13.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>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 12:48:51 -08:00
dependabot[bot] 5f65cd0859 build(deps): bump go.mongodb.org/mongo-driver from 1.17.9 to 1.17.10 (#13163)
Bumps [go.mongodb.org/mongo-driver](https://github.com/mongodb/mongo-go-driver) from 1.17.9 to 1.17.10.
- [Release notes](https://github.com/mongodb/mongo-go-driver/releases)
- [Commits](https://github.com/mongodb/mongo-go-driver/compare/v1.17.9...v1.17.10)

---
updated-dependencies:
- dependency-name: go.mongodb.org/mongo-driver
  dependency-version: 1.17.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-30 12:48:04 -08:00
dependabot[bot] 184860a4c3 build(deps): bump golang.org/x/oauth2 from 0.37.0 to 0.38.0 (#13165)
Bumps [golang.org/x/oauth2](https://github.com/golang/oauth2) from 0.37.0 to 0.38.0.
- [Commits](https://github.com/golang/oauth2/compare/v0.37.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/oauth2
  dependency-version: 0.38.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-30 12:47:44 -08:00
dependabot[bot] 1924ce9f06 build(deps): bump github.com/aws/aws-sdk-go-v2 from 1.48.0 to 1.48.1 (#13166)
Bumps [github.com/aws/aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2) from 1.48.0 to 1.48.1.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/v1.48.0...v1.48.1)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go-v2
  dependency-version: 1.48.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:34 -08:00
dependabot[bot] 3993cb38c3 build(deps): bump github.com/jhump/protoreflect from 1.18.1 to 1.19.0 (#13167)
Bumps [github.com/jhump/protoreflect](https://github.com/jhump/protoreflect) from 1.18.1 to 1.19.0.
- [Release notes](https://github.com/jhump/protoreflect/releases)
- [Commits](https://github.com/jhump/protoreflect/compare/v1.18.1...v1.19.0)

---
updated-dependencies:
- dependency-name: github.com/jhump/protoreflect
  dependency-version: 1.19.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-30 12:47:24 -08:00
dependabot[bot] 62d6127d6e build(deps): bump actions/download-artifact from 7 to 8 (#13169)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 7 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-30 12:47:15 -08:00
dependabot[bot] a07f774e6f build(deps): bump github/codeql-action from 4.39.4 to 4.39.5 (#13170)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.4 to 4.39.5.
- [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.4...v4.39.5)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 4.39.5
  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-30 12:47:05 -08:00
dependabot[bot] b066c31172 build(deps): bump sigstore/cosign-installer from 4.1.3 to 4.1.4 in /.github/actions/sign-image (#13171)
build(deps): bump sigstore/cosign-installer

Bumps [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) from 4.1.3 to 4.1.4.
- [Release notes](https://github.com/sigstore/cosign-installer/releases)
- [Commits](https://github.com/sigstore/cosign-installer/compare/v4.1.3...v4.1.4)

---
updated-dependencies:
- dependency-name: sigstore/cosign-installer
  dependency-version: 4.1.4
  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-30 12:46:53 -08:00
672ba10b2b iceberg: parse each table metadata version once and encode the load response once (#13129)
* iceberg: parse each table metadata version once and encode the load response once

Under an Iceberg commit load, about half of the S3/Iceberg server's CPU went into the JSON of the same metadata document. A writer loads a table and then commits to it, and each request parsed the stored metadata again (`table.ParseMetadataBytes`, 17% of CPU in a profile). The load then marshalled it, `json.Marshal` compacted and validated the whole document again around the `json.RawMessage` inside `MarshalJSON`, and the response encoder did that once more around the result (8%). The cost grows with a table's snapshot history.

Changes:

- `tableMetadataCache` keeps the parsed form (and, lazily, the rendered response form) of recently read metadata documents, keyed by bucket and metadata location and bounded at 64 MiB (an entry is charged 6x its source size; a document over a quarter of the bound is never cached). An entry is used only when the stored bytes are byte-identical to the bytes it was parsed from, so a hit returns exactly what parsing would; the key only finds the candidate, and a parse error is never cached. Load table, commit table and commit transaction read through it.
- The parsed metadata is shared read-only between requests: iceberg-go guards its lazily decoded snapshots with its own `sync.Once` and lock, and the metadata builder copies what it changes (`TestMetadataCacheSharedEntryUnderConcurrency`, run with `-race`).
- A table commit remembers the version it stored (parsed from exactly those bytes), so the next load of it is a hit, and drops the version it replaced; a transaction commit drops the versions it replaced.
- `LoadTableResult.MarshalJSON` assembles the response around the rendered metadata instead of re-encoding it as a `RawMessage`, and `writeLoadResult` writes those bytes without the encoder's extra pass. The rendering is used only while `Metadata` is still the cache entry's own parsed metadata; a filtered (`?snapshots=refs`) or replaced `Metadata` is marshalled as before. An encoding failure is now a 500 rather than an empty 200.

The response bytes are the same as before: `TestLoadTableResultMarshalBytes` compares them with the previous encoding, including HTML and U+2028 escaping, with and without a metadata location, config and storage credentials. `TestMetadataCacheHitsOnlyIdenticalBytes` covers the byte check, parse errors, eviction and the commit remember/forget path.

Measured on one server at 8 concurrent writers, about 20 commits/s, CPU sampled over 20 s: 30.0 s before, 21.7 s after.

`go vet ./weed/s3api/iceberg`, `go test ./weed/s3api/iceberg` and `go test -race -run 'MetadataCache|LoadTableResult' ./weed/s3api/iceberg` pass; `go build ./weed` builds.

* iceberg: the shared-entry concurrency test shares one entry

The test started from an empty cache, so each worker could miss and parse
its own copy, and it passed without readers and builders ever sharing an
object. The entry is now parsed before the workers start, and each worker
checks that it was handed that entry. A cache that returns a fresh copy now
fails the test.

* iceberg: keep the snapshots=refs check inline and log the parse error directly

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

* iceberg: shorten the metadata cache comments

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-30 11:50:59 -08:00
a2d6b07d3c filer: refuse a non-recursive delete of a bucket that has children (#13122)
* filer: refuse a non-recursive delete of a bucket that has children

A non-recursive delete of a folder that has children fails with
ErrNonEmptyFolder: doBatchDeleteFolderMetaAndData lists the folder's
first page and refuses. For a bucket on a store that keeps each bucket
apart (leveldb3, the SQL stores with bucket tables, ArangoDB, YDB with
bucket tables), it skipped that listing, because such a store drops a
deleted bucket's children in one call and a recursive delete needs no
walk. The non-recursive delete then went through: DeleteFolderChildren
dropped the bucket's objects, the bucket entry was deleted, and
DeleteEntryMetaAndData deleted the bucket's collection, so the objects'
volumes went with them.

rmdir on a weed mount, fs.rm without -r and a filer HTTP DELETE without
recursive=true each send such a delete. On the other stores the same
request is refused.

A non-recursive delete now lists a bucket on these stores the way it
lists any other folder, and is refused when the bucket has children. An
empty bucket is still dropped by the store, which frees what the store
keeps per bucket, and a recursive delete still drops a bucket without a
walk.

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

* filer: say why a non-recursive bucket delete still sweeps

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-30 11:50:00 -08:00
8bb5c069ec iceberg, s3tables: new tables take only fresh locations (#13160)
* s3tables, iceberg, lance: the catalog assigns every new location; an existing name answers only a reader

A REST create without a location gets <ns>/<name>-<uuid> (#12475) and a
location another record holds is refused (#12473), but a location a
client names is still taken: the REST create's location field and
warehouse property, S3 Tables CreateTable and CreateView with a
MetadataLocation, the Lance declare's location. A free location a client
picks can be one another caller holds staged write credentials for
(stage markers are not claims), or files no record claims any more.
Separately, CreateTable of a name that already holds a table returns
that table (ARN, version token, metadata location) to any caller who may
create, including one who may not read it.

- A REST create or create view naming a location (field or property,
  stage-create or not, the bare bucket included) is refused with 400
  before anything is written; the location is always placeNewEntry's:
  <ns>/<name>-<uuid> in the bucket, or under the operator's
  ICEBERG_WAREHOUSE (no longer under a client's warehouse property).
- A create commit uses a stage marker only when its assign-uuid matches
  the staged table's UUID (PyIceberg and Java send it); any other create
  commit is placed at a fresh <name>-<uuid>, never at the bare name path
  and never at another caller's staged location. Its updates may not set
  another location than the one assigned (400).
- S3 Tables CreateTable and CreateView naming a MetadataLocation are
  refused with 400 (ErrClientTableLocation) unless the call is the
  process's own (WithCatalogAssignedLocation: the REST create, create
  view and create commit at the location they placed; the Lance declare
  at the dataset's name path and register at an existing dataset). AWS's
  CreateTable takes no location either.
- A Lance declare naming a location is refused with 400 (register is for
  existing datasets).
- CreateTable of an existing name answers the table only to a caller who
  may GetTable it; a caller who may only create gets 409
  TableAlreadyExists and nothing about it.

Tests: TestAClientCreateNamesNoLocation (positive controls: a client
create without a location, the catalog's own create with one),
TestARESTCreateNamesNoLocation, TestACreateCommitCannotSetAnotherLocation,
TestACreateCommitTakesOnlyItsOwnStage (the stager's own commit is the
positive control), TestCreateExistingTableAnswersOnlyAReaderWithIt (a
reader gets the table). Existing tests adapted: the s3tables fixtures and
request helpers run as the catalog's own calls (assignedCtx), as do the
iceberg tests that seed tables through the manager;
iceberg_create_table_conflict_test.go's creates send no location and
newConflictEnv points placeNewEntry at conflictLocation, so its races
still collide on one location; TestCreatePathsRefuseAnotherTablesLocation
expects 400 for the three create paths and 409 for the register;
TestCreateTableWithoutLocationUsesItsOwnDirectory drops the bare-bucket
body; lance TestIcebergTablesAreInvisible seeds its Iceberg table as the
catalog; TestDeclareOfAnExistingTableKeepsItsLocation expects 400 for a
declare naming the index's location; TestDeregisterAndReregisterNeedUpdateTable
(#12552) expects 409 instead of 404 for the register and the declare of
a caller without GetTable: the table stays deregistered and nothing is
vended. Each rule is red with it undone.

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

* iceberg: a create may name a fresh location

A REST CreateTable naming a location (Trino always sends one built from
the namespace location, Spark LOCATION, PyIceberg location=) is accepted
again when nothing is stored under it and no live stage holds it; a used
or staged location answers 400. The check runs after the create's
authorization and before anything is written. A bare-bucket location
still gets the assigned <name>-<uuid>. CreateView always uses the
assigned location: a view holds only metadata files.

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

* lance: a declare may restate its name path as its location

pylance and other namespace clients may send the location they expect;
the dataset's own name path is accepted, any other location still
answers 400.

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

* iceberg: a commit cannot set another location on an existing table

CommitTable and CommitTransaction applied a set-location update, so a
table's metadata could name a location outside the directory its record
holds. Such a commit now answers 400 and nothing is written.

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

* iceberg: the fresh-location check pages through every stage marker

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

* iceberg: a fresh location stays apart from stages and tables above or under it

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

* iceberg: a create checks its location again after claiming it

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

* s3tables, iceberg: a live stage holds its location against every create

The catalog counts each live stage-create as a root of the record it
would commit to, so a native create, register, rename or move over a
stage's location is refused. The fresh-location check reads the same
roots, so a stage also backs out of a record that claimed an ancestor
after its first check. A location held by a record or stage answers 409,
as the create gate already did.

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

* iceberg: a create removes only the stages its location covers

A create or commit used to drop every stage marker of its name, which
freed the location of a stage whose credentials were still live.
Expired markers now go with their staged metadata.

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

* iceberg: an assigned stage location checks its claim again too

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

* iceberg: a stage marker lasts as long as its vended credentials

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

* iceberg: test a create that runs while a stage checks its claim

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

* iceberg: a stage holds its location against a create of the same name

A live stage-create now counts under its marker rather than under the
record of its name, so a same-name create over its location is refused
and a stage refuses a same-name table created over its location. Only a
staged commit takes the location its own stage holds.

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

* s3tables: a stage holds only its location against its own record's create

A live stage keeps the path of the record it would commit to away from
other records' files, but a create of that same record writes it: the
stage then holds only its location against it. A stage at its name path
can commit while a later stage of its name, elsewhere, is live.

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

* iceberg: a staged commit's create gate reads its location as a create does

The gate maps a metadata file's location to its table directory, so the
bare location of a stage under a metadata directory resolved to the
namespace and conflicted with the stage's own claim.

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

* iceberg, lance: tests from master create through the catalog's own call

Their creates name a location, which only the catalog's own calls may, and
a caller who may only create gets 409 for an existing name whatever
location its register names.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:47:29 -08:00
Javier de la TorreandClaude Opus 5.5 aa006fa228 iceberg: answer vended credentials with Cache-Control: no-store (#13137)
A table or view load (and create) answered with `X-Iceberg-Access-Delegation: vended-credentials` carries live S3 session credentials in `config` and `storage-credentials`. The response sends `Vary: X-Iceberg-Access-Delegation` but no `Cache-Control`, so a shared HTTP cache in front of the catalog may store it and hand one caller's table-scoped session to another caller of the same URL that sends the same delegation header. The OAuth token endpoint already answers `Cache-Control: no-store` for the same reason (RFC 6749 §5.1).

`writeLoadResult` sets `Cache-Control: no-store` when the response holds credentials: a non-empty `storage-credentials`, or `s3.access-key-id` / `s3.secret-access-key` / `s3.session-token` in `config` (tables and views, values or pointers). Responses without credentials are unchanged.

`TestVendedLoadAnswerIsNoStore` (vended and not vended, table and view responses): red with the header removed. `go vet ./weed/s3api/iceberg/` and `go test -race ./weed/s3api/iceberg/` pass, and `weed` builds.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:36:25 -08:00
3da9c41404 iceberg maintenance: worker setting for the row-group size of compacted files (#13128)
* iceberg maintenance: worker setting for the row-group size of compacted files

Compaction takes a compacted file's row-group size from the table property `write.parquet.row-group-size-bytes`, and falls back to Iceberg's default, 128 MB, when the table sets none. Most tables set none, and the default target file size is also around 128 MB, so a compacted file usually comes out as a single row group. A reader's column filter (a time range, an id range) can then skip the whole file or nothing inside it.

Setting the property table by table is the only way to change that today. This adds a worker setting, `row_group_size_mb`, that sets the size for tables without the property:

- default 0 = Iceberg's 128 MB, so nothing changes unless an operator sets it;
- the table property still wins over it, so an engine or a user that chose a size keeps it;
- `write.parquet.row-group-limit` (rows) is untouched.

For example, `row_group_size_mb = 64` gives about two row groups per 128 MB compacted file.

Test: `TestRowGroupSizeWorkerSettingAndTableOverride` (the default is 0, the setting is read, a table without the property gets the worker's size, the property wins).

`go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg maintenance: raise the descriptor version with row_group_size_mb

The admin keeps a stored descriptor unless the new one's version is not
lower. With both at 1, an older worker serving a descriptor refresh during a
rolling upgrade replaced the form and row_group_size_mb disappeared. The
test fails at version 1.

* iceberg maintenance: say row_group_size_mb also caps the spatial row group size

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

* iceberg maintenance: keep at least one row per row group when a row outgrows the byte size

With an explicit row limit the estimate had no floor, so a byte size
smaller than one row gave 0, which parquet-go takes as no limit.

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

* iceberg maintenance: say row_group_size_mb only caps a spatial rewrite's row groups

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-30 11:33:32 -08:00
4cda7ca0a4 iceberg: a transaction's rollback never overwrites a later write (#13162)
* iceberg: a transaction's rollback never overwrites a later write

CommitTransaction rolls an already flipped table back with an
UpdateTable that names no version token: a commit that landed on the
table after the flip is overwritten, and the transaction's metadata file,
which that commit may build on, is deleted with it. A table that had no
metadata location before the transaction (created without one, never
committed) is not put back at all (an update leaves an empty location as
it is), yet its restore is reported done and the file it still points at
is deleted: the table then fails every load. And when the failing flip
lost a version race, the client was answered 409 CommitFailedException
even though a table left unrestored kept the transaction's change: a
client that refreshes and retries applies it twice.

- The flip records the version token it wrote, and the restore is
  conditional on it (it fails, and the file is kept, when anything wrote
  since).
- A table that had no metadata location before the transaction is
  reported unrestored, so it keeps the transaction's metadata and file.
- When any table is left unrestored the answer is 500
  CommitStateUnknownException; a full rollback still answers 409.

Tests: TestARolledBackTransactionNeverOverwritesALaterWrite (a write
before the rollback and one during the restore's write are both kept;
the file stays while referenced) and
TestARolledBackTransactionKeepsTheFileOfATableItCannotRestore (the table
still loads; the flip fails with a version race and the answer is 500).
The test filer (memFiler in iceberg_create_view_test.go) now answers a
lookup with a copy and refuses a conditional UpdateEntry whose
ExpectedExtended no longer holds, as the filer does; without it no
conditional write could fail in these tests. Red with the restore
unconditional, with the no-location table restored, and with 409 for an
unrestored table.

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

* iceberg: the failing-flip test filer fails only record writes

A storage marker written on a table's own directory carries the record
it read unchanged; failing or counting it moved the injected failure
and the concurrent write off the flip and the restore.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:31:38 -08:00
8f4663f516 iceberg: a Lance record loads with read-only credentials (#13159)
iceberg: the Iceberg REST catalog keeps off Lance tables

A Lance dataset's catalog record lives in the same table bucket as
Iceberg tables, and the Iceberg REST endpoint serves it as a table:
LoadTable vends write credentials over the dataset's directory to anyone
who may update the table, and CommitTable or CommitTransaction on it
writes Iceberg metadata into the dataset's directory and repoints the
record at it. Reproduced on master: the record's metadataLocation became
finance/vec/metadata/v2.metadata.json, its format still LANCE.

notIcebergTable now refuses a commit and a transaction on a record of
another format with 400, after the commit's authorization; LoadTable
serves a catalog-only record as an empty table (its metadata is never
read as Iceberg) with read-only credentials. A REST create of the name
already answered 409.

Test: TestIcebergRESTKeepsOffLanceTables: an Iceberg table's owner gets
write credentials (positive control), the Lance table read-only ones;
commit and transaction 400; the Lance record unchanged. Red with each of
the three rules undone.

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:30:50 -08:00
d29b0d430c lance: a register of a new name needs a dataset at its location (#13158)
* lance: a register of a new name needs a Lance dataset at its location

A Lance register of a new name takes any free location in the table's
namespace (#12473 refuses one another record holds), so it can claim an
empty location, or a dropped table's emptied root, in the catalog's
stead.

A register of a name without a record now authorizes the create with its
location (AuthorizeCreateTable: the permission, the namespace check and
the refusal of a claimed location run before anything is read, so a
location in another namespace is answered alike whether it holds a
dataset or not), then refuses with 400 a location holding no Lance
dataset (no _versions/). A name that has a record, readable by the
caller or not (deregistered, or without GetTable), keeps the existing
path: CreateTable answers for it and bringing it back needs UpdateTable
(#12552).

Test: TestRegisterNeedsALanceDataset: an empty location 400; a caller
who may not create 403; a dropped table's root 400; another namespace's
path answers the same with and without a dataset; a written dataset
registers (positive control). Red with the dataset check removed, the
authorization skipped, or the location left out of the authorization;
TestDeregisterAndReregisterNeedUpdateTable is red when the dataset check
also runs for a name that has a record.

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

* lance: a register of a name with a record keeps the CreateTable path

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

* lance: a register needs _versions to be a directory

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:30:17 -08:00
10c66011c8 iceberg: vended credentials list only the table's directory (#13157)
s3: vended credentials list only inside their table's directory

A vended session's s3:ListBucket is conditioned on s3:prefix
{prefix, prefix/*}. The bare table path (ns/t) also matches every
sibling whose name starts with it, so a session vended for ns/t lists the
object names of ns/t2/..., ns/t_x/... and ns/t-<uuid>/... (the catalog's
own placements of other tables).

The condition is now {prefix/, prefix/*}: the table's directory only. A
client listing the table's location without the trailing slash (Java's
S3FileIO.listPrefix(location), used by remove_orphan_files) is refused
with vended credentials; reads, writes and listings of the table's
directory are unaffected.

Test: TestTablePrefixSessionPolicyRestrictsListing now expects the
slash-terminated pair; red with the bare prefix back.

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:29:52 -08:00
79b4a8ab31 s3tables: keep a table's root on update and rename (#13156)
* s3tables, lance: an update cannot move a table's or view's root

UpdateTable and UpdateView may move a record to another root (the move is
reserved while it happens: moveCatalogRecord, ExtendedKeyMoving). The old
root is then claimed by no record, although the table's older snapshots
still name files under it: a table registered or created over it loads
them and is vended credentials for them, and its drop purges them.
Reproduced on master: table u moved from ns/udir to ns/u2, an alias
created at ns/udir, the alias dropped: u's first snapshot's data file is
gone.

An update whose metadata location gives the record another root is now
refused with 400 InvalidRequest (ErrLocationMove) before anything is
written. No client path needs a move: a commit writes under the location
the record has (a table created without a location commits at its
assigned directory; a table renamed into another namespace keeps
committing at its directory, #12515). Lance's Overwrite register at
another dataset goes through UpdateTable and is refused the same way; an
Overwrite at the table's own location still works. The move reservation
stays (a reservation a crashed move left is still cleared by the next
update).

Tests: TestUpdateCannotMoveATablesRoot (the move refused, an alias over
the old root refused, the old snapshot's file kept, an update under the
table's own root works). Existing tests adapted to the rule, none
deleted: the UpdateTable refusals of TestLocationOwnedByOneRecord, the
moving subtests of TestLocationRaceBacksOut and
TestMoveReservationLeftBehind expect 400 with nothing written;
TestUpdateAfterRenameAcrossNamespacesRefusesAnotherTablesDirectory and
TestUpdateAfterRenameAcrossNamespacesMayMoveIntoItsNamespace expect
ErrLocationMove; vector_namespace_test.go's UpdateTable keeps the index's
root so its write reaches the fence it tests; lance
TestRegisterOverwriteKeepsTheOldDataset expects 400 for an Overwrite at
another dataset, the location unchanged and the dataset kept. Each
refusal is red with it replaced by the claim check.

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

* s3tables: a record without a stored location is not renamed

A rename moves the catalog record and leaves the files where they are. A
record with neither a metadata location nor a warehouse location (every
Lance dataset, which lives at its name path; an Iceberg table created at
its name path by an older build) takes the root of its record path, so
after a rename it claims its new, empty name path and the files at the
old one belong to no record: a table created under the old name sits on
them. Reproduced on master: Lance table l renamed to l2, ns.l declared
again, l2's _versions/1.manifest is under the new ns.l.

A rename whose record would claim another root at its destination than
at its source is now refused with 400 InvalidRequest, after the
authorization checks (a caller without rights is answered as before). A
record with a stored location keeps its root and renames as before,
within its namespace or into another. In the vector namespace of a
vector bucket the read-only answer its fence gives stays the answer.

Tests: TestRenameRefusesARecordWithoutAStoredLocation: a Lance dataset
renamed in its namespace and a location-less Iceberg table renamed into
another are refused, both records and the dataset's files stay; a table
with a stored location renames (positive control). Adapted: the rename
subtest of TestLocationRaceBacksOut (its table has no stored location)
expects 400 with nothing written. Red with the refusal removed, and
TestVectorNamespaceIsReadOnlyOverLance/rename_out with the vector
namespace's answer skipped.

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

---------

Co-authored-by: Javier de la Torre <jatorre@carto.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:29:04 -08:00
442e0a24c6 iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s (#13138)
* iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s

## Problem

The Iceberg REST catalog vends table-scoped S3 sessions on load and create with one process-wide lifetime, `-iceberg.credentialDurationSeconds` (default 3600). A client has no way to ask for less, and nothing can go below STS's 900 s floor. Some deployments want short sessions for some callers (a one-off read, a session handed to a less trusted process) without shortening them for every client: a process-wide 900 already breaks clients that keep a loaded table object for longer than its session (PyIceberg does not refresh vended credentials; DuckDB, Spark and Trino re-load and are fine).

The Iceberg REST spec has no parameter for a credential lifetime. The precedent is `DurationSeconds` on AWS STS and on Lake Formation's `GetTemporaryGlueTableCredentials`.

## Fix

- **Request header** `X-SeaweedFS-Credential-Duration-Seconds` on a load or create that asks for vended credentials (`X-Iceberg-Access-Delegation: vended-credentials`). A positive whole number of at most 9 digits is passed to the vendor; a missing, malformed, zero, signed or overlong value is ignored without an error, so clients that never send it see no change.
- **It can only shorten a session.** The vended lifetime is `min(asked, configured)`; with no configured duration the ceiling is STS's `TokenDuration`, capped at `MaxSessionLength` as STS caps it. A request at or above the ceiling changes nothing (the configured duration is sent, as before).
- **Floor:** new `-iceberg.credentialMinDurationSeconds` (`-s3.iceberg.credentialMinDurationSeconds` on `weed server` and `weed mini`), **default 900, which keeps today's behaviour exactly.** A request below the floor is raised to it. Values outside 1-900 mean 900, with a warning at startup; the setting can only lower the floor.
- **STS:** `AssumeRoleForPrincipalRequest` gains `MinDurationSeconds`, a per-request floor honoured only within (0, 900]. Only the catalog's vend sets it, and only when the client actually shortened the session: a vend at the configured duration keeps the 900 s floor (so a configured `credentialDurationSeconds` under 900 is still refused), and AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials and every other action keep 900 through the unchanged `validateSessionDurationSeconds`. `MinSessionDurationSeconds` names the 900.
- **Caching:** load answers now send `Vary: X-Iceberg-Access-Delegation, X-SeaweedFS-Credential-Duration-Seconds`, so a cache never hands a session vended for one lifetime to a request that asked for another.
- The client learns the lifetime it got from `s3.session-token-expires-at-ms`, as today. The Lance namespace vend passes 0 (unchanged).

## Tests

- `weed/s3api`: `TestVendDurationRequestOnlyShortensTheSession` (real STS and trust policy; the lifetime read from the session JWT's `exp - iat` and `max_dur`): nothing asked keeps 3600; 120 honoured; 60 at a floor of 60; 7200 capped to 3600; 30 raised to a floor of 60; floor unset, 900 or 1200 keeps 900. `TestVendFloorDoesNotLowerAssumeRole`: with the floor at 60 the vend mints 60 s (positive control) while AssumeRole and AssumeRoleWithCredentials on the same server refuse 60 s. `TestVendDurationRequestRespectsMaxSessionLength`, `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`.
- `weed/iam/sts`: `TestSessionFloorIsLoweredOnlyForTheRequestThatAsks`.
- `weed/s3api/iceberg`: `TestCredentialDurationHeaderReachesTheVendor` (the accepted and ignored header forms), and the Vary test updated.
- Each rule undone turns its test red (request ignored: `TestVendDurationRequestOnlyShortensTheSession`, `…RespectsMaxSessionLength`; floor applied to every vend: `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`).
- `go vet` and `go test` of `weed/s3api`, `weed/s3api/iceberg`, `weed/iam/sts`, `weed/iam/integration`, `weed/command` pass, `-race` on `weed/s3api/iceberg`, and `weed` builds.

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

* iceberg: let a shortened vend fit a caller credential with less than 900 s left

A vend the caller shortened below 900 s (with a lower catalog floor)
needs only that floor of the caller's credential to remain, not 900 s.

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-30 10:52:41 -08:00
81f9231e2f iceberg compact: optional spatial clustering of geometry tables (#13135)
* iceberg compact: optional spatial clustering of geometry tables

Compaction of an Iceberg v3 table with a geometry column merges files in
manifest order (bin-pack) or by a declared sort order. Neither keeps nearby
geometries together: after a bin-pack every output file and row group spans
the whole extent of the table, so a reader can skip nothing by the geometry
bounds and row-group geospatial statistics. In one measurement a point lookup
on a table of places read 4.59 MB after bin-pack compaction and 0.55 MB after
a spatial one. A declared sort order cannot express this either: Iceberg v3
has no spatial sort transform, a geometry cannot be a sort source, and DuckDB
refuses INSERTs into a table that declares a sort order.

This adds an opt-in spatial order to the compaction job.

Spatial clustering (`spatial_clustering`, off by default). When on, a v3
table with no declared sort order and exactly one top-level geometry column
is rewritten in the Hilbert order of each row's bounding-box centre, whatever
`rewrite_strategy` says (a declared sort order is still honoured, since such a
table does not qualify):

- The 62-bit key (31 bits per axis) is computed from the WKB while the rows
  stream through the merge, carried as an extra last column through
  parquet-go's sorting writer into a temporary file in `sort_spill_dir`, and
  dropped when a plain writer copies the rows to the output. Row lineage is
  mapped before the key is added. The grid is the globe for a lon/lat CRS and
  the union of the bin's file bounds for a projected one. Null, empty and
  unreadable geometries sort last. The key only orders rows; pruning stays on
  the geometry bounds, so a poor key costs speed, never results.
- Files are listed by the key of their bound's centre before binning, so the
  bins of one partition cover compact areas.
- Row groups target `spatial_row_group_size_mb` (2 MB, capped by the table's
  `write.parquet.row-group-size-bytes`, at least 16 rows; an explicit
  `write.parquet.row-group-limit` still wins). A row group is what a spatial
  filter skips, and a row of a large polygon can be tens of kilobytes.
- A bin the order cannot be laid over (a projected column whose files carry
  no bounds, a geometry column the merge cannot find, e.g. after a rename in
  files without field ids) is bin-packed in bin-pack row groups.
- The table property `seaweedfs.compaction.spatial-column` names the column
  when a table has several, or opts a table out with `none`.
- The snapshot summary records `rewrite-strategy=spatial` and
  `spatial-column`, or `binpack` when every bin fell back, and
  `spatial-fallback-bins` when some did. The planning
  index's config hash covers the new settings.

Open time partitions (`spatial_hold_open_partitions`, default true, and
`spatial_open_partition_grace_minutes`, default 120; both only matter with
spatial clustering on). A spatially ordered partition has every row group
spanning its whole time range. On a day of vehicle positions, "where is every
vehicle now" read 2.51 MB of the spatially compacted day against 0.04 MB of
the files as written, while an area query on a closed day read 2.74 MB
against 19.35 MB. So a day or hour partition is left in write order until it
has ended plus the grace (late batches still land in it), and is ordered in
space after that. The job and detection hold the same bins; the planning
index caches its answer only until the first held partition is released, so
a table nobody writes to after midnight still gets its last day ordered.
Coarser time partitions and the other strategies are unchanged.

`github.com/twpayne/go-geom` (already in the module graph) becomes a direct
requirement for its WKB parser.

Tests:

- spatial_order_test.go: the Hilbert curve, plan resolution (version, sort
  order, one or several geometry columns, the property, opt-out), 2,400
  scattered points compacted end to end in spatial order with row ids kept
  and no key column written, the job setting off as control, nulls last, a
  projected CRS with and without file bounds, file ordering, and the
  row-group sizing.
- spatial_fallback_test.go: the bin-pack fallback uses bin-pack row groups;
  a geometry column the merge cannot find falls back, with the summary
  saying so.
- spatial_open_test.go: partition ends for day and hour across the value
  types a manifest reader returns and far from 1970; the hold, the grace and
  their controls; the planning index release time and config hash; on the
  fake filer, a day-partitioned geometry table where the job compacts the
  past day in spatial order and leaves today's files, a table of only today
  commits nothing, and the index records midnight UTC plus the grace (each
  with the hold off as control); spatial clustering is off by default.
- Mutation checks: a constant key fails the spatial order tests; disabling
  the hold fails four open-partition tests.
- go vet and go test (also with -race) of weed/worker/tasks/iceberg pass;
  go build ./weed passes.

* iceberg compact: give the spatial sort key a name no table column has

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

* iceberg compact: report spatial order only for bins it wrote

A bin skipped after a read or merge error no longer counts as
spatially ordered in the snapshot summary or the job result.

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

* iceberg compact: do not hold an open partition the spatial order cannot cover

A projected geometry column whose files carry no bounds is bin-packed,
so holding its open day or hour partition only left small files behind.

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

* iceberg compact: do not hold a drop-only bin in an open partition

A bin whose rows are all deleted removes its files and writes nothing, so
there is no spatial rewrite for an open day or hour partition to wait for.

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

* iceberg compact: pack delete-heavy files in the spatial file order

Delete-heavy bins took the table's order while the other bins of a spatial
plan list their files by the Hilbert key of their geometry bounds, so a
partition split into several delete-heavy bins merged overlapping areas.

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-30 10:51:16 -08:00
ec2d96888d pb: use the slot allocator as gRPC's buffer pool (#13136)
* pb: power-of-two gRPC buffer tiers up to 1 MB

## Problem

gRPC's default buffer pool has tiers of 256 B, 4 KB, 16 KB, 32 KB and 1 MB, and zeroes a pooled buffer's whole capacity on every `Get`. Every message between 32 KB and 1 MB therefore zeroes 1 MB, in the proto codec's marshal and in every receive. A filer entry that holds a table's Iceberg metadata (inline content, extended attributes) is such a message, several times per commit.

Profiled on `weed mini` under an Iceberg commit load (8 DuckDB writers, one table each, 30 s CPU profile): `runtime.memclrNoHeapPointers` under `sizedBufferPool.Get` was 2.39 s of 30.0 s sampled, 8% of the process's CPU. With the tiers below it is 0.74 s of 22.2 s.

## Fix

`weed/pb` sets the process-wide default pool at init (`experimental.SetDefaultBufferPool`, which gRPC documents as init-time only) to a binary tiered pool with every power of two from 4 KB to 1 MB (plus 256 B), so zeroing is bounded by twice the message size. Buffers are still zeroed; only the tier sizes change. The proto codec reads only the default pool; `NewGrpcServer` and `GrpcDial` also pass the pool as an option (`experimental.BufferPool`, `experimental.WithBufferPool`), because gRPC's own default server and dial options captured the old pool before this package's init ran.

Messages up to 32 KB and above 1 MB use the same tiers as before. Each extra tier is a `sync.Pool`, emptied by the GC like the others.

## Tests

`weed/pb/grpc_buffer_pool_test.go`:

- `TestGrpcBufferPoolIsTheDefault`: the default pool is the tiered one.
- `BenchmarkGrpcBufferPoolGet`: a `Get`+`Put` with gRPC's default tiers against these (Apple M-series, `go test -bench GrpcBufferPool -count 3 ./weed/pb/`):

| message | default tiers | power-of-two tiers |
|---|---|---|
| 40 KB | 9.8–10.1 µs | 0.59–0.71 µs |
| 100 KB | 10.1–10.8 µs | 1.24–1.29 µs |
| 300 KB | 11.1–14.7 µs | 5.6–5.7 µs |

`go vet ./weed/pb/` reports nothing in the touched files; `go test ./weed/pb/`: ok. `go build ./weed`: ok.

* pb: test the buffer capacity each gRPC pool tier hands out

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

* pb: rely on the default pool for dials, which read it per connection

grpc's defaultDialOptions() reads mem.DefaultBufferPool() at dial time,
so only the server, whose defaults were captured at grpc's init, needs
the pool passed as an option.

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

* mem: return only slot-sized buffers to the slot pools

Free put any buffer into the slot its capacity rounds up to, so a nil or
odd-capacity buffer made a later Allocate of that slot panic.

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

* mem: serve the slots through a Get/Put pool type

SlotPool satisfies gRPC's mem.BufferPool, and Allocate and Free now go
through it.

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

* pb: use the slot pool as gRPC's buffer pool

The slots round up to the next power of two and do not zero, so gRPC
shares buffers with Allocate and no longer clears them on every Get.

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-30 10:50:31 -08:00
Yip LeoandClaude Opus 5.5 c3f7f24684 mount: wake an upload parked on a read when the read ends (#13123)
* mount: wake an upload parked on a read when the read ends

An upload that finishes while a read holds its chunk waits in its own
goroutine until the read lets go (`for up.IsLocked(index) {
up.readerCountCond.Wait() }`), and only then drops the sealed chunk and
returns its executor slot. The only wake-up came from MaybeReadDataAt,
which a read calls before it lets go of the chunk. UnlockForRead, where
the read does let go, woke nobody. So:

- A read that returns before its dirty-page pass never wakes the
  upload. readDataByFileHandleWithContext skips readFromDirtyPages when
  the chunk read fails, and the kernel interrupts a FUSE read, which
  cancels it, whenever a signal reaches the reading thread.
- A read that does call MaybeReadDataAt wakes the upload while it still
  holds the chunk, so the upload goes back to waiting unless the read
  releases the chunk before the upload gets the lock back.

Only a later read of the same file then moves the upload on. When none
comes, because the file was closed or is no longer read, the upload
stays parked for good. It keeps its sealed chunk (and its share of
-writeBufferSizeMB, when that is set) and a slot of the
concurrentWriters executor, which every file of the mount shares (128
by default). Once parked uploads hold every slot, each new upload of
the mount waits for one, and writes and flushes behind them hang.

UnlockForRead now broadcasts when the last read of a chunk ends, which
is the only place the condition changes, and MaybeReadDataAt no longer
signals. It broadcasts rather than signals: a read across a chunk
boundary releases two chunks, and an upload may be parked on each.

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

* mount: wait for the uploads to park instead of sleeping in the wake-up tests

parkUploads slept 100ms and assumed the uploads were waiting on the read
by then. An upload that had not got there yet would find the read gone
and go on without a wake-up, so the tests could pass with the wake-up
missing. It now watches the goroutines' stacks until each upload waits
on readerCountCond, counting out uploads an earlier test left waiting.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:49:25 -08:00
576eb98ce9 mount: leave -cacheMinFreeSpace free on the chunk cache's disk (#13124)
* mount: leave -cacheMinFreeSpace free on the chunk cache's disk

weed mount sizes its on-disk chunk cache by -cacheCapacityMB alone and
preallocates each cache file in full when it creates it. With a capacity
larger than the free space of the disk holding -cacheDir, the cache takes
that disk down to nothing: the preallocations run until fallocate fails,
and chunk writes fill the rest. The mount's metadata cache (a leveldb
store under -cacheDir) and the swap files of dirty pages (-cacheDirWrite,
which defaults to -cacheDir) live on the same disk, so once it is full
their writes fail with ENOSPC, and writes whose dirty pages spill to
swap return EIO to the application. The same happens when several mounts
share a cache disk and together are configured beyond it.

-cacheMinFreeSpace is the free space the cache leaves on that disk,
written like the volume server's -minFreeSpace: a percentage like 1 or a
size like 10GiB, 1 by default, as for volume servers.

- When the cache opens, its disk layers shrink to the space above the
  floor, counting the cache files already in the directory as the cache's
  own. With no room the disk tier keeps no files.
- Each new cache file preallocates only what the disk holds above the
  floor at that moment, so the files of one cache, or the caches of
  several mounts opening together, stop reserving at the floor.
- A chunk write that lands in blocks its file already holds, preallocated
  or written, goes ahead as before, even with the disk under the floor.
  A write that takes new disk space, into a file a rotation truncated or
  where nothing could be preallocated, goes ahead only while the space
  above the floor covers it. The disk is read at most once a second, and
  the cache counts what it takes in between, so it cannot run past the
  floor between readings. A rotation gives the truncated file's blocks
  back, so the write after it reads the disk again.

A chunk the cache cannot place is not cached, like any other miss. The
webdav server's cache passes no floor and behaves as before.

* mount: read the cache disk on every write that takes space, leave the index files room

Review follow-ups.

- take reads the disk each time, instead of once a second less what the
  cache took since, so a write sees what other mounts sharing the disk
  wrote, and what a rotation gave back. It runs only for writes past the
  blocks a file already holds, and a statfs costs little next to the
  write.
- The index files (.idx and the leveldb maps) grow by a few dozen bytes a
  chunk beside the data files that the cache size counts. Sizing leaves
  them a sixteenth of the room above the floor.
- The cache's own files count as room by the blocks they hold, so a file
  that was preallocated but not yet written when the mount exited counts
  in full when the cache reopens.
- weed fuse checks -o cacheMinFreeSpace in the parent as well: the parent
  waits for the child's signal, and a child that rejects the value never
  sends it.

* mount: keep the resolveCacheDirs doc comment on resolveCacheDirs

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

* mount: say -cacheMinFreeSpace stops new disk space, not every chunk

Under the floor the cache still fills the blocks its files already hold.

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-30 10:48:28 -08:00
Tiago PosseandClaude Opus 5.5 7a5c12a8b0 filer: order finished reader cache downloads by a counter (#13125)
Eviction picked the oldest finished download by the wall clock time it
finished at, and only counted downloads that finished before
time.Now(). A download that finished in the same clock tick as the
eviction didn't count, so the loop fell back to a chunk a stream was
still reading, and two pinned downloads that finished in the same tick
tied. After a wall clock step back, downloads that finished before the
step didn't count either, and with none of them pinned nothing was
evicted and the cache grew past its limit.

Finished downloads now take the next value of a counter on the cache,
which never ties or steps back.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:46:16 -08:00
Yip LeoandClaude Opus 5.5 ecd0493906 mount: keep following the metadata log when the cache refuses an event (#13141)
* mount: keep following the metadata log when the cache refuses an event

The mount applies each event of the filer's metadata log to its local
metadata cache, a leveldb store under -cacheDir. Once that disk is full
every write to the store fails, and an event the cache refuses goes one
of two ways:

- An event the stream delivers fails the follow, which the mount runs
  with FatalOnError: glog.Fatalf ends the process, every file open on
  the mount goes with it, and the mount does not come back when the disk
  has room again.
- An event replayed from the persisted log is returned to the follow
  loop, which resubscribes from it and fails on it again: the mount
  stays up, but no later event reaches its cache, so its listings stop
  changing.

A local change whose apply fails (create, mkdir, unlink, rmdir) drops
its directory's cached listing with InvalidateChildrenCache and goes on.
An event from the log now does the same: the cached listings it
changes, the parents it leaves and enters and a directory it creates,
moves or deletes, are dropped, so the next lookup reads the filer and
the next listing rebuilds them, and the event's kernel invalidations
still go out. The follow goes on. A warning reports the first such
event and then at most one a minute.

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

* mount: handle a refused event in the apply step that refused it

Review of the previous commit found two gaps.

A rename into a directory whose listing is being built applies the part
leaving the source at once and keeps the part entering the building
directory for the build to replay. When the part applied at once was
refused, the other part was not kept, and the build published its
listing without the renamed file. It is now kept whatever happens to
the part applied at once.

The listings a refused event changes were dropped, and its kernel
invalidations sent, by the follow's event function after the apply
returned. By then the apply loop could have taken a later request, such
as this mount's own create of the name a rename left, and the rename's
invalidation would then move the new file. The apply step that fails
now does both before it returns, as it sends the side effects of an
event the store takes, and on the apply loop, which owns buildingDirs
and is the only one to feed the invalidate worker. A local change whose
apply fails gets the same; its caller still drops its directory's
listing as before.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:42:25 -08:00
3c7b3fc16f mount: fail an unlink or rename the filer did not apply (#13140)
* mount: fail an unlink the filer did not apply

* mount: hold an unlinked handle's flushes until the filer answers

* mount: mark a rename's replaced handle once the filer answers

* mount: read a draining handle's unlink mark under its lock

Unlink now sets the mark after the delete answers, while a close queued
before it can be draining, so the worker's bare read raced the write.

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

* mount: drop the unlink comment about marking before the delete

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

* mount: wait for the close to block on the handle lock in the unlink and rename tests

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

* mount: wait on the handle lock with the untagged helper in the rename close test

waitAttributeReadFrame lives in a !freebsd test file, so the FreeBSD test
build failed on weedfs_rename_publish_test.go.

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-30 10:41:22 -08:00
Chris LuandClaude Opus 5.5 d4a21cef59 weed: flush buffered log lines when a command exits (#13151)
exit() ends the process with os.Exit, which skips deferred calls, and
glog writes its files only every 30s. A short-lived command such as a
piped weed shell session lost every log line it buffered, including the
daily_run summary of s3.lifecycle.run-shard.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:39:05 -08:00
edbcc718d3 iceberg: read remote-only metadata files, and fail a table whose metadata cannot be read (#13134)
* iceberg: read remote-only metadata files, and fail a table whose metadata cannot be read

## Problem

In a remote-mounted bucket (`remote.mount` + `filer.remote.sync`), a table's `metadata.json` that is not cached locally is a filer entry holding only its `RemoteEntry`: no inline content, no chunks. The Iceberg REST catalog read metadata files as inline content (and, for a register, chunks), so such a file read as empty bytes, and an empty read was then treated as "no metadata":

- a table stored with its metadata location alone (registered, or created through the S3 Tables API) loaded as an empty table: no schema, no snapshots, and clients read no rows;
- a commit to it was refused on a table UUID mismatch for ever, and a commit without requirements replaced the table's history with an empty one;
- registering such a file failed with `unexpected end of JSON input`.

The same empty stand-ins were served when the file was gone or unreadable, and a synthetic empty table when stored metadata did not parse, with the same consequences.

## Fix

- `loadMetadataFile` (and through it `currentMetadataBytes` and RegisterTable) reads a remote-only file of a mounted bucket: its remote size is checked against a 64 MiB bound before anything is fetched, it is cached into the cluster with `CacheRemoteObjectToLocalCluster` (one retry: a cache can race an uncache or a write-back), then inline content or chunks are read.
- An empty file is `errEmptyMetadataFile`. A staged create's empty placeholder is still treated as absent where the staged commit reads it.
- A location whose file is gone or unreadable, or stored metadata that does not parse, fails load, commit and transaction instead of serving an empty stand-in a writer could commit over. A table created without a location (no metadata yet) still loads as a new empty table, and a catalog-only record (Lance) is never read as Iceberg.
- RegisterTable refuses, before anything is read, a metadata location that is not a file directly in a table's `metadata/` directory (a deeper path was read as the same-named file there), and refuses metadata whose own `location` is not the table location it is registered from (a file copied from another table names that table's files).
- The table UUID a commit or a transaction stores is the base metadata's, not a record's that disagrees with it.

`loadTableMetadataBlob` (used only by the manifest repair) is unchanged.

## Tests

- New `iceberg_register_load_test.go` (inline and remote-only files; a location-only table loads from its file and fails with the file gone; commits and transactions keep the history, and fail leaving the table unchanged when the file is gone; oversized remote files and nested locations refused) and `TestACommitStoresTheBaseMetadatasUUID`. Each rule is red with it undone, except the refusal of an entry still remote-only after two cache calls, which fails closed anyway (it reads as an empty file).
- Adapted: the fixtures of `iceberg_register_table_test.go` (`seedRegistrableMetadata`, `seedOversizedMetadata`) give the metadata the table's own location; `TestLoadTableResultOmitsConfigForCredentialVendingClients` and `seedOwnedTable` store the table with its metadata; `TestBuildLoadTableResultNeverReturnsNilMetadata` now expects an error for a location whose file cannot be read and for unparseable metadata, and keeps the empty-metadata and no-location cases.
- `go vet ./weed/s3api/iceberg/`, `go test -race ./weed/s3api/iceberg/` pass, and `weed` builds.

No unit test reads a chunked `metadata.json` (the in-memory filer has no volume servers); that path was checked against a real cluster with a remote-mounted bucket.

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

* iceberg: refuse commits to catalog-only tables

A Lance table loads as an empty Iceberg table, and a commit built on that
placeholder wrote Iceberg metadata and repointed the record's location
(the Lance dataset root) to it. Both commit paths now answer 400.

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

* iceberg: pass the metadata size limit to the remote cache request

The size check ran on the entry the lookup returned. A remote refresh
between the lookup and the cache call could swap in a larger object, which
the filer then downloaded whole. With MaxSize the filer checks the entry
it actually downloads.

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

* iceberg: apply the metadata size limit to inline content

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-30 10:36:13 -08:00
f4931605e0 s3tables: say why a write the table bucket layout refuses is refused (#13133)
* s3tables: say why a write the table bucket layout refuses is refused

## Problem

A table bucket accepts only Iceberg files under `<namespace>/<table>/(data|metadata)/`. A PutObject, CopyObject or CreateMultipartUpload of any other key is refused with a bare 403 AccessDenied, which a client that put a plain file there (a README, a CSV next to the table) reads as a permissions problem and goes looking for a missing grant.

## Fix

Those three refusals now carry a message:

    table buckets accept only Iceberg files under <namespace>/<table>/data/ or <namespace>/<table>/metadata/; put other objects in a general purpose bucket

Status and code are unchanged (403 AccessDenied).

The message tells the caller that the bucket is a table bucket, so it goes only to a caller the bucket policy lets write that key (`checkPolicyWithEntry`). A caller the policy denies gets the policy's own refusal, identical to the one for a key the layout accepts, so the answer never tells a table bucket from another bucket to someone who could not write there.

A PUT of the volume verification key that the layout accepts but `volumeVerifyPutAllowed` refuses (outside its window, too large, stored headers) is not a layout refusal and keeps the bare AccessDenied.

## Tests

`weed/s3api/table_bucket_layout_message_test.go`:

- `TestTableBucketLayoutRefusalExplainsItself`: PUT, copy and multipart initiation of `ns/t/data/notes.txt` answer 403 AccessDenied with the message. Fails without the change.
- `TestTableBucketLayoutRefusalIsBareWhenPolicyDenies`: with a bucket policy denying the write, the refusal of a layout-refused key is byte-for-byte the refusal of a valid `.parquet` key.
- `TestTableBucketVerifyRefusalIsNotALayoutRefusal`: a stale verification key keeps the bare refusal.

`go vet ./weed/s3api/` reports nothing in the touched files; `go test ./weed/s3api/`: ok. `go build ./weed`: ok.

* s3api: load the bucket before a layout refusal checks its policy

With authentication off nothing loads the bucket before the handler, so a
stored Deny was not in the engine yet and the first layout-refused write
after a restart got the table-bucket explanation.

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

* s3api: apply existing-object tag conditions before a layout refusal explains itself

A Deny on s3:ExistingObjectTag is deferred by the first policy check and
applied only by the later lookup recheck, which the layout refusal skipped,
so a tag-denied writer still learned the bucket is a table bucket.

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

* s3api: name the format-owned directories in the table layout refusal

Table buckets also accept a table format's own _-prefixed directories
(Lance's _versions, _transactions, _indices), so telling a Lance writer that
only Iceberg data/ and metadata/ files are accepted misleads 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-30 10:33:15 -08:00
bf14326c3c iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files (#13131)
* iceberg maintenance: recognise deletion vectors whose format is written in lowercase

Iceberg maintenance tells a Puffin deletion vector from a Parquet position-delete file by its `file_format`, compared exactly with iceberg-go's constant `PUFFIN`. DuckDB records the format in lowercase, `puffin` (as it records `parquet`, which compaction already compares without case). Such a vector was never taken for a vector:

- the data file it covers was not kept out of compaction bins, and
- the vector itself was handed to the Parquet position-delete reader, which cannot read a Puffin file, so compacting any table holding one failed (and the position-delete rewrite tried to read it the same way).

The fix adds `isPuffin`, a case-insensitive comparison, and uses it at the four places that compared the format.

Test: `TestLowercasePuffinDeletionVector` wraps a deletion-vector entry so its format reads `puffin` (as the Avro reader passes it through) and checks that the data file it covers is excluded and that `collectPositionDeletes` does not try to read the vector. It fails without the change (`dv paths = map[]`).

`go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg maintenance: apply deletion vectors in compaction; optionally rewrite delete-heavy files

Compaction has no reader for Puffin deletion vectors (DVs), so every data file a vector covers is kept out of compaction for good (`excludeDeletionVectorFiles`). A format-version 3 table that is reloaded with DELETE + INSERT (DuckDB writes a vector hiding all of the old file) keeps the old file and its vector forever, and every reader pays for both. Bins also form only from `min_input_files` small files per partition, so deleted rows never enter the decision.

This builds on #13127 (the case-insensitive `puffin` format check); the first commit on this branch is that PR.

Changes:

- **Vectors are applied.** The vectors of the compaction candidates are read with iceberg-go's `table/dv` (length, magic and CRC checked, and the decoded cardinality checked against the manifest's `record_count`) and joined with the Parquet position deletes the merge already applies. A vector that does not decode keeps its file out of every bin, as before, so a file never merges without its deletes. One Puffin file is read once per run even when it holds several vectors.
- **A consumed vector leaves with its data file.** When the snapshot removes a data file, the delete manifests holding its vector are rewritten (that vector `DELETED`, the other entries `EXISTING`); manifests without one are carried as they are. Vectors are matched by the data file they cover, never by the Puffin file path, because one Puffin file may hold the vectors of several data files (Spark writes them that way) and the vectors of files left in place must stay.
- **A bin whose deletes leave no row writes no empty file**; its files are just removed.
- **New setting `delete_ratio_threshold_percent`** (default 0 = off, so bin selection is unchanged unless set; Iceberg's own `rewrite_data_files` uses 30%). When set, a Parquet file whose vector deletes at least that share of its rows is rewritten in a bin of its own, whatever `min_input_files` says, packed by live bytes up to the target size. A file whose decoded vector deletes exactly positions 0..n-1 is dropped without being read; a manifest count that says "all" with positions that do not is rewritten row by row instead. Only files under the target file size are taken (the merge reads a file whole into memory), except a file dropped unread.
- **Detection reads no vector**: a DV's `record_count` is its cardinality, which is all the ratio needs. With `apply_deletes` off, planning ignores vectors (execution skips tables with deletes then). The planning-index cache key includes the ratio.

Tests (`deletion_vector_test.go`):

- a vector with a lowercase `puffin` format is matched to its data file under either path spelling;
- a merge with a vector and a Parquet position delete: every file merges minus its deleted rows, row ids kept, and the delete files leave the table (ratio off);
- a reloaded table: the wholly deleted file and its vector are dropped without the file being read (it is not even present), the new file untouched;
- ratio past / under / vector not decodable / manifest count says all but positions do not / partly deleted file past the target size left alone;
- two vectors in one Puffin file, only one data file compacted: the other file's vector stays;
- detection with the ratio on and off.

Each was checked red against a mutation of the rule it covers (exact format compare, vectors not applied, vector consumed by Puffin path, size check skipped, whole-file check skipped). `go vet ./weed/worker/tasks/iceberg` and `go test ./weed/worker/tasks/iceberg` pass; `go build ./weed` builds.

* iceberg compact: check a deletion vector's blob range without overflow

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

* iceberg detection: key the cached compaction plan on apply_deletes

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

* iceberg detection: skip a table with deletes while apply_deletes is off

Execution already skips it, so detection proposed a job that never ran.

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

* iceberg compact: a drop-only bin is not held to the sort input cap

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

* iceberg compact: split delete-heavy bins at the sort input cap

The packer counted live bytes only, so two partly deleted files could
share a bin the sort input cap then dropped on every run.

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

* iceberg compact: compare the delete ratio in whole rows

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

* iceberg compact: merge delete-heavy files in the order of their bounds

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

* iceberg compact: read only the vectors of files a bin can take

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

* iceberg compact: pack a vector whose count and positions disagree by its whole size

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-30 10:22:30 -08:00
347f1cf705 deps: bump parquet-go to v0.33.0 (#13130)
* deps: bump parquet-go to v0.33.0

parquet-go v0.33.0 fixes several bugs that Iceberg compaction runs into:

- BOOLEAN columns that Arrow and parquet-mr write with data page v2 are
  RLE-encoded. v0.32.0 decoded such runs wrong (a run's value byte expanded
  bit by bit, runs taken as multiples of 8 values), so compaction rewrote the
  flags wrong, and it wrote its own runs of trues with the value byte 0xFF,
  which DuckDB refuses to read ("Payload value bigger than allowed")
  (parquet-go/parquet-go#617, fixed by parquet-go/parquet-go#620).
- A column chunk without a dictionary lists the level encoding RLE next to
  PLAIN. v0.32.0 took RLE as the column's encoding, so the schema derived from
  a non-dictionary INT32 or DATE file could not write ("RLE: cannot encode
  INT32 with invalid bit-width=0") and such files never compacted
  (parquet-go/parquet-go#603, fixed by parquet-go/parquet-go#611).
- The sorting writer dropped the row groups' geospatial statistics when a
  bin fit in its sort buffer, so a sorted rewrite of a geometry table wrote
  files without a geometry bound (parquet-go/parquet-go#627, fixed by parquet-go/parquet-go#693 and parquet-go/parquet-go#700).
- A null in a list of required values wrote no value and shifted the rest of
  the page (parquet-go/parquet-go#616, fixed by parquet-go/parquet-go#618); a short data page read leftover
  values from a pooled buffer instead of failing (parquet-go/parquet-go#624, fixed by
  parquet-go/parquet-go#731).
- A geometry or geography column declared without a CRS is now written
  without one rather than with OGC:CRS84 spelled out (parquet-go/parquet-go#628, fixed
  by parquet-go/parquet-go#688).

Changes that follow from the bump:

- A corrupt data page now fails with an error rather than a panic. The
  position and equality delete readers returned that error without the file
  name; they now name the file, as the data file merge already does.
- The default-CRS tests built their "spelled out" inputs with
  parquet.Geometry(""), which now writes no CRS; they declare OGC:CRS84
  explicitly. The footer rewrite in geometry_crs.go is still needed when an
  input spells the default out, since the output schema comes from an input.

Tests:

- compact_rle_boolean_test.go with four pyarrow fixtures: two files with
  v2-page RLE booleans (with nulls) read back and compacted with every flag
  kept, and two non-dictionary INT32/DATE files compacted with every value
  kept. All three tests fail on v0.32.0 (3005 of 6000 flags wrong; "no bins
  successfully compacted").
- TestCompactSortedGeometryBoundCoversEveryRow only checked a bound when
  there was one, so it passed with the statistics dropped. It now requires a
  geometry bound on the data file and geometry statistics in the footer; it
  fails on v0.32.0 and passes on v0.33.0.
- go vet and go test of every package that imports parquet-go
  (weed/admin/dash, weed/mq/logstore, weed/mq/schema, weed/query/engine,
  weed/worker/tasks/iceberg) pass; -race on weed/worker/tasks/iceberg and
  weed/mq/logstore passes; go build ./weed passes.

* iceberg: fail the Arrow fixture tests on a read error

Both row-reading loops ended on any error, so rows decoded next to an
error could still pass the value checks.

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

* iceberg: check each fixture row comes out of compaction exactly once

A row replaced by a copy of another kept the row count and passed the
value checks, which use the row's own id.

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-30 10:18:24 -08:00
5017a07475 iceberg maintenance: whole-pass tests of equality deletes on a partitioned table (#13132)
* iceberg maintenance: whole-pass tests of equality deletes on a partitioned table

The equality-delete tests call the pieces (`collectEqualityDeletes`, `eqDeleteGroupsForBin`, `mergeParquetFiles`) one at a time. These run `compactDataFiles` end to end and check what a reader sees after the commit, including the deletes carried for files left uncompacted and the sequence numbers of the merged files. Tests only; no code changes.

The table has three partition specs: 0 unpartitioned, and 1 and 2 both `identity(name)` on the same partition field, so only the spec ID tells their deletes apart. It is written as a writer commits it: one snapshot per data sequence number, its manifests carrying the number and their ADDED entries inheriting it. Its equality deletes come in every scope: partition-scoped, global, by another column, and with keys that live in other partitions or specs. Each test reads the table before and after the pass with its own merge-on-read (each delete applies to data files with a lower data sequence number, under an unpartitioned spec or the same spec and partition) and compares the rows.

- Every two-file bin compacts, bin-packed and sorted; one partition's single file does not. The live rows are unchanged and the deletes are carried for the file left as it was (a merged file given an input's lower sequence number would lose rows to the carried deletes).
- Every file compacts: the rows are unchanged and the deletes leave the table.
- An unreadable partition delete fails the pass, names the file, and commits nothing; once the file is back the table reads as before.
- A delete under a spec the table does not list fails the pass and commits nothing.

Checked red against a mutation of the sequence-number rule (equality deletes applied whatever the sequence numbers): the first two tests fail. `go vet` and `go test ./weed/worker/tasks/iceberg` pass.

* iceberg maintenance: whole-pass table snapshot IDs differ from its sequence numbers

The fixture gave each commit's snapshot the ID of its data sequence number,
so a compaction that read an entry's snapshot ID in place of its sequence
number still kept the right rows. The IDs now count down as the sequence
numbers count up.

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

* iceberg maintenance: a whole-pass name-keyed delete that removes a live row

The only name-keyed delete matched no row, so a pass that ignored deletes
keyed by name still kept the right rows. u1 now holds a "zz" row that a
global name-keyed delete removes.

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-30 10:17:18 -08:00
Chris LuandClaude Opus 5.5 2acd49ba27 s3api: end a vended table session no later than the caller's credential (#13161)
* s3api: record the verified credential's expiry in the request context

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

* s3api: cap a vended table session at the caller's credential expiry

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

* sts: let a principal session request cap the session's expiry

AssumeRoleForPrincipal takes an absolute NotAfter. issueSession caps both
the credentials and the signed token at it, so a cap computed before the
trust-policy lookup is not stretched by the time that lookup takes.

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

* s3api: hand the caller's credential expiry to STS as an absolute cap

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:15:36 -08:00
Chris LuandClaude Opus 5.5 df59c81a8c master: record when the cluster started (#13121)
* topology: record when the cluster started

StartedAt rides on MaxVolumeIdCommand; the first non-zero value wins so
replayed or racing entries cannot move it, and the max volume id mirror
file keeps it across raft state loss.

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

* master: carry StartedAt through raft apply and snapshots

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

* master: leader records StartedAt once per cluster

The leader records it right after the topology id. A cluster that predates
the record gets the time its first upgraded leader runs. /dir/status shows it.

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

* test: use current StartedAt values

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

* topology: never lower the mirrored max volume id

A mirror rewrite for a StartedAt change could carry a bound older than
one already persisted. Keep the highest bound, and read StartedAt under
the file lock.

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

* topology: let the latest applied StartedAt win

With first-wins, a master that restored an older-version snapshot without
the field could record a second value while the others kept the first.
Following the raft order makes every master converge on the same value.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:12:46 -08:00
Chris LuandClaude Opus 5.5 d49876a7aa filer: every filer store reads KV keys in batches (#13119)
* filer: read KV keys a few at a time for a store without batch reads

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

* abstract_sql: read KV keys with one query

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

* redis: read KV keys in one pipeline

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

* etcd: read KV keys in read-only transactions

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

* mongodb: read KV keys with one query

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

* cassandra: read KV keys concurrently

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

* hbase: read KV keys concurrently

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

* elastic: read KV keys concurrently

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

* arangodb: read KV keys with one request

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

* foundationdb: read KV keys in one transaction

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

* ydb: read KV keys with one query

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

* tarantool: send KV reads before waiting for any

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

* filer: every filer store reads KV keys in batches

KvBatchGet moves from the optional KvBatchReader onto FilerStore. A listing
now reads the hard link records of its waiting entries together from any
store, a path-specific one included.

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

* tikv: count only the record reads of a listing in its test

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

* filer: return every batched key that pads to the same stored row

SQL, MongoDB and YDB pad a short KV key with zero bytes, so "short" and
"short\x00" read the same row. KvBatchGet kept only the last such key.

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

* filer: read keys in a plain loop when KvGetEach runs one at a time

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:10:49 -08:00
github-actions[bot] 604d391012 4.56 2026-11-30 02:49:57 +00:00
Chris LuandClaude Opus 5.5 689e98ea4c test: fall back to a Maven Central mirror for the S3 Spark suite (#13120)
Spark resolved hadoop-aws and the AWS SDK bundle through Ivy from Maven
Central only, so a refused Central request failed the suite with
"module not found" before any test ran. spark.jars.repositories adds the
Google mirror after Central in Ivy's resolver chain.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:32:08 -08:00
f905b33f19 tikv: read a key from TiKV once per transaction (#13115)
* tikv: read a key from TiKV once per transaction

Inside one store transaction the filer reads the same key more than once:
a rename looks its source up when it starts and again to delete it, and
its target before the create and again in it. On TiKV a second read cannot
differ from the first. A transaction reads the store as it was when the
transaction began, and its own writes are answered from its buffer. Each
of those reads was still a request to TiKV, because the client keeps what
a batch get read with the transaction's snapshot and not what a get read.

Inside a caller's transaction a key is now read as a batch get of that one
key, and the next read of it is answered from the snapshot. A read outside
a caller's transaction is a transaction of its own and keeps the plain
get.

With the store on the client library's in-process TiKV, a rename of a file
to a new name sends 4 reads instead of 7, and one over an existing file 4
instead of 6.

The tests run the store on that in-process TiKV, which needs
pingcap/goleveldb as an indirect dependency.

* tikv: shorten the comment on the transaction read

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-29 17:50:09 -08:00
cb958290c8 filer: read the hard link records of a listing in batches (#13117)
* filer: read the hard link records of a listing in batches

A hard-linked entry keeps its attributes and chunks in a record the file's
names share, and a listing reads that record for every hard-linked entry
it lists. It read them one at a time from the callback of the store's
listing: a round trip to the store for each such name, each waiting for
the one before, so a directory of hard-linked files listed far slower than
one of as many plain files.

A store may now say that it reads several KV keys in one round trip
(KvBatchReader). For a listing by such a store the wrapper holds the
entries back from the first hard-linked one on, up to 256 of them, reads
their records together and hands them on. The caller of the listing gets
the same entries in the same order, and the name of the entry it ended
the listing at.

TiKV implements it with the client's batch get. With the store on the
client library's in-process TiKV, the records of a directory of 200
hard-linked names take one batch get instead of 200 gets.

The TiKV tests run the store on that in-process TiKV, which needs
pingcap/goleveldb as an indirect dependency.

* filer: end a listing where its caller ended it, whatever the store met behind

The store goes on past the entry its caller ends the listing at, to the
entries that wait for their records with it, and may fail there. The
listing then returned the store's error, though a caller handed each entry
as it arrived would have stopped the store before it got that far. The
listing now ends at the entry its caller ended it at, and a caller that
fails among the waiting entries gets its own error, not the store's.

The same holds for the step a store takes after it is told to stop, when
the caller ended the listing at an entry the store had already passed. At
the last entry that waited the step's error is still returned, as it is
from a store that hands each entry on as it arrives.

* filer: finish a hard link listing on every return of the listing

The listing hands on the entries that wait from a deferred finish, so a
return path that lists from elsewhere with the same callback hands them on
too. The callback keeps the adjustedEntryFunc shape the prefixed listing
already had.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-29 17:47:40 -08:00
Chris LuandClaude Opus 5.5 3d076dfcdf filer: aggregated metadata stream reads the log files of peers with their own store (#13116)
* filer: pass the reader's context to persisted metadata log listings

The day and minute listings behind ReadPersistedLogBuffer used
context.Background(), so nothing scoped to the subscription reached them.
List through one helper that takes the caller's context.

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

* filer: aggregated metadata stream reads the log files of peers with their own store

A filer with its own store never holds another filer's persisted
metadata log: log file writes emit no events and the bootstrap traverse
skips the log directory. The aggregated stream read history from the
local log directory and the in-memory aggregate ring only, and the ring
restarts empty, refilled from each peer's saved offset. A subscriber whose
cursor was older than that missed every event a peer recorded before it,
for example the S3 lifecycle worker replaying expirations.

Aggregated reads now also list the log directories of followed peers not
known to share this filer's store, merged by file name, so the existing
ordered reader and chunk-ref path serve their history. Local streams, which
peers aggregate from, stay local.

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

* filer: bound peer log listings and fail the read when one fails

Each peer listing gets its own deadline, so a peer that stalls mid-listing
cannot hold the read. A failed listing now fails the read instead of
silently hiding that peer's persisted files; peers already retired as
unreachable are left out. Peers are asked from the same start name the
caller uses for its own store instead of the whole directory.

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

* filer: keep a still-unreachable peer out of log listings after its mark expires

A followed peer that keeps refusing connections is marked removed once, and
the mark is dropped with its resume point an hour later. It was then listed
again and its failing listing ended every aggregated persisted-log read.
Leave out any peer refusing connections for peerUnreachableRemovalAfter,
marked or not.

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

* filer: subscribe tests track their peers on the test filer's store

Aggregated reads now list the log files of followed peers with their own
store. The subscribe tests' peers have no server and share the test
filer's store, so record that instead of dialing them.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:46:29 -08:00
12ef22477a filer: read a missing path once when a rename or a delete looks it up (#13114)
* filer: read a missing path once when a rename or a delete looks it up

A rename looks its target up with FindEntryForOverwrite, and
DeleteEntryMetaAndData looks up the path it deletes the same way. Inside a
store transaction an ordinary lookup hides an expired S3 entry and leaves
its row for the commit. A write over the path still owes that row its
chunks and its hard link, so the store was read again whenever the lookup
came back with nothing.

It comes back with nothing far more often because the store holds nothing
at the path, which is what a rename to a new name finds. The second read
then repeats the first. Filer.findEntry already tells whether its answer
is what the store holds at the path, so the store is read again only for
a row the lookup found and kept from its caller.

Around 20 renames of a file to a new name on leveldb2 the store counter
shows 7 finds per rename before and 6 after.

* filer: shorten the overwrite-lookup comments

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@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-29 17:45:49 -08:00
Chris LuandClaude Opus 5.5 bd9e9a37c2 mount: send an open's truncate to the write owner as a conditional update (#13113)
An open with O_TRUNC over an existing file stored the empty entry with an
unconditional UpdateEntry. The filer only routes conditional writes to the
path's write owner, so the truncate landed on the filer the mount talks to,
which deleted the chunks it dropped, while a peer's conditional chmod could
still commit at the owner over the entry it had not yet seen truncated. The
owner's write then brought the deleted chunks back into the entry.

The truncate now goes through saveEntryAttributes: guarded by the entry the
open found, routed to the owner, and replayed on the owner's entry when
refused.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:44:06 -08:00
github-actions[bot] 7d1ad72e74 docs: regenerate star history chart 2026-11-30 01:27:56 +00:00
Martijn HoekstraandClaude Opus 5.5 89dbcb44c7 security: fips.mode follow-ups from the #13029 review (header comments, EMS on verified HTTPS, CA and read checks) (#13110)
* volume: read security.toml section headers that carry a trailing comment

The volume server's own security.toml parser compared each whole trimmed
line with the section headers it knows, so `[fips] # policy`, valid TOML
that Go's viper reads, fell through to an unknown section and its `mode`
was dropped: Go enforced the mode while weed-volume ran with FIPS mode off
and logged nothing. The same held for `[jwt.signing]` and every other
section. Header lines now have a trailing `#` comment removed before they
are matched.

Refs #13029

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

* sw-client: require the Extended Master Secret on verified HTTPS in FIPS mode

In FIPS mode only the `insecure_skip_verify` client configuration, which
sw-client builds itself, set `require_ems`. With certificate checks on,
reqwest built the configuration and left `require_ems` at rustls's
default, which is off for a provider that is not FIPS-validated, so a
trusted TLS 1.2 volume server without EMS was accepted where the insecure
path refused it. Go requires EMS in FIPS mode. Both FIPS-mode paths now go
through one rustls configuration built here: certificates checked against
`https.client.ca` or the system roots (loaded with rustls-native-certs, as
reqwest loads them), or not checked with `insecure_skip_verify`, and EMS
required either way. Off mode keeps reqwest's configuration.

Refs #13029

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

* volume: refuse a FIPS mode from a security.toml parse that did not read the file

resolve_fips_setting reads security.toml once to check that it can, then
parses it. The parse falls back to defaults when its own read fails and
reports that only in `file_read`, which was not checked, so a file that
became unreadable between the two reads resolved to FIPS mode off. A
parse without `file_read` is now the same FipsModeError::File as a failed
first read.

Refs #13029

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

* sw-client: refuse a malformed https.client.ca with insecure_skip_verify in FIPS mode

The FIPS-mode insecure_skip_verify configuration never parsed
`https.client.ca`, so a CA file whose certificate does not parse was
accepted there and refused on every other path, where reqwest or the
verified configuration load it. The CA is now parsed, and refused when
malformed, before it is set aside.

Refs #13029

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

* seaweed-vector: lock sw-client's rustls-native-certs dependency

sw-client depends on rustls-native-certs since the FIPS-mode HTTPS
configuration; seaweed-vector depends on sw-client by path, so a --locked
build there refused to update its lockfile. The crate was already locked
in seaweed-vector; only the edge was missing.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:57:41 -08:00
Chris LuandClaude Opus 5.5 276be51d04 volume(rs): require the Extended Master Secret on outgoing HTTPS in FIPS mode (#13111)
The outgoing client took reqwest's rustls configuration, which leaves
require_ems at rustls's default: off for a provider that is not
FIPS-validated. A TLS 1.2 peer without EMS was accepted where Go's FIPS
mode refuses it. In FIPS mode the configuration is now built with the same
roots, CA and identity, and require_ems set.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:56:59 -08:00
760f88e294 filer: bind scoped POSIX locks to the verified token id (#13047)
* filer/posixlock: key lock owners and leases by principal

A lock's owner becomes (Principal, Sid, Owner). The principal is server-side
state, empty for unscoped callers, so owners with equal client-chosen sid and
owner under different principals conflict and never match on unlock, release,
reassertion or coalescing. The session index and leases key on
(Principal, Sid).

Scoped sessions are leased per key from their first acquisition: the lease
ends at the earlier of TTL after the last acquisition or renewal on that key
and Lease.NotAfter. Expired scoped locks are dropped before any operation on
their key as well as by ReapExpired. Unscoped sessions keep their current
whole-session lease, started by the first keepalive.

The handler passes the unscoped session for now, so behaviour is unchanged.
NewManagerWithClock lets tests drive lease boundaries.

* filer: bind scoped POSIX locks to the verified token id

PosixLock trusted the client-supplied sid. GET_LK reports a conflicting
lock's sid and owner, so a scoped caller with a write grant on the same path
could reuse them to unlock or release another holder's lock, keep it alive,
or replace it through a KEEP_ALIVE reassertion. A tokenless request with the
same identity could do the same.

A request admitted for a scoped token now acts for that token's verified jti,
derived in posixLockAuthority from the interceptor's authority. It controls
only the locks it took, whatever sid or owner it names. Its lease on each key
ends at the earlier of the 15s TTL after its last acquisition or renewal and
the token's expiry plus the clock leeway. Each renewal passes admission for
its key, so a narrower token cannot extend keys outside its grant. Tokenless
and unscoped calls keep the unscoped namespace and behaviour, and can no
longer match a scoped lock. Scoped TRY_LOCK and reassertion ranges must be
well-formed read or write ranges, checked before any state changes.

GET_LK, the protobuf and forwarding are unchanged; the principal is never
returned or logged. A renewed token with a new jti is a new owner: the old
locks expire and are reacquired.

* filer/posixlock: release an expired session once, however many ranges it holds

* posix locks: report a lock lost on re-assertion to the mount

A mount whose lease lapsed, for example when its scoped token expired or
was replaced by one with a new id, kept re-asserting locks that another
session had since taken. The filer logged the loss but returned success,
and the mount discarded the reply, so nothing on the mount side showed it.

KEEP_ALIVE now returns the first conflicting lock in the existing
has_conflict and conflict fields, which older mounts ignore. The mount
warns once per key when it learns of a loss and forgets it once a
re-assertion succeeds or the key is no longer held. Writes are not fenced.

* filer/posixlock: drop every expired session's ranges in one pass

* filer/posixlock: renew a scoped session's same-grant leases together

Scoped leases expire per key and a keepalive renewed only the key it named.
A mount renews its keys one keepalive at a time, so with many keys and slow
keepalives a round could outlast the 15s lease and a healthy mount lost
locks; unscoped sessions never had this problem because any keepalive
renews the whole session.

Each scoped lease now records a fingerprint of the verified grants it was
acquired or re-asserted under: a SHA-256 over the sorted, deduplicated
(access level, path) entries. A keepalive, bare or re-assertion, extends
every live lease of the same session (principal and sid) held under the
same fingerprint, each to the request's lease (the earlier of the TTL and
the token's expiry plus leeway). Leases taken under other grants, such as
a narrower token reusing the jti, are still renewed only by name, and a
lease that already ended is not revived before the sweep drops it. No
extra filer lookups; unscoped sessions are unchanged.

* filer/posixlock: bound same-grant renewal and refuse ended-lease grants

A scoped keepalive scanned every key of its session to renew those held
under the same grant, so a mount renewing N keys one by one did N^2 lease
visits per round under the manager's mutex. The scan now runs at most once
per quarter lease TTL per grant; every key under the grant still ends no
earlier than three quarters of a TTL after the latest renewal, and the named
key is always renewed in full.

TryLock now refuses a scoped grant whose lease has already ended, such as a
request admitted just before its token expired that then waited on the
manager, instead of granting a lock the next operation would drop. The filer
returns Unauthenticated, which the mount reports as EIO.

* filer/posixlock: skip same-grant scans by deadline floor, not by time

The scan throttle remembered when a grant was last renewed, not how long
that renewal made its keys last. A replacement token with the same id and
grants but a later expiry could then renew one key while the others kept
ending at the old token's expiry.

Each session now keeps, per grant, the deadline the last scan gave every
live key under it, lowered whenever a key is leased for less. A renewal
skips the scan only while that floor already reaches the earlier of its
own deadline and three quarters of a TTL from now, so a mount renewing
keys one by one still costs linear work.

A keepalive from a session holding no leases records nothing, and a
session's floors go with its last lease, so lock-less keepalives with
changing session ids no longer accumulate state the sweeper never sees.

* filer/posixlock: never move a scoped lease's deadline earlier

Renew, a re-assertion, a same-grant scan and a re-lock all set the key's
deadline to the request's own bound. A request under the old token of a
principal that already renews under a replacement (same id and grants,
later expiry) can land after the replacement's renewal, for example one
of the 32 concurrent keepalives in flight when the mount switched
credentials. It then cut the key back to the old token's expiry, and the
lock was dropped before the next round although the replacement had
renewed it. Keep the later of the current and the requested deadline:
every deadline still comes from an admitted request of the same
principal, so a lease never outlives the latest of its tokens.

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

* filer/posixlock: keep each session's index and leases in one map

bySession, lastSeen, leases and floors were four maps keyed by Session that
had to be created and pruned together. They become one sessions map whose
sessionState holds the session's keys (with each key's lease), its last
keepalive and its grant floors, so a session's state is dropped in one place.
The release loop shared by ReapExpired and ReleaseSession becomes releaseOn.

ReleaseSession now also forgets an unscoped session's last keepalive, so a
session it released is not reported again by the next sweep.

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-29 12:58:42 -08:00
Chris LuandClaude Opus 5.5 46b10efcce mount: refuse a stale truncate over a peer's chunks and keep later times when merging a flush (#13100)
* mount: refuse a merge whose local truncate cuts chunks a peer wrote

A flush refused by IF_ENTRY_EQUAL replays the handle's truncate onto the
stored entry. The truncate was made over the handle's base, so a chunk a
peer committed after that base was dropped or clipped silently, losing
data the peer had already fsynced. Like a stale whole-file rewrite over a
peer's chunk change, it now fails the merge. A base chunk the peer only
shortened carries no peer data and is still cut.

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

* mount: keep the later mtime and ctime when merging a delayed flush

The merge took every attribute the handle changed from the handle, so a
flush that waited behind a peer's commit moved mtime and ctime back to
the handle's older write. Each time is now merged as one value (seconds
and nanoseconds were merged field by field, so a moved second could take
the peer's nanoseconds): the handle's time stands unless a peer moved it
too and later.

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

* mount: let a truncate merge pass the handle's own committed chunks

A flush whose commit answer was lost finds its own chunks in the stored
entry while its base is still the older one. Those chunks are the
handle's writes, not a peer's, so they do not refuse the merge.

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

* mount: do not keep a stored copy of a chunk the merge re-adds from the handle

A stored chunk the base lacks but the handle holds is the handle's own
commit whose answer was lost. The merge appends the handle's chunks after
the stored ones, so keeping the stored copy referenced the chunk twice.

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

* mount: take the manifests of a failed flush's fold for the handle's own chunks

A flush can commit its folded manifests and lose the answer. The handle
reverts to the member chunks and keeps its old base, so the next merge
found the stored manifest, knew neither its file id nor its key, and
refused it as a peer write across the handle's truncate.

The handle now remembers the folds of flushes that failed over its base,
and a merge unfolds them in the stored entry before comparing, so the
members match the handle's chunks. A peer's manifest is still refused.

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

* mount: take a retried flush's own stored fold for its own chunks

The client retries a request whose connection dropped, and the first try
may have stored the flush's folded manifests. The retry is then refused
over them before the fold is recorded as failed, and the merge took the
manifest for a peer's write across the handle's truncate. The merge now
unfolds the flush's own fold in the stored entry as well; the condition
still names the entry as stored.

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

* mount: keep every fold the filer may hold instead of the last four

Dropping the oldest of four could forget the fold the filer committed,
and the merge then refused that manifest again. A fold is now kept only
when the flush failed without the filer's answer, or when the refusal
lookup shows it stored, so a refused flush no longer adds one, and the
list ends with the base.

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

* mount: keep a flush's fold when its first request may have been stored

A precondition verdict on a retried send does not prove the first send
stored nothing, and a failed refusal lookup then hid that it had. The
create now counts the sends of the request that carries the fold and
keeps the fold whenever the flush fails and that request was sent more
than once or never got the filer's answer. That covers both flush paths,
so revert is back to only restoring the chunks.

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

* mount: drop the failed folds a refused create shows were not stored

A refusal means the stored entry moved off the handle's base, so no
request guarded by that base can store another fold. After the refusal
lookup the handle keeps only the folds whose manifests the stored entry
holds, at most one, which bounds the list over a base.

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

* mount: bound the failed folds a handle keeps over one base

Flushes that keep failing with no filer answer each saved a new fold the
filer may hold, so the list grew for as long as the outage lasted. Once a
handle keeps maxFailedFolds folds over its base, its flushes send their
chunks unfolded for the filer to fold, and no kept fold is dropped.

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

* mount: keep the failed folds a refusal lookup does not show

The refusal comes from the file's write owner, but the lookup after it can
read a filer that lags behind and still shows the base. Pruning the folds
against that read forgot a fold the owner had stored, and once its manifest
showed up a pending truncate took it for a peer's chunk on every flush. The
maxFailedFolds limit bounds the list, so the folds stay until the base moves.

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

* mount: drop the chunks a failed flush sent that the handle has cut since

A flush that commits with its answer lost, then a truncate of the handle,
left the next merge with the handle's own committed chunks in the stored
entry, outside both base and the handle. The truncate check took them for
a peer's writes and refused every later flush over the base. A failed
flush now records the file ids of the chunks it sent that base lacks, and
the merge drops those the handle no longer holds: it cut or replaced them.

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

* mount: copy the failed flush's sent set with a loop

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

* mount: keep folding past maxFailedFolds instead of sending chunks unfolded

The filer folds a flat chunk list itself, into manifests the handle does
not know: a lost answer then left one of them across a pending truncate,
and an acknowledged one gave the handle flat chunks under a folded base.
Flushes fold as before, and the handle stops keeping folds past the limit
while it still records the chunks they sent.

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

* mount: read the stored manifests a refused merge cannot name

A fold changes no content, but a manifest the handle does not know sat in
the stored entry as one chunk: across a pending truncate it refused the
merge, though it can hold the handle's own chunks (a fold it did not keep,
or one the filer made). When the merge is refused, the flush reads those
manifests, replaces them with the chunks they hold and merges again.

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

* mount: hold the chunks the filer stored after a plain acknowledged flush

The filer folds a flat chunk list (the mount's own fold failed), and the
acknowledgement makes the stored entry the base while the handle kept the
flat chunks. A later merge took them for writes of the handle, which can
bring back chunks a peer's truncate removed. As after a merge, the handle
now takes the stored chunks, keeping those attached since the request.

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

* mount: keep a bounded record per failed flush instead of a growing set

The set of chunk ids failed flushes sent grew with every overwrite while
commits failed, and each failure copied it whole. Each failed flush the
filer may have stored (a send got no verdict) now keeps one record, its
fold and the ids it sent, built once and at most maxFailedFlushes over a
base. Past that, a merge refuses the chunks of a flush it did not keep
that the handle has cut since, as a peer's.

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

* mount: register the chunks a rebase or install gives the handle for reads

A handle that takes the stored chunks after a flush (or a peer's, after a
merge) can get manifests the filer made, and resolving them needs the
file's read token. rebaseEntry and installRewrittenChunks now record the
chunks under the file's path before the read view resolves them.

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

* mount: keep every chunk id a failed flush sent, cap only the folds

Past four failed flushes over one base the handle stopped recording what a
later flush sent. If that flush was stored with its answer lost, a truncate
of its chunks was refused as a peer's write and kept failing after the
filer came back. The ids now go into one set shared by the base's marks,
each kept once and never copied, until the base moves. Only the folds stay
capped: a stored manifest past the cap is read when a refused merge cannot
place it.

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

* mount: fail a flush over a peer's chunk change unless -concurrentWriteMerge

A content flush refused because another mount committed first used to
merge the handle's writes onto the stored entry. That merge now runs
only with the new -concurrentWriteMerge mount option (off by default).
By default a stored chunk change that neither the base nor the handle
holds fails the flush with EIO, and a peer's chunk event no longer
rebases a dirty handle. Attribute-only changes and the handle's own
commits (a lost answer, its own truncate) still merge.

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

* mount: recognize the shortened references a failed flush sent

A truncate shrinks a base chunk in place, keeping its file id. A failed
flush that may have stored such a reference recorded only file ids base
lacks, so a later truncate saw its own stored reference as a peer's
change and failed with EIO by default.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:34:30 -08:00
Chris LuandClaude Opus 5.5 a963c1309c worker: purge the filer metadata log from a lifecycle job that keeps it past every TTL (#13101)
* worker: share the one-filer-per-store selection with other filer jobs

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

* worker: add a meta_log_purge job that keeps the log past every TTL

The job deletes whole metadata log days once per filer store, keeping
every day that the longest filer.conf TTL, the longest S3 lifecycle rule,
a registered retention floor or a running replay job's cursor still
needs. A floor input that cannot be read stops the run before anything
is deleted.

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

* worker: register meta_log_purge in the lifecycle lane

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

* maintenance: stop purging the metadata log from the default scripts

The meta_log_purge job now deletes old log days, keeping what TTLs,
lifecycle rules and replay jobs still need. fs.log.purge stays for
manual use.

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

* worker: let an idle filer_ttl rule's read position release the log

filer_ttl no longer needs events up to read_ns, and an idle rule keeps an
old ts_ns while read_ns advances, so the floor follows the later of the
two.

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

* worker: cap min_retention_days so a huge value cannot overflow

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

* worker: show the min_retention_days limit in the admin form

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

* worker: give a registered retention floor the store's filer client

A floor that only gets a context cannot tell which cluster or store it
answers for, so it cannot ask that cluster's master or read the store's
own settings. Pass the filer client the job already holds.

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

* worker: keep the log an unfinished lifecycle walk will replay

A cold-start or recovery walk that resumes across runs rewinds its
shard cursor to the walk's start minus the longest lifecycle TTL once it
completes. Until then only its walk checkpoint records that start, so a
walk running for more than a day let the purge delete the creation
events the rewound replay reads. A checkpoint with buckets done or
partly walked now holds the floor at started_ns minus that TTL.

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

* worker: hold the walk start until the checkpoint goes stale

A walk clears its checkpoint in finish() before each of its shards saves
the rewound cursor, so a purge scan that read the old shard cursor and
then the cleared checkpoint saw neither. A cleared checkpoint keeps
started_ns, so every live checkpoint now holds the floor at its start
minus the longest lifecycle TTL. A finished one stops holding once it
has not been saved for cursorStaleAfter.

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

* worker: read walk checkpoints before the shard cursors they rewind

A purge scan that read a shard cursor, then a checkpoint that a later
walk had already replaced, saw neither the earlier walk's hold nor the
rewind its shards saved. A walk replaces its checkpoint only after the
previous walk's rewind is on disk, so reading the checkpoints first
always sees one of the two.

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

* lifecycle: save a fresh walk's checkpoint at its first progress

A walk that progressed during its first save interval and then stalled
for more than a day had no checkpoint on disk, so the metadata log purge
saw nothing holding the days its completion replays. A fresh walk now
saves on its first finished entry or bucket; a resumed walk already has
its record on disk and keeps the interval.

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

* lifecycle: rewrite an unchanged shard cursor so its mtime stays fresh

A shard stuck on RETRY_LATER saved identical bytes each pass, and
SaveInsideFiler skips identical content, so the file's mtime aged past
the meta log purge's staleness cutoff while the shard still needed it.

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

* worker: keep the log day a reader from the cursor lists first

Log files are named for their flush start, so a file from just before
midnight holds events after a cursor just past it. The reader backs off
one flush interval before choosing its first day; the purge now does too.

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

* worker: stop the meta log purge on an unreadable lifecycle policy

LoadCompileInputs reports a bucket whose lifecycle XML does not parse
separately from its error, so the purge used the shorter floors and
deleted days that bucket's rules may need once the policy is fixed.

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

* worker: read shard cursors with the replay's loader in the meta log purge

A shard cursor the replay refuses, such as an empty object, decoded as
a zero position and released the purge; it now stops the run instead.

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

* worker: saturate the meta log purge's TTL plus a day

A lifecycle TTL near the largest duration wrapped negative once a day
was added, so the purge fell back to the shorter floors; the walk hold
at started_ns minus that TTL likewise dropped below zero and was lost.

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

* worker: leave disabled lifecycle rules out of the meta log purge floor

AllActivePriorStates activates every compiled rule, so a disabled rule
still held the log for its TTL, and disabling it could not release it.

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

* worker: compute the meta log purge floor in SafeKeepFrom

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

* shell: fs.log.purge keeps the logs the meta log purge floor needs unless -force

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

* shell: run the fs.log.purge floor test without a master client

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:33:26 -08:00
3836311f8f filer: end a listing at a short page, and make every store fill its pages (#13105)
* filer: end a listing at a short page from a store that fills its pages

ListEntries read a directory a page at a time and stopped at the first
empty page, so every listing the caller's limit did not cut ended with
one more scan of the store, from the last name on, that returned
nothing: two scans for a directory smaller than a page.

A page that comes back short of its limit now ends the listing when the
store says it fills its pages (the new optional FullPageListingStore).
leveldb, leveldb2, leveldb3 and TiKV do: they iterate the directory's
keys until the limit is handed over or the keys end. A store that cuts a
page of names to the limit and then drops some (the Redis stores, for a
name whose entry is gone or expired) can end a page short with names
behind it; it does not declare the interface and is asked until a page
comes back empty, as before.

TiKV's listing swallowed an iterator error while it skipped the start
name or an expired entry, and ended the page there. It returns the error
now: a page that ends short must mean the keys ended.

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

* filer: see through the path translator for a store that fills its pages

A path-specific store is wrapped in FilerStorePathTranslator, which does not
implement FullPageListingStore, so its directories kept the extra empty scan.

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

* filer: keep the last listed name when a refill lists nothing

A page that lost entries to expiry is refilled from its last name. A refill
that found nothing returned an empty last name, so the next page of a store
that does not fill its pages started over at the top of the directory and
listed every entry again.

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

* filer: name the stores that fill their pages instead of an interface

A short list of store names in Filer.ListsFullPages replaces the
FullPageListingStore interface, the wrapper method and the per-store
declarations. A path translator reports its backend's name, so it needs
no unwrapping.

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

* foundationdb: read a listing in batches until it fills the page

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

* redis: fill a listing page past orphaned and expired members

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

* redis2: fill a listing page past orphaned and expired members

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

* mongodb: report a cursor error that ends a listing

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

* tarantool: fail a listing on a malformed reply

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

* filer: test the last listed name after a refill that lists nothing

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

* filer: end a listing at a short page from any store

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rocksdb: build the tests against the current NewFiler

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rocksdb: count only listed entries toward the page limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rocksdb: return the decode error instead of ending the listing

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-29 12:32:36 -08:00
Martin Lettry 5a9287642f filer: cap list snapshots at the peers' delivery watermark (#13109)
A listing's snapshot only accounted for this filer's in-flight writes. A peer on the same store can have stamped a write below it that is not committed yet; the listing misses it and the client drops its event as already listed, leaving a stale entry (a mount reads a just-closed file as empty) until the next listing.
2026-11-29 11:31:30 -08:00
f9b494c576 filer, s3: give an entry without chunks the ETag of its inline content (#13106)
* filer, s3: give an entry without chunks the ETag of its inline content

A file written through a mount stores no MD5. With no chunks either (an
empty file, or a small one kept inline) S3 answered HEAD, GET and
listings with an empty ETag, and the filer's HTTP API with the chunk
form for zero chunks, "d41d8cd98f00b204e9800998ecf8427e-0". Both now
answer with the MD5 of the inline content, which for an empty file is
what AWS gives an empty object and what the same file gets once it is
written through S3.

An entry whose size reaches past its inline content (a hole that no
chunk covers) keeps the ETag it had.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: match If-Match on an entry without chunks against its inline-content ETag

The gateway now answers the MD5 of the inline bytes for an entry with no
stored MD5 and no chunks; the filer's conditional check still saw an empty
ETag, so a PUT with If-Match set to the ETag HEAD returned failed with 412.

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-29 10:32:38 -08:00
db0ec9e9b3 filer: count and time the gRPC requests by method (#13107)
* filer: count and time the gRPC requests by method

The filer's request metrics cover its HTTP API. The mounts and the S3
gateway reach it over gRPC, so on a cluster used through them the filer
reported its store operations and nothing about the requests behind
them: how many lookups, creates, renames or listings arrive, how long
each kind takes, how many end in an error.

Two metrics for the gRPC port, filled by a unary and a stream
interceptor: SeaweedFS_filer_grpc_request_total{method, code} and
SeaweedFS_filer_grpc_request_seconds{method}. A stream is counted when
it ends, and timed unless the client holds it open (a subscription, a
client stream). A lookup that finds nothing returns ErrNotFound without
a status; it is labelled NotFound rather than Unknown.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: label a call ending in its context's error as gRPC reports it

A handler that returns ctx.Err() reaches the client as Canceled or
DeadlineExceeded; status.Code labelled it Unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: count a health watch without timing it

grpc.health.v1.Health/Watch stays open until the client leaves, so its
duration is the connection's lifetime, like a subscription's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* metrics: dashboard panels for the filer's gRPC requests

Calls, errors by code, and p99/p50 durations by method, in the Filer row.

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-29 10:26:52 -08:00
Chris LuandClaude Opus 5.5 207aa69a9d filer: keep the metadata log in its own collection, with room reserved for it (#13102)
* filer: grow the metadata log collection on its own, fall back when it is full

metaLog.volumeGrowthCount (default 2) is sent with assigns into the
metadata log collection, so it grows by a few volumes instead of the
master's default growth. When that collection cannot take the piece, the
assign falls back to the collection the log uses without the override, so
a full cluster does not stall the log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the metadata log in its own collection by default

metaLog.collection now defaults to filer-meta, so purging old log days
empties whole volumes instead of leaving log chunks scattered across the
default collection's volumes. Setting it to "" keeps the log in the
filer's -collection as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: default -max to 10 to leave room for the metadata log collection

The default collection still grows by 7 volumes; the extra slots keep
the filer's metadata log collection (2 volumes by default) from taking
them. Go and Rust volume servers share the new default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: bound the meta log collection's share of the assign budget

A meta log collection that cannot grow (for example a replication the
cluster cannot place) keeps answering with retryable errors, so the
first assign used the whole shared budget and the fallback was never
tried. Give it 10s, then fall back, and skip it for a minute after a
failure instead of waiting on it at every flush.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: name the default meta log collection so no bucket maps to it

A bucket named filer-meta mapped to the same collection, and deleting
it from the admin page or weed shell drops the collection directly at
the master, taking the metadata log with it. Bucket names cannot
contain "_", and filer group buckets map to "<group>_<bucket>".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: clear the meta log overrides after the viper test

Setting the collection back to its default value kept an explicit
override, so the defaults test passed even without the SetDefault.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: retry the meta log collection once its fallback also fails

The pause after a failed meta collection assign kept pieces on the shared
collection for a full minute even when that assign failed too, so meta
volumes that finished growing stayed unused while every flush failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: pick a default meta log collection no grouped bucket maps to

Filer group "_filer" with bucket "meta" maps to "_filer_meta". The
default now keeps its only "_" in front, and the test checks every
group and bucket split of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: default the meta log collection to _meta

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the default meta log collection on bucket delete

A filer that logs elsewhere did not treat _meta as reserved, so deleting a
bucket a storage rule maps to _meta dropped the collection other filers
write their logs to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 10:01:16 -08:00
036d1117d2 fix(s3api): refuse a "dir/" PUT body larger than a directory marker holds (#13104)
* s3api: refuse a "dir/" PUT body larger than a directory marker holds
A key ending in "/" whose body had no Content-Length took the marker
branch, was read whole into memory and stored inline in the directory
entry. One declaring more than 1024 bytes took the regular path, which
wrote it to the object "dir/dir".
Both now get EntityTooLarge: a declared length is checked before the
body is read, an unknown one is read at most 1025 bytes. An aws-chunked
body counts by its decoded length.

* s3api: size an aws-chunked "dir/" body without a decoded length as unknown

Without X-Amz-Decoded-Content-Length the marker check fell back to the
encoded Content-Length, whose chunk framing pushed a marker of up to 1024
bytes past the limit. Such a body is now read through the limit instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep a "dir/" body past a marker as a version in a versioned bucket

A versioning-enabled bucket stores a trailing-slash key larger than a
marker as a versioned object under its .versions directory, so refusing
it broke that write. Only the unversioned and suspended paths, which
would land on "dir/dir", refuse it now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck a large "dir/" PUT against the versioning state its write uses

The size check and the write path each read the versioning state, so
versioning suspended in between sent the body to the suspended path,
which writes "dir/dir".

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-29 09:22:35 -08:00
Chris LuandClaude Opus 5.5 7092edfb06 webhook: keep the bearer token on the configured endpoint's host (#13103)
* webhook: send the bearer token only to the configured endpoint's host

A redirect to another host or port, or from https to http, now gets the
request without the Authorization header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webhook: test the token scope across redirects

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webhook: compare effective ports when scoping the token

An omitted default port and an explicit :443 or :80 are the same
endpoint; http on port 80 upgrading to https on 443 keeps the token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:17:34 -08:00
Chris LuandClaude Opus 5.5 4ff3147ee5 worker: filer_ttl job removes expired rows from stores without native TTL (#13084)
* worker: add a filer_ttl job that walks filer.conf TTL paths

A filer store without native TTL keeps the rows of expired entries until
something looks them up or lists their directory. The job lists every
TTL path subtree once per filer store, so the filer drops the expired
rows it meets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: register the filer_ttl job in the lifecycle lane

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: re-check an expired entry under its path lock before a listing deletes it

A listing deleted the expired entries it collected by path after the page
was read, so a write that replaced one in between lost its new row. The
delete now re-reads the row under the lock writers take, and in one
conflict-checked transaction on stores that refuse a commit over another
writer's change; anything but a still-expired row is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: read each filer store's own filer.conf, chunk-backed included

Filers with separate stores keep separate filer.conf files, so one
filer's rules could hide another store's TTL paths. A config stored in
chunks read as empty. An unreadable config now fails the detection
instead of reading as no rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* command: count filer_ttl among the mini default job types

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: resume an unfinished filer_ttl walk from its checkpoint

The walk position is saved in the job's filer store every 30s and at
the first failure, keyed by store signature, and cleared when a pass
completes. The next run skips the prefixes and subtrees already walked,
unless the TTL prefix set changed or the pass is over 7 days old.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: save the filer_ttl checkpoint as soon as a walk fails

The first failure froze the checkpoint but only the end of the run saved it,
so a worker killed while walking later prefixes lost it. stop now saves it at
once; the end of the run saves again only if that save failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: keep a path TTL rule from expiring the filer_ttl checkpoint

A filer.conf TTL rule over /etc/ gave the checkpoint that rule's TTL, so an
interrupted pass could lose its record long before checkpointMaxAge. The
checkpoint is now written with its own TTL of checkpointMaxAge, which the
filer keeps instead of the rule's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: remove a filer_ttl checkpoint the new pass will not resume from

An overwrite keeps the stored entry's Crtime, and the checkpoint's TTL counts
from it, so a pass that replaced a rejected record could lose its own record
before checkpointMaxAge. load now deletes a record it rejects, and the new
pass creates a fresh one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: expire filer_ttl entries from metadata events per TTL rule

Each run replays every filer.conf TTL rule's metadata events from that
rule's cursor up to the run start, and looks up each entry whose TTL has
passed so the filer removes its row. The first entry not yet due holds the
rule's cursor, so a later run replays it. A rule without a cursor, or
whose TTL changed, is listed once to reach rows older than its replay
window. The periodic full walk and its checkpoint are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: re-check an S3-expired entry under its path lock before a listing deletes it

A listing deleted an S3-expired object by the row it had read, so an upload
that replaced it after the page was read was removed. The delete now re-reads
the row under the path lock and removes it only if it is still S3-expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: remove an expired row a lookup meets in a conflict-checked transaction

A lookup that met an expired row deleted it by path, so a replacement written
through another filer between the read and the delete was lost, even on
stores that refuse conflicting commits; a failed delete was hidden behind not
found. The lookup now re-reads and deletes through deleteIfExpired and returns
the delete error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: keep a failed filer_ttl lookup that ties a done event

When the first event at a timestamp was done and the second one's lookup
failed, the cursor already stood at that timestamp, so the retry subscribed
after it and skipped the failed event. A failed lookup now holds the cursor
below a tie, as a waiting entry does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: hold a filer_ttl event whose entry the filer still serves

A lookup that returned the live entry counted as done, so when the worker's
clock ran ahead of the filer's near the deadline the event was skipped and
the row stayed. An entry the filer still serves with the same deadline now
holds the cursor like one not yet due.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: keep a path TTL rule from expiring the filer_ttl cursors

The cursors were written without a TTL, so a filer.conf TTL rule covering
/etc/seaweedfs/filer_ttl gave them the rule's TTL and every rule was listed
again once they expired. When a rule covers them they are now written with a
TTL of their own, which the filer keeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: list a filer_ttl rule again for a live entry its replay cannot reach

A new rule nested under a longer one started its replay one TTL back, so a
live entry the enclosing rule had stamped with its longer TTL, written before
that, was in neither rule's replay: the nested rule now owns it and the
enclosing rule skips it. The listing of a new rule now records the earliest
deadline of such entries, and the rule is listed again then.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: hand a removed filer_ttl rule's replay to the rule enclosing it

When a nested rule was removed, its entries became the enclosing rule's, but
that rule's cursor could already be past their events, so they were never
replayed. The enclosing rule now replays from the earlier of both cursors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: list a filer_ttl rule whose unfinished events the filer no longer keeps

When fs.log.purge removed the event of an entry still waiting for its TTL,
the rule's cursor matched, so the rule was never listed and the replay never
met the entry again. A rule whose cursor is older than the oldest kept
metadata log is now listed, and its cursor moves to that log. The cursor also
records how far a replay read with nothing left waiting, so a quiet rule is
not listed just because old logs were purged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: leave S3 lifecycle expiry to the s3_lifecycle job in filer_ttl

An entry whose TTL an S3 lifecycle rule set carries the S3 expiry flag;
s3_lifecycle evaluates and removes it. filer_ttl no longer looks such
entries up, and their deadline no longer holds a TTL rule's cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:20:03 -08:00
github-actions[bot] 0ea67a4438 docs: regenerate star history chart 2026-11-29 00:36:56 +00:00
Chris LuandClaude Opus 5.5 663af6fccb mount: review fixes for the metadata follow shutdown (on top of #13092) (#13097)
* mount: drop the issue number from the shutdown test comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: end the filer walk when the consumer stopped following

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: end the follow when a retried event reports a stop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check the subscriber is gone before the late event can end it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: never retry a filer call whose consumer stopped following

The walk already stopped on pb.ErrStopFollowing, but RetryOnError still
classified the wrapped error by its cause, so a transport-looking cause
reran the whole filer walk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: keep the cursor behind an event whose retry the follow ended

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: close the meta cache after the follow-cancel test joins it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:10:26 -08:00
Konstantin Lebedevandwhitefox 63ab6c6190 mount: stop the metadata follow before closing the meta cache (#13092)
* test(mount): reproduce the #5289 mount abort on a late metadata event

A metadata event that arrives after metaCache.Shutdown() reaches
glog.Fatalf through FatalOnError, so the mount dumps every goroutine and
exits 255 instead of unmounting cleanly — the signature reported in
issue #5289, still reachable on current master.

The subscriber has no way to stop: its context is rooted at
context.Background() and util.RetryUntil always retries, while unmount
closes the cache underneath it.

glog.Fatalf cannot be intercepted from another package (glog's
logExitFunc is unexported), so the reproduction runs the mount in a child
process and reads its exit code.

* mount,pb: stop following metadata when the cache closes

The mount follows metadata with FatalOnError, so an event that arrives
after metaCache.Shutdown() — which unmount guarantees, since the
subscriber is never stopped — was logged as a fatal and aborted the
process with a goroutine dump.

Report a closed cache as pb.ErrStopFollowing, a class the follow loop
ends on instead of routing through the per-event error modes. It is not
a failed event but the end of the subscription: no later event can land
either. SubscribeMetaEvents then leaves its retry loop rather than
reconnecting onto a store that no longer exists.

Also export the meta_cache sentinel as ErrClosed so consumers can tell a
closed cache from a storage failure.

* mount: end the metadata follow before closing the meta cache

The subscription goroutine had no owner: its context was rooted at
context.Background() and util.RetryUntil retried forever, while unmount
closed the cache underneath it. Every unmount left a window in which a
filer event landed on a closed store, and the mount survived it only
because the previous commit demoted that error.

Give the follow a context the mount owns, and stop it — cancel, then
join — before metaCache.Shutdown() in both teardown paths. MetadataFollowOption
takes a ParentContext so cancelling the caller ends the stream, which is
the ordering the filer already got in #11363 and #11663; the mount had no
equivalent.

Verified that the new assertion catches the ordering on its own: making
stopMetadataFollow a no-op fails it with the subscriber still running,
even with the fatal path already demoted.

* mount,pb: make a cancelled follow a stop, and cover the new seams

Review findings on the previous commits:

Cancelling the follow context surfaced as a bare gRPC Canceled, which
matched neither terminal condition, so every clean unmount logged an
ERROR, ran the retry callback — which wipes every cached listing on the
assumption that events were missed — and slept a second before the loop
stopped itself. Test the context instead of the error text.

Also assert the two new weed/pb seams where they are defined rather than
only through a mount exit code: ErrStopFollowing ends the stream without
reaching the per-event error modes and leaves the cursor behind the
event, and a cancelled ParentContext ends the stream. Publishing the
cancel handle and bumping the WaitGroup happen under one lock, so a
start racing a stop cannot let the join report success too early.

All four new tests were mutation-checked: dropping the early return,
ignoring ParentContext, removing stopMetadataFollow from ClearCacheDir,
and making stopMetadataFollow a no-op each fail their own test.

---------

Co-authored-by: whitefox <whitefox@mayflower.work>
2026-11-28 16:04:59 -08:00
Chris LuandClaude Opus 5.5 a7cc8fb767 filer, docs: 503 in the upload wait flag help; Yandex restart after a token refresh (#13096)
* filer: flag help names the 503 an upload gets after the wait

The filer answers an upload that found no slot within
-inflightUploadDataTimeout with 503 and Retry-After: 1, not 429.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: a restart after a Yandex token refresh may need a new token

The client keeps the refresh token Yandex returns in memory only, and
Yandex does not say whether the stored one survives the rotation, so the
doc no longer promises that a restart keeps working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:34:59 -08:00
ef0967bead filer: read the entry path once per write (#13090)
* filer: read the entry path once per write

A create looks the path up to decide what it makes of the entry: the inode and
crtime to keep, the chunks the write leaves behind, the old side of the metadata
event. The store wrapper looked the same path up again, in
handleUpdateToHardLinks, to learn the hard link the name carried before. Both
reads happen under the same per-path lock, a moment apart, and for a file written
without a hard link the second one decides nothing at all: its result is
discarded. An overwrite pays for it twice over, because that read decodes the row
being replaced -- gunzip included above CountEntryChunksForGzip -- and it is the
row the create already holds.

Neither read shows up as a second find in the store metrics: the wrapper's goes
to the actual store, and FilerStoreCounter counts only FilerStoreWrapper.FindEntry.

The wrapper now takes the caller's word. InsertEntryReplaces and
UpdateEntryReplaces carry the entry a caller read to handleUpdateToHardLinks,
which keeps to it instead of reading the path again. An insert whose lookup found
the path empty goes the way #13006 opened with InsertEntryKnownAbsent, which
rename alone used.

Which word may be taken is the delicate part, so Filer.findEntry reports whether
its answer is what the store holds at the path:

- a lazy fetch from a remote mount serves an object the store does not have and
  writes nothing to it, so it says nothing about the row there;
- inside a store transaction a lookup hides an expired S3 entry whose row the
  transaction keeps until the commit, and a write replacing it still owes that
  entry its hard link -- which is why FindEntryForOverwrite exists;
- where the expiry check deleted the row, the delete dropped its link already, so
  an answer of "empty" is honest.

The write also reads the path itself whenever there is a link to take off, for
two reasons. A file with a hard link has its record changed again when the store
refused a commit (changeLinkRecord runs its change up to linkRecordAttempts
times), and each run must judge the name as the store holds it by then. And a row
that carries a link is the row whose link this write drops: plain creates are not
routed to the write owner, so another filer may have replaced the same name
already and dropped that link, and dropping it twice deletes the record under the
file's remaining names. What is trusted is the case with nothing to decide --
no link on either side -- which is an ordinary file write, since a mount makes a
link id only when a file is linked or copied.

The HTTP append path read the entry three times: once to merge with it, once to
prove it had not changed while the chunks were uploaded, and once in the create.
The create takes the recheck's entry now.

A 20-chunk entry on leveldb2 goes from 343 to 286 allocs/op and from 44.6 to
38.3 KiB/op per overwrite, the difference being the decode of the replaced row.
Where the store is reached over the network, the read saved is a round trip per
write.

Tests count the reads one write makes at the store, pin that a dropped link is
dropped once against a row another filer has already replaced, and keep the
create using the entry it is handed. #9645's own guard expected the create's
lookup to be what separates passing existing from passing nil; both are one read
now, so it requires one read either way and checks the crtime came from the entry
passed in.

Issue #5067.

Review of the first version caught one more case. The known-absent shortcut must
not take an entry that carries a link: InsertEntryKnownAbsent counts the name as
joining without reading it, so another filer storing that name for the same link
between this lookup and the write would have it counted twice, and the count
would run one above the names. The regular insert reads the name inside the
change of the record. CreateEntry and ReplaceFileForRename keep the write's own
read for a linked entry; TestNewLinkedNameStillReadsThePath pins it.

* filer: drop issue numbers from the write-read test comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: say a plain-over-plain write can miss a link stored after the read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: whitefox <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-28 15:33:51 -08:00
Chris LuandClaude Opus 5.5 e7cbfdcc44 s3: blame no filer for a deadline gRPC reports before ctx.Err() (#13098)
The filer walk told the caller's expiry apart from a filer failure by
ctx.Err() alone. A server-side DeadlineExceeded can reach the client
before the context's own timer runs, so the walk recorded a failure
against each filer and moved on with no budget left, the same race
LookupVolumeIds already guards against.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:31:57 -08:00
5b7e2d9e9e fix: retain released lock version watermarks (#13083)
* fix: retain released lock version watermarks

* fix(lock_manager): scope release records to lease identities

Keep a stable acquisition ID in opaque renewal tokens so release history cannot reject a valid lease from a different primary when generation counters overlap. Preserve earlier releases across new acquisitions and ownership eviction.

Carry the maximum lease expiry with releases, prevent renewals from shortening that bound, reject expired inserts, and reclaim release records after expiry. Track replication and handoff before sending copies so local-only leases need no release records.

Add regressions for fresh-primary failover, equal and lower generation counters, reordered releases and renewals, bounded retention, local-only workloads, ownership eviction, legacy release metadata, and gRPC release handling.

* lock_manager: name the release replay tests after the behavior they check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(lock_manager): serialize lease handoff with local mutations

Hold per-key mutation admission through a fresh lease snapshot, the transfer RPC, and source demotion or removal. A release that wins first suppresses the transfer; a release arriving during handoff waits and is forwarded to the new primary afterward.

Keep incoming replication outside the gate to avoid callback cycles. Retain source authority on transfer errors and apply transfer completion only to the lease that was sent.

Add real gRPC regressions for releases during both handoff branches and replay after release, plus coverage for fresh snapshots, transfer errors, unrelated keys, and replacement leases.

* fix(lock_manager): retry handoffs without retaining renewal authority

Deliver a source-held lease to the current owner before forwarding renewal or unlock. Freeze local authority before sending a transfer, including when the receiver may have committed despite an RPC error. Retry without requiring a membership change, with backoff and shutdown cancellation.

Recheck ownership after a background handoff and preserve the copy until the latest owner receives it. Replicate the effective installed expiry instead of a shorter transfer input.

Replace timing assumptions with a same-key admission contention hook. Cover pre-handoff releases, lost acknowledgements, retry cleanup, owner changes, and effective expiry. Document why identityless legacy releases cannot safely delete slash-format leases with overlapping generation counters.

* test(filer): set up DLM handoff before the peer lock transfer check

Ring-change transfers now go through Dlm.TransferFn, which
SetupDlmReplication installs; without it the lock stays pending on the
old filer and the peer-auth transfer test cannot see it move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(lock_manager): bound the handoff and unlock completion waits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(filer): give the handoff retry expiry subtest a one-second lease

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(lock_manager): serve lock and unlock here when a handoff ends with this node as primary

transferToOwnerLocked now returns the primary it observed after the
handoff. LockWithTimeout and Unlock redirected to the primary read before
the transfer, so a ring that moved back during the handoff sent the client
away from the node that holds the lease.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(lock_manager): bound the admission probes in the handoff tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(filer): keep the holder's renew token while its lock handoff is pending

A failed transfer RPC or a frozen lease answered the lock request with an
error and an empty RenewToken. The client treats that as a rejection and
drops its token, so it can no longer renew the lease once the handoff
completes. Report transfer failures as LockHandoffPending and echo the
caller's token for that error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(lock_manager): return lease expiry from Lock, Unlock and InsertLock

The DLM was the only production caller of these methods and used private
twins (lockWithExpiry, unlock, insertLock) to get the effective expiry.
Return it from the public methods instead and drop the twins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(lock_manager): share the copy acceptance checks between InsertLock and InsertBackupLock

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(lock_manager): drive handoff tests through TransferLockToOwner

TransferLock and its helpers were only reachable from tests. Remove them
so the tests exercise the production handoff path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(lock_manager): share the routing and handoff prologue of LockWithTimeout and Unlock

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Master <Master@node0.8m510.lpad-pg0.utah.cloudlab.us>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:31:06 -08:00
Chris LuandClaude Opus 5.5 889af96779 mount: store a truncate through an open handle before answering (#13089)
* mount: store a truncate through an open handle before answering

SetAttr with a new size and an open handle only marked the handle dirty,
so the size reached the filer at the next flush or release. A mount that
died before then brought the old size and data back, and an NFS export
answered SETATTR, which no COMMIT follows, with a size it had not stored.
Flush the handle once the entry locks are released, as a truncate
without a handle saves the entry. The writeback cache still defers it,
except under an NFS export.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test that a truncate through an open handle is stored

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: refuse a truncate up past the quota before the file grows

The size is now stored before SetAttr answers, so a growth the quota
cannot take was installed and charged, then refused by the flush,
leaving the grown size on the handle. Check the growth first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: compare a truncate's growth with the quota headroom

The used size, the uncommitted writes and the growth were summed in
int64, so a truncate up to near 2^63 wrapped the sum negative and passed
the check. Take the growth as uint64 and compare it with what is left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:53:42 -08:00
Chris LuandClaude Opus 5.5 6b2ad112a8 volume: check the collection name in handlers that build file paths from it (#13087)
* volume: check the collection name in handlers that build file paths from it

AllocateVolume, VolumeMount, VolumeCopy and the EC rebuild, copy,
delete, mount and to-volume handlers joined the request collection into
volume file paths, so a collection such as "../x" reached files outside
the volume directory. They now apply checkVolumeCollection, as CopyFile
and ReceiveFile already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: check the collection name in handlers that build file paths from it

Mirrors the Go volume server: allocate_volume, volume_mount, volume_copy
and the EC rebuild, copy, delete, mount and to-volume handlers apply
check_volume_collection, as copy_file and receive_file already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check the source's collection before VolumeCopy builds paths from it

VolumeCopy names the destination files after the collection the source
reports in ReadVolumeFileStatus, so that value needs the same check as
the request's collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: check the source's collection before volume_copy builds paths from it

Mirrors the Go VolumeCopy: the collection the source reports in
ReadVolumeFileStatus names the destination files, so it gets
check_volume_collection too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: stub the source in the VolumeCopy source collection test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: keep check_volume_collection's doc comment as on master

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:50:53 -08:00
Chris LuandClaude Opus 5.5 16412c374a test(filer): wait for the fake master's volume location in the manifest reuse tests (#13086)
The master client marks a master current as soon as the stream opens and
applies the first VolumeLocation afterwards, so GetLocations right after
GetMaster can miss volume 1 on a loaded runner.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:49:46 -08:00
Chris LuandClaude Opus 5.5 efcee4a186 test(volume_server): wait out a server's disk I/O before calling its SIGINT exit a hang (#13085)
* test(volume_server): wait out a server's disk I/O before calling its SIGINT exit a hang

stopProcess gave every server 10s to exit after SIGINT. On a CI runner
with a busy disk, the fsync in volume close can take longer than that:
the server is in uninterruptible sleep, not hung. Sample the server's
threads from /proc while waiting. Once one has been in D state, allow
up to a minute. A server that never touched the disk still fails at
10s, and the failure now lists its threads' states and wait channels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(volume_server): wait for the sleep child before checking its stop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(volume_server): reap the SIGINT-ignoring child if it never starts sleeping

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:29:59 -08:00
Chris LuandClaude Opus 5.5 e6aed012f8 filer: pass cutToSpan in the manifest reuse test (#13082)
ResolveChunkManifest gained a cutToSpan argument while this test was in
flight, so master stopped compiling weed/server. The test compares chunk
lists, so it resolves every referenced chunk.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:04:12 -08:00
Chris LuandClaude Opus 5.5 4cf028f683 grafana: show the first EC shard copy failure of each series (#13071)
* grafana: count the failure that creates an EC shard copy failure series

The EC shard copy failure counter exports a collection and reason pair
only once a copy fails, so rate() saw that first value as a baseline and
never showed it. The panel now shows failures per rate interval and adds
the earliest value of a series that did not exist one interval ago.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: count a new EC shard copy failure series from its last value

increase() extrapolates the increments of a series that appears inside
the window, and an instant offset selector loses an old series across a
scrape gap, so the panel could add a whole counter as new failures.
A series with no sample in the day before the window now shows its last
value; every other series shows increase().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: count the first EC shard copy failure after a restart

A restarted volume server exports a failure series again only at its first
failure, so when the same labels had a sample earlier in the day the window
held only the new counter's samples and increase() missed that failure. A
series whose lowest value in the window is below its last value before the
window has been reset since, and now shows its last value; a series back
from a scrape gap keeps its value and still uses increase().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:58:37 -08:00
a9fda6b50f filer clients: authenticate filer gRPC calls with per-call admin tokens (#13039)
* Add per-call filer authentication sources and pooled client wrappers

* Authenticate gateway filer calls with per-call admin tokens

* Authenticate shell admin and synchronization filer calls

* Authenticate workers MQ and remaining filer client paths

* Cache filer client signing keys and sign subscriptions with the shared key

Re-reading security.toml on every filer RPC cost about 125us against 8us for
signing. Keep the keys for up to a second, re-reading at once when a WEED_
override or the configuration directory changes. When the file exists but
cannot be read, keep the last keys read, else the startup keys, as
FilerAdminKeys does, so a process without a key stays tokenless. Metadata
subscriptions prefer the shared key, as filer peers do, because older filers
verify subscription admin tokens only with it.

* Authenticate admin-script, maintenance and filer.conf shell paths

Plugin worker admin scripts and master maintenance scripts build their own
shell options and carried no filer token source; fs.configure and
s3.bucket.quota.check read filer.conf without it.

* filer.cat: report a failed read; isolate key overrides in the admin-script test

filer.cat ignored the error from its filer call and exited successfully,
leaving a truncated -output file. Report the error and exit with failure.
The admin-script token test now clears the WEED_ signing-key overrides,
which take precedence over security.toml.

* security: refuse gRPC keys too short to sign; query engine uses client TLS

Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The
startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key,
and filer client token sources check the keys they read, so a reloaded or
per-endpoint security file with a short key is refused instead of
panicking when the next RPC signs.

The query engine's broker client dialed every master, filer and broker in
plaintext, so the admin token it now sends could cross the network in the
clear. It dials with the grpc.client TLS settings instead, and weed-sql
loads security.toml as weed-db does.

* security: per-endpoint admin tokens ignore WEED_ key overrides

FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and
WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with
-a.security and -b.security signed both clusters' admin tokens with the
one key, handing each cluster a token valid on the other. A per-endpoint
file now supplies its own keys only.

* weed-sql, weed-db: refuse to start on an unreadable security.toml

Both only warned when security.toml was present but could not be read or
parsed. They then dialed without the grpc.client TLS settings while the
filer token source could still sign admin tokens from WEED_ environment
keys, so the tokens could travel in plaintext. They now exit with an
error that does not quote the file; a missing file is still fine.

* pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients

Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the
existing helpers instead of keeping two names for each. Callers without a
token source pass nil.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: return the read error from ReadConfiguration

Fold ReadConfigurationWithError into ReadConfiguration. The error is
returned and not logged, since parser errors can quote values; the
existing reload callers already warn when no file was read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: keep the test-only filerAdminToken helper in the test

It had no production caller. The test helper now resolves keys through
filerClientKeysFrom, as the token sources do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: read security.toml once in LoadSecurityConfigurationOrError

It validated the file, then merged it with a second read whose failure
was ignored and whose parser error was logged. It now merges with one
read and logs nothing from the parser. Viper's search also treats a
directory the process cannot search as holding no file; a candidate
that cannot be checked for lack of permission is now refused too.

* security: verify admin subscription tokens with the gRPC clock leeway

CheckGrpcMetadataSubscription checked admin tokens strictly, while unary
filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second
client admin tokens, a subscriber whose clock trailed the filer's by more
than ten seconds was refused with a matching key. It now takes the leeway,
and the filer passes its configured one. The leeway check moves from the
server package to security.IsFilerAdminTokenWithLeeway so both use it.

* util: start without security.toml only when every candidate is confirmed absent

A candidate whose check fails for any reason other than not existing,
such as a symlink loop, is refused like one the process cannot search.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:59 -08:00
f6b130f61c filer: keep a stored manifest when a commit lists its chunks flat (#13051)
* filer: keep a stored manifest when a commit lists its chunks flat

Since #12462 the filer folds a commit's small chunks into manifests
256 at a time, whichever client sent them. A client that keeps its own
chunk list sends every chunk it wrote on each flush and does not take
the folded list back. The Hadoop client is one: SeaweedOutputStream's
hflush and hsync send CreateEntry with the whole list, which the client
folds itself only past 1000 chunks. Once 256 small chunks have piled
up, each flush makes the filer fold the same chunks again into a new
manifest blob, and the manifest of the entry it replaces is deleted:
up to three manifests written and three deleted per flush.

cleanupChunks now puts back, after compacting the list and before
folding it, each manifest of the replaced entry whose chunks the list
holds flat and unchanged (filer.ReuseStoredManifests). The manifest
must span exactly the chunks it holds. A manifest the commit lists
itself, one that cannot be read, one with a chunk changed or missing,
and a hard-linked file's are left alone. MinusChunks counts the kept
manifests as listed, so the commit does not delete them.

That entry has to be the one the commit replaces and deletes against.
UpdateEntry already prepares its chunks under the path lock from
the entry it read there. CreateEntry folded before taking the lock;
it now prepares the chunks under the lock, after its precondition
checks, and reads the replaced entry there when the request has at
least 256 chunks.  filer.CreateEntry still deletes the chunks of the
replaced entry that the new list drops, which no longer include the
kept manifests.

TestCommitKeepsTheStoredManifestOfChunksListedFlat (create and update):
the second commit of the same list plus one chunk keeps the manifest,
writes no blob and queues nothing for deletion. It fails on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: take the replaced entry in cleanupChunks instead of a cleanupChunksReplacing twin

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: reuse a stored manifest only for its chunks listed in its order

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep the stored entry's manifests out of a refused update's cleanup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: do not reuse a manifest whose chunk ties with a chunk outside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: drop a pull request number from a reuse test comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: look up same-timestamp chunks by index in the manifest reuse overlap check

The tie check rescanned the whole commit for every candidate manifest,
so a 102,400-chunk commit with 400 matching manifests ran 40M map
lookups under the path lock. Index the commit's positions by
ModifiedTsNs once and check only the positions sharing a held chunk's
timestamp.

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-27 18:53:35 -08:00
Chris LuandClaude Opus 5.5 3880e7ee5a volume(rs): keep the needle_not_found doc comment on its function (#13070)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:13 -08:00
c7fc40c76c filer, mount: read a manifest's chunks only within its span (#13048)
* filer, mount: read a manifest's chunks only within its span

Until #13042, a truncate through a manifest only shortened the manifest
chunk; the chunks it holds stayed whole. Reads resolve those chunks at
their own offsets and sizes, so once such a file grows over the cut again
without writing it, by an extending truncate or a write past the end, the
cut bytes come back where zeros belong. #13042 keeps new truncates from
leaving such manifests, but files a mount truncated between #12462 and
#13042 still have them.

Reproduced with weed mount on a local cluster: a mount from before #13042
appends 700 lines with one close() each, so the first 256 fold into a
manifest, and truncates the file to 100 lines; a mount from current master
then extends it past its old end with ftruncate. The extended range read
8,580 bytes of the cut lines instead of zeros, through that mount and
through the filer.

Reads now cut each manifest's chunks to the manifest's span:
ResolveChunkManifestForRead, used by NonOverlappingVisibleIntervals (filer
and S3 streaming, WebDAV, the mount's merge reads), the S3 ranged reads and
the mount's peer reads, and ChunkGroup for the mount's reads. A manifest
made by MaybeManifestize spans its chunks exactly, so only shortened ones
change. ResolveChunkManifest still returns the chunks whole: MinusChunks,
deletions and the other chunk-list comparisons need every chunk a manifest
references, or the chunks past the cut would never be deleted.

* sw-client: read a manifest's chunks only within its span

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: read a manifest's chunks only within its span

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: drop PR numbers from the manifest span comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: fold ResolveChunkManifestForRead into ResolveChunkManifest

ResolveChunkManifest takes cutToSpan: the read paths pass true, the
deletion and chunk-list comparison paths pass false.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: cut manifests to their span when flattening an object's chunks

A full-object SSE GET, CopyObject and UploadPartCopy flatten the
source's manifests into a plain chunk list, which drops each manifest's
span, so the chunks a truncate left past a shortened manifest came back
as object data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: purge a volume.fsck path only for chunks within a manifest's span

A chunk past a shortened manifest's span is still referenced but never
read, so a missing volume under it loses nothing. The purge decision now
uses the span-cut chunks while the inventory keeps every reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: cut manifests to their span in fs.distribute_chunks

The entry is rewritten with the resolved chunks as a flat list or a new
manifest that spans them, so chunks past a shortened manifest's span
became readable again. The filer's update still deletes them, since it
compares against the old entry's uncut chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: verify only the chunks within a manifest's span in fs.verify

A chunk past a shortened manifest's span is never read, so a missing
needle under it failed the entry and, with -pruneEntries, deleted a file
whose readable bytes were intact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: mark the chunks past a manifest's span instead of allowing the visible ones

The purge gate now skips only the resolved chunks that the span cut drops,
so chunks that come from outside the manifests keep their purge behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: skip the purge for a missing past-span chunk on a listed volume

volume.fsck -findMissingChunksInFiler queued a path for deletion when a
listed volume's index lacked any chunk the uncut inventory recorded,
including a chunk past a shortened manifest's span that no read reaches.
Record those chunks per path during the filer walk and let only a missing
chunk within the span queue the purge. The path is still reported.

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-27 18:51:15 -08:00
c812a37c83 feat(grpc): serve grpc.health.v1 on every server, add health-check-only client certificates (#13049)
* feat(grpc): serve grpc.health.v1 on every server, add health-check-only client certificates

Every gRPC server built by pb.NewGrpcServer now answers the standard
grpc.health.v1.Health service, so blackbox_exporter's grpc prober,
grpc_health_probe and Kubernetes grpc probes can check SeaweedFS ports.
Check("") reports the server; Check(<service>) reports whether that
service is registered on the port.

grpc.health_check_commonNames lists client certificate common names that
pass the mTLS handshake on every component but may call only the health
service; any other RPC gets PermissionDenied. A monitoring probe can then
check the port and its certificate without a credential that opens the
whole gRPC API.

Fixes #5012

* seaweed-volume: serve grpc.health.v1 on the gRPC port

Mirrors pb.NewGrpcServer registering the health service on every Go
server: the whole server, the volume service and the health service
answer SERVING, other names NotFound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: confine grpc.health_check_commonNames to the health service

Mirrors the Go healthCheckOnlyTap: a client certificate whose common name
is on [grpc] health_check_commonNames passes the handshake even when
allowed_commonNames is set, and any RPC outside grpc.health.v1.Health is
refused with PermissionDenied. WEED_GRPC_HEALTH_CHECK_COMMONNAMES
overrides the key like the other WEED_GRPC_ settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: end health watches when the gRPC server shuts down

Graceful shutdown waits for open streams, so a client holding a health
Watch kept the volume server from reaching store close. Clearing the
reported statuses ends every Watch stream once the shutdown signal fires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: end health watches before gRPC graceful stop

GracefulStop waits on open streams, and Watch held its stream until the
client left, so a connected probe kept volume and admin worker shutdown
from finishing and made filer and S3 wait out their drain timeout.
StopHealthWatches ends those streams; every GracefulStop path calls it
first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* scaffold: point mTLS health probes at an exec probe

The built-in Kubernetes grpc probe sends no client certificate, so it
cannot pass an mTLS port; grpc_health_probe run as an exec probe can.

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-27 18:50:34 -08:00
Chris LuandClaude Opus 5.5 6c54935723 java client, hdfs3: authenticate to a filer that requires filer JWT or Basic Auth (#13053)
* java client: read security.toml without an [https.client] section

toml.getBoolean returns null for a missing key, so unboxing it threw a
NullPointerException in the static initializer and every FilerClient
failed with ExceptionInInitializerError when security.toml held only
other sections, such as [grpc] or [jwt.filer_signing].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: sign filer JWTs and hold [filer.basic_auth] credentials

FilerSecurityContext reads jwt.filer_signing.key, jwt.filer_signing.read.key
(with their expires_after_seconds, defaulting to 10 and 60 like the Go
clients) and [filer.basic_auth] from security.toml, with setters to set
them in code. getFilerAuthorizationHeaderValue returns the credential for a
request to the filer's HTTP port: an HS256 token for the access level,
minted like security.GenJwtForFilerServer, else the filer Basic Auth, else
the existing [basic_auth] value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: send the filer credential on filer-proxied chunk requests

With volume server access through the filer proxy, chunk reads and writes
address the filer's HTTP port, which checks the filer JWT or Basic Auth
before proxying. The write sent the AssignVolume token instead, which the
filer rejects with "wrong jwt", and reads sent no filer token. Send the
filer credential on proxy URLs only; direct and publicUrl volume requests
keep the volume token. With no filer credential configured, the old
headers are sent unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: take filer JWT keys and Basic Auth from the Hadoop configuration

fs.seaweed.filer.jwt.signing.key, fs.seaweed.filer.jwt.signing.read.key
(and their expires.after.seconds) and fs.seaweed.filer.basic.auth.user /
password override security.toml. The secrets are read with
Configuration.getPassword, so a Hadoop credential provider can hold them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: document a filer secured with JWT or Basic Auth

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: fail a chunk fetch that answers a non-2xx status

doFetchOneFullChunkData returned the response body whatever the status,
so a 401 "wrong jwt" or a 404 JSON error was taken as chunk data and
cached. Throw instead, so the fetch tries the next location and reports
the error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client, hdfs3: accept filer Basic Auth with an empty user

The filer turns Basic Auth on whenever the password is set, user empty or
not. The client dropped credentials without a user, so a password-only
filer refused every proxied chunk request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: point the secured filer docs at [https.client]

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client, hdfs3: keep filer credentials on each filer client

The filer JWT keys and [filer.basic_auth] lived in process-wide fields,
so a second filesystem with its own fs.seaweed.filer.* options replaced
the credentials of the first one, and a filesystem without options
inherited the previous overrides. Each FilerClient now copies the
security.toml values into its own FilerCredentials, and chunk reads and
uploads use the credentials of the client that issued them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: let each filer credential option override only its own value

A password-only or token-lifetime-only option in core-site.xml was
ignored or dropped the security.toml user and key. Each option now
replaces just the security.toml value it names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: show [https.client] for a secured filer and per-option overrides

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: note that [https.client] does not check the filer host name

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: check filer tokens against the configured key and lifetime

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: do not follow redirects on filer proxy chunk requests

HttpClient copies the request's Authorization header onto a followed
redirect, even to another origin, so a relayed 3xx would hand the filer
JWT or Basic credential to the redirect target. A 3xx now fails like any
other non-2xx answer and the read moves to the next location.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: close the filer client when credential options fail

A credential provider error or a malformed lifetime option threw out of
the store constructor after the client had opened its gRPC channels,
leaving them open on every failed initialization.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hdfs3: say the filer HTTP credentials apply only to filerProxy mode

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* java client: pick filer credentials by access mode and filer address

The proxy check matched any URL containing proxyChunkId=, so a volume
url or publicUrl carrying that text would receive the filer JWT or Basic
credential. Only filerProxy-mode URLs that start with this client's own
filer proxy prefix count as filer requests now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:50:04 -08:00
Yip Leo 50ac729a71 filer: fold only runs of small chunks that lie end to end (#13041)
* filer: fold only runs of small chunks that lie end to end

#12462 folds every chunk under 1 MiB into manifests, 256 at a time in
list order. Two things go wrong when those chunks are not plain appends:

- A manifest's chunks are not compacted again. A small chunk that a
  later write covers stays stored and referenced after the write hid it.
- weed mount's bloat check sums chunk sizes and counts a manifest by its
  span. A manifest over chunks that are not next to each other spans
  bytes other chunks hold, so the file looks bloated and the flush reads
  it back and stores it again, whole.

With weed mount on a local cluster, a writer that appends 300-byte
records and rewrites a 4 KiB header at the front after each one (open,
two pwrites, close): after 766 records the mount logged "2.0x chunk
bloat detected ... (2 chunks, 475684 stored vs 233896 content),
merging" and rewrote the file, and did it again at 2.5x (1164184 stored
vs 463396 content); 1,600 records cost two whole-file rewrites. Each
rewrite reads and stores the whole file, and the next one comes a few
hundred flushes later. Random small writes fold their overwritten pages
the same way.

Only small chunks that no other chunk overlaps now fold, and only in
runs that lie end to end, so a manifest spans exactly the bytes it
holds. Appends make such runs and fold as before. Chunks between
full-size ones, chunks that overlap others and chunks with a hole
between them stay flat, as they did before #12462. What is left of a
run stays flat until the run grows.

* filer: size the small-chunk fold's result by its input

CodeQL alert 446 (go/allocation-size-overflow) flagged the capacity
len(inputChunks)-len(folded)+len(manifests). It cannot overflow, but the
input's length bounds the result anyway: each manifest takes the place of
SmallChunkManifestBatch chunks.
2026-11-27 18:49:20 -08:00
Chris LuandClaude Opus 5.5 40a95a8ef5 admin: filter plugin jobs and activities by volume id (#13077)
* admin: keep the volume id on tracked plugin jobs

Volume-scoped jobs carry their volume in the volume_id parameter, but
the in-memory job list drops parameters, so nothing could select a
volume's jobs without reading every job detail file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: filter plugin jobs and activities by volume id

/api/plugin/jobs and /api/plugin/activities accept volume_id, applied
before the limit like the lane filter. Activities follow the tracked
jobs of that volume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: volume id filter on the plugin monitor

A Volume ID box next to the execution state filter narrows the queue,
execution jobs and activities to that volume's jobs, fetched with the
volume_id API filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep detection scans visible under the volume filter

Detection activities belong to no job, so the volume-filtered activity
window had none of them and the Detection Jobs table went empty. That
table now reads its own job-type window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: accept zero-padded volume ids in the monitor filter

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: drop a monitor refresh that finishes after a newer one

Two refreshes of the same scope can finish out of order; the older one
then replaced the newer rows, with empty lists when its volume-filtered
fetch failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep rows committed for the scope when a plugin monitor refresh fails

A failed request fell back to the rows captured when the refresh started,
so a refresh overlapping one that had already committed the new scope's
rows cleared them. Resolve the fallback when the refresh commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: validate the monitor volume id before fetching

Out-of-range ids went to the APIs and came back 400. The filter is now
applied only from a valid change event, so the periodic refresh no longer
reads a value still being typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: volume id filter on the job queue view

The queue renders the volume-scoped rows, but the only filter box sat on
the execution view, so an active filter was invisible and could not be
cleared there. Both views now carry a box kept in sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: reject unparsable volume id text instead of clearing the filter

A number input holding text like "1e" reports an empty value with
validity.badInput set; treat it as invalid rather than as a cleared box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:42:11 -08:00
Chris LuandClaude Opus 5.5 ec34160a1a master, admin: report the real last heartbeat time of volume servers (#13074)
* master: report each volume server's last heartbeat time

DataNode.LastSeen only moves when a volume server registers, so nothing
recorded when the master last heard from it. Stamp every processed
heartbeat and carry it in DataNodeInfo.last_heartbeat_ns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: show the master's last heartbeat time for volume servers

The volume server details reported the admin's own clock as the last
heartbeat. Use the time the master reports, and show unknown when the
master does not report one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: carry the last heartbeat time into the volume servers page

GetClusterVolumeServers builds its records from the master's volume list
without the topology conversion, so the details dialog showed unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:02:55 -08:00
Chris LuandClaude Opus 5.5 df98e9df3e admin: wait for the failed record in the worker-restart orphan test (#13079)
handleJobCompleted hands the completion to the dispatcher before it
updates the tracked job, so the test could read the record while it
still said assigned.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:57:38 -08:00
Chris LuandClaude Opus 5.5 2e81c0b7c0 filer: route a rename whose source misses locally to the write owner (#13064)
* filer.proto: mark a forwarded StreamRenameEntry with is_moved

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: send a rename whose source misses locally to the write owner

Exclusive and conditional creates are stored on the path's write owner. With
separate filer stores, a rename sent to another filer before it has replayed
the create found no source and failed, so a mount that flushed a deferred
create and renamed the file right after got EIO. Such a rename now goes to
the source's write owner, which moves the entry and whose events are relayed
to the caller, unless the owner runs on this filer's store. A forwarded
rename is applied only by the filer its own ring names as the owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: send an AtomicRenameEntry whose source misses locally to the write owner

The same race reaches the unary rename that S3, WebDAV, SFTP and fs.mv use:
an object or file created through the owner and renamed through another
filer before replication found no source. It is forwarded like the stream
rename, with is_moved bounding it to one hop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rename: report a missing source as ENOENT

A rename whose source is absent fails with the store's "no entry is found"
error, which neither the filer's errno mapping nor the mount's message
mapping recognized, so the client got EIO instead of ENOENT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.proto: report a forwarded AtomicRenameEntry's last event position

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: answer a forwarded rename once the owner's events are replayed here

The rename's target is stored on the owner only until this filer replays
it, so an unlink of that name sent here right after the rename would miss
it and report success. The owner now reports the log position of the
rename's last event, and the forwarding filer holds its answer (bounded)
until its stream from the owner has delivered that far.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse a forwarded no-replace rename over a target this filer has

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: wait for an owner this filer no longer follows before answering a forwarded rename

PeersCaughtUpTo counts an untracked peer as caught up. An owner whose
stream was down long enough to be dropped has replayed nothing here, so a
forwarded rename answered then could leave a follow-up unlink through this
filer missing the target. Require the owner to be tracked with a watermark
at or past the rename, still bounded by ownerEventsCatchUpCap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:54:48 -08:00
Chris LuandClaude Opus 5.5 96fd7fe6e2 volume: report mounted EC shards whose file on disk is gone, replaced or resized (#13069)
* volume: report mounted EC shards whose file on disk is gone, replaced or resized

Each EC heartbeat tick stats every mounted shard file and compares it with the
open descriptor: a missing path or a different file is a ghost, a size other
than the mounted one is stale_size. Mismatches are logged per shard and counted
in SeaweedFS_volumeServer_ec_shard_disk_mismatch{reason}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): report mounted EC shards whose file on disk is gone, replaced or resized

Mirror of the Go check: each EC heartbeat tick compares every mounted shard
with its file (missing or another inode = ghost, other size = stale_size),
warns per shard and sets SeaweedFS_volumeServer_ec_shard_disk_mismatch{reason}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* metrics: chart EC shards that disagree with their file on disk

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): tell a replaced EC shard file apart on non-unix hosts

Without inode numbers, compare the creation and modification times of the
path and of the open handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check mounted EC shards off the heartbeat loop

A stat stuck on a stalled disk no longer holds up heartbeats or shutdown; at
most one check runs at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): check mounted EC shards off the heartbeat loop

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): compare file ids to tell a replaced EC shard file apart on Windows

Timestamps can match on a replacement file. Use the volume serial and
file index from GetFileInformationByHandle there, and dev/inode on
unix, the same identity Go's os.SameFile compares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): copy mounted EC shard state out before checking the disk

The check held the store read guard across its file system calls, so a
stalled disk kept the guard and a waiting writer could then stall the
heartbeat's own read. Copy each shard's path, size and file id under
the guard and check them after it is released. The id is recorded when
the shard opens, so no extra handle is held for the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): run the EC shard disk check on a detached thread

Dropping the runtime waits for spawn_blocking tasks, so a stat stuck on
a hung disk could hold up shutdown. A plain thread is not waited on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): stat the EC shard path instead of opening it

A replacement the server cannot read failed the open and was never
counted as a ghost. Compare device, inode and length from the path's
metadata, as the Go side does with os.Stat; on Windows open it with no
access rights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): test the EC tick past a stalled disk check

The check thread start takes the check to run, so a test can stall one
after its snapshot and show that a writer still gets the store, the tick
still reports, and no second check starts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: keep VolumeServer int64 counters 8-byte aligned on 32-bit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:53:58 -08:00
Chris LuandClaude Opus 5.5 8ab78a9a06 s3: return part checksums in ListParts (#13076)
* s3: return part checksums in ListParts

UploadPart stores the part's checksum on the part entry and returns it,
but ListParts built each Part from the SDK type, which has no CRC64NVME
field, and never filled the checksum fields. List each part with its
stored checksum so a client can verify an uploaded part after losing the
UploadPart response.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: name the upload's checksum algorithm and type in ListParts

CreateMultipartUpload records the requested checksum algorithm and
type on the upload, but ListParts never reported them. Return both, as
AWS does, when the upload was created with a checksum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:52:47 -08:00
Chris LuandClaude Opus 5.5 2ce8b75b3f ci: refresh the apt index before installing musl and cross toolchains (#13075)
The runner image's package index can name versions the mirrors have
already dropped, so apt-get install fails with a 404 on the first
security update after the image was built.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:51:52 -08:00
Chris LuandClaude Opus 5.5 b53f6d4b5e admin: warn when more than one scheduler runs the same maintenance work (#13065)
* admin/maintenance: report whether the running manager queues a task type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: list the EC balancers that are active at the same time

The plugin ec_balance job, the legacy maintenance manager's ec_balance task
and an admin_script job that runs ec.balance -apply each plan shard moves
from the same topology without knowing about the others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: log a warning while more than one EC balancer is active

The check runs on the maintenance metrics tick and logs again only when the
set of active balancers changes. The legacy maintenance entry names the
admin.toml switch that turns it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: warn on the plugin pages when more than one EC balancer is active

The scheduler status API returns the active EC balancers, and the scheduler
banner on the plugin and lane pages lists them when there are two or more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/maintenance: count a task type only when a registered worker can run it

Only legacy maintenance workers pull tasks from the legacy queue. With plugin
workers alone, the queued ec_balance tasks never run, so they do not compete
with the plugin ec_balance job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: parse ec.balance apply flags like the flag package

A value counts only when strconv.ParseBool reads it as true, and a # token
ends the arguments, as it does for the shell command's flag parser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/maintenance: skip legacy workers past their heartbeat timeout

A disconnected worker keeps its queue record until the cleanup loop removes
it, so the capability check also requires a heartbeat within the worker
timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: count ec.balance only when its flags parse the way the command parses them

An invalid boolean in -apply or -force fails the whole command, the last
value of a flag wins, -force overrides -apply, and parsing stops at the
first non-flag argument.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: share ec.balance's flag set and report whether its arguments apply the plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: count an admin_script ec.balance only when ec.balance accepts its flags

Unknown flags and invalid values of any flag fail the command before it
can move shards, so they no longer count as an active balancer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell, plugin/worker: move admin_script command tokenizing into the shell package

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: split admin_script ec.balance arguments with the executor's tokenizer

A quoted value with spaces is one argument to ec.balance, so flags after it
are still seen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: report through one lookup whether a command's arguments change the cluster

ec.balance now also rejects an invalid -volumeIds, as its Do does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: report whether volume.balance arguments apply its plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: report whether ec.encode accepts its arguments

ec.encode has no dry run, so any accepted invocation changes the cluster.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: report whether volume.vacuum accepts its arguments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: report overlap for every maintenance work that more than one scheduler runs

The plugin scheduler, the legacy maintenance manager, and an admin_script can
each run volume balance, EC balance, EC encoding, and vacuum. Check all four
from one table and report each work with two or more active runners, in the
log and in the scheduler-status API as maintenance_overlaps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: show each maintenance overlap on the plugin pages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:46:34 -08:00
Chris LuandClaude Opus 5.5 1e4739f97a s3api: count object reads that fail after the status line is sent (#13073)
* s3api: count object reads that fail after the status line is sent

A GET whose body breaks after the 200/206 was committed is recorded by
SeaweedFS_s3_request_total as a success and only shows up in the log.
SeaweedFS_s3_read_aborted_total{bucket,cause} counts these reads on the
volume-server, SSE and remote-mount stream paths, split into
client_canceled, deadline_exceeded and read_error, and is dropped with
the other per-bucket series when a bucket is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: plot aborted S3 reads by bucket and cause

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: count aborted reads of inline objects and directory content

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: count gRPC deadline failures as deadline_exceeded aborted reads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: count an aborted read as client_canceled only when its request was canceled

A context.Canceled error under a live request context comes from an
internal cancellation, such as a shared lookup canceled by another
request, so it is recorded as read_error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:44:12 -08:00
Chris LuandClaude Opus 5.5 ef633dcc4d admin: inspect an S3 object's versions, retention and chunk volume health (#13078)
* admin: inspect an S3 object's versions, retention and chunk volumes

For a bucket and key, collect the base entry and every entry under
<key>.versions, decode version id, delete marker, ETag, client checksum,
Object Lock mode, retain-until, legal hold and the WORM enforcement time,
and map each chunk to its volume. One filtered VolumeList then reports,
per volume, replicas present versus the replica placement, or the EC
shards present and missing against the data shard count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: serve the S3 object inspection at /api/s3/buckets/{bucket}/objects/inspect

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: add an Inspect Object page for a bucket and key

/object-store/buckets/{bucket}/inspect?key= renders the inspection:
volume health per chunk volume with a link to the volume or EC volume
page, then every version with size, mtime, ETag, client checksum, lock
mode, retain-until, legal hold, WORM time and its chunk file ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: link each bucket to the object inspector

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: inspect a key that is also a prefix of other keys

The filer keeps such an object on a directory entry marked as a prefix
object, so the base entry lookup must accept it like a file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: count only S3 version entries as an object's history

A sibling named <key>.versions is history only when it is a directory,
and only children with a version id (attribute or v_ file name, as
VersionIdFromEntry reads them) are versions. Without a base object or
any such version the inspection is not found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: mark the newest version latest when the pointer is missing

When the base object is gone and .versions has no latest pointer (for
example after deleting a current null version), pick the latest with the
S3 gateway's own version ordering, exported as SelectLatestVersionId,
instead of leaving every version noncurrent. A truncated listing marks
none, since it may not hold the newest version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: report the ETag the S3 gateway returns

Use objectETag, exported as ObjectETag, so remote-only entries show
their remote ETag and entries without a stored ETag or MD5 show the
chunk-derived one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: read the buckets path with the inspection's request context

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: report the filer's logical size for each inspected version

filer.FileSize also covers chunk extents past a stale attribute size and
a newer remote size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: drop EC shard state once a volume also reports a replica

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: let the latest-version pointer outrank the null-is-latest flag

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: page the inspector's version scan past non-version entries

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: judge an inspected EC volume by its newest encode run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:43:19 -08:00
github-actions[bot] ebe5c8ac91 docs: regenerate star history chart 2026-11-28 01:19:02 +00:00
Chris LuandClaude Opus 5.5 46fe0f10da volume: count failed EC shard copies by reason (#13068)
* volume: count failed EC shard copies by reason

Each failed VolumeEcShardsCopy now increments
SeaweedFS_volumeServer_ec_shard_copy_failures_total{collection,reason} and
logs the volume, shards, source and reason. Reasons: source_not_found,
empty_index, no_space, timeout, io_error, other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* grafana: chart EC shard copy failures by reason

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): count failed EC shard copies by reason

Mirrors the Go volume server: each failed VolumeEcShardsCopy increments
SeaweedFS_volumeServer_ec_shard_copy_failures_total{collection,reason}
with the same reasons and logs the volume, shards, source and reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: classify wrapped gRPC NotFound and DeadlineExceeded copy errors

A source status that the destination wraps as text keeps its code only as
"code = NotFound" (Go) or the code's description (Rust), so match those
too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): record EC copy failures inside the copy task

The copy keeps running after the caller cancels, so its failure is
reported from the spawned task; a join error is reported by the handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:22:00 -08:00
Chris LuandClaude Opus 5.5 b6237dd8b1 master, admin, shell: warn about volume servers left in the default data center or rack (#13066)
* master: warn when a volume server registers in the default data center or rack

A volume server started without -dataCenter or -rack lands in
DefaultDataCenter/DefaultRack. Next to servers with explicit placement it
becomes its own failure domain for placement and balancing. Log a warning
when such a server registers while other servers name their data center,
or other racks of the same data center are named.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: warn about volume servers left in the default data center or rack

The Volume Servers page lists the servers that fell back to
DefaultDataCenter or DefaultRack while other servers name theirs, with
their volume and EC shard counts, so the stray failure domain shows up
before placement and balancing act on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: cluster.check warns about volume servers in the default data center or rack

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: cluster.check prints placement warnings before the capacity checks

A disk type with no free slots made cluster.check return before the
default data center/rack warnings were printed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: list each data center's rack once in the default placement check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:16:25 -08:00
dependabot[bot] 8df718eaf3 build(deps): bump actions/dependency-review-action from 5.0.0 to 5.0.1 (#12929)
Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/actions/dependency-review-action/releases)
- [Commits](https://github.com/actions/dependency-review-action/compare/a1d282b36b6f3519aa1f3fc636f609c47dddb294...bbc44d14a204704ccc493733616cd1e93a0321ec)

---
updated-dependencies:
- dependency-name: actions/dependency-review-action
  dependency-version: 5.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-27 15:04:34 -08:00
76bc731c69 feat: s3: record object path in needle Content-Location pair (#13061)
* feat: operation: pass needle pairs through chunked uploads (#12997)

* feat: s3: build Content-Location needle pair from the object path (#12997)

* feat: s3: record object path in needles written by putToFiler (#12997)

* feat: s3: record destination object path in copied chunks (#12997)

* feat: s3: record destination object path in stream-copied chunks (#12997)

* test: s3: pin Content-Location in putToFiler upload options (#12997)

* s3: record no path on copies of volume-encrypted chunks

A chunk written with -encryptVolumeData is copied as ciphertext through
the plain upload path, so the copy sent the destination path in
plaintext next to encrypted data, while PutObject's cipher upload sends
no pairs at all.

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-27 15:02:15 -08:00
bf0da715fc ci: keep dev builds published and document them (#13059)
* ci: keep dev builds published and document them

The dev release was emptied before every build: the cleanup job deleted
all weed-* assets first, and cancel-in-progress cancelled the build on
the next master push. Build the platforms with one prepare timestamp,
upload first, then prune assets from older builds. Queue runs instead
of cancelling them, and allow manual runs from master only.

Document the dev binaries and the :dev container images in the README
and docker/README.md.

Refs #5009

* ci: key dev build concurrency by ref

A workflow_dispatch from another branch joined the single dev group and
replaced the pending master run before failing its ref guard, so the
newest master commit was never built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: keep newer dev builds when an older run retries

A "Re-run failed jobs" of an older run keeps that run's BUILD_TIME, so
its prune treated a newer complete build as stale and deleted it. Prune
now deletes only assets whose stamp sorts before BUILD_TIME.

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-27 14:59:44 -08:00
Chris LuandClaude Opus 5.5 978ff95327 volume(rs): reload TLS server certificates on SIGHUP (#13067)
The Go volume server re-reads its gRPC and HTTPS cert/key files on
SIGHUP (certreload.ReloadAll). The Rust server built each rustls
ServerConfig with a fixed cert, so a rotated pair only took effect
after a restart. Serve the pair through a resolver that re-reads the
files on SIGHUP and keeps the previous pair when the new files fail to
load.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:57:26 -08:00
Konstantin Lebedevandwhitefox b0df54aa8f security: reload TLS credentials on SIGHUP (#13058)
TLS certs currently refresh only on the periodic WEED_TLS_CERT_REFRESH_INTERVAL poll (5h by default), so after replacing cert/key files an operator has to wait up to one interval for the new material to be used. SIGHUP already reloads configs and JWT keys, but not TLS.

Replace gRPC's pemfile.Provider with a small certprovider.Provider in weed/security/certreload that keeps the current KeyMaterial, refreshes on the same timer, and can be forced to re-read the files via Reload. A process-wide registry plus grace.OnReload(ReloadAll) makes SIGHUP apply rotated certs immediately to every gRPC and HTTPS server/client.

On parse/read errors the previous material is kept, so a broken rotation does not take the listener down.

Fixes #13056

Co-authored-by: whitefox <whitefox@mayflower.work>
2026-11-27 14:57:06 -08:00
7bbb65fa80 master: /col/delete requires an explicit collection name (#13055)
* master: /col/delete requires an explicit collection name

A /col/delete request without a collection parameter, or with an empty
one, read as the empty-named default collection and deleted it. Return
400 instead, and accept collection=_default (the keyword weed shell
uses) to delete the default collection deliberately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: keep a collection literally named _default addressable by /col/delete

collection=_default now names the empty-named collection. A collection
created with that literal name would have been unreachable, and a request
meant for it would have deleted the default collection instead. Resolve
the keyword to the literal collection when one exists, and refuse the
request when both exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: /col/delete accepts only the DELETE method

A GET is expected to be safe, yet a bare GET or a link prefetch deleted
the named collection. Any other method now gets 405 with an Allow
header, and the docs, benchmark help and test helpers send DELETE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: /col/delete accepts _default_ for the default collection

When a collection literally named _default exists next to the default
collection, collection=_default is refused, which left the default
collection with no way to be named. Accept the _default_ spelling that
weed shell collection.delete already takes; it always means the
default collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: /col/delete keeps a literal _default_ collection addressable

_default_ now resolves like _default: to the literal collection when one
exists, to the default collection otherwise, and refuses the request when
both exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* REST_API: /col/delete when both keyword names are literal collections

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-27 14:56:18 -08:00
Chris LuandClaude Opus 5.5 96321141cc filer.sync: stop deleting versions on transient lookups and in-flight pointers (#13063)
* filer.sync: retry an update whose destination lookup failed transiently

FilerSink.UpdateEntry reported every lookup error as a missing entry, so
the replicator and filer.sync deleted the destination key and created it
again. For a directory, a canceled or unavailable lookup removed it with
everything under it. Only a real not-found now lets the caller recreate
the key; other lookup errors are returned for retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: leave a pointer to a recently minted version unrepaired

When a versioned read finds a latest pointer whose version file is
missing, the self-heal rescanned .versions and then either removed the
directory (no version left) or rewrote the pointer to the newest version
found. With filer.sync the directory and its pointer can arrive before
the version file, so the heal acted on a version still in flight: the
local directory removal replicated back and deleted the committed
version on the source cluster, and a pointer repair would roll its
latest pointer back.

While the pointer names a version minted in the last ten minutes, the
read now answers from the rescan without persisting anything, and the
reconciler skips the key. After that window the heal works as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.sync: retry a failed destination lookup before giving up on an update

Returning a transient lookup error leaves the retry to the caller, and
filer.replicate hands a failed event to the notification input instead
of replaying it. Retry the lookup in place with the shared bounded
backoff; a not-found still returns at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.sync: count only the not-found sentinel as a missing destination

LookupEntry already maps every miss to filer_pb.ErrNotFound, plain-text
ones included. Matching the sentinel's text in any error also counted an
Unavailable lookup carrying that text as a miss, which let the caller
delete and recreate the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: requeue an in-flight versions pointer for after the grace window

The reconciler dropped a key whose pointer named a version still in
flight, so nothing revisited it once the window passed. Requeue it for
one grace window without counting the skip as an attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: probe the latest version file before deferring an in-flight pointer

A recent pointer whose version file is already present needs no repair;
deferring it kept the key queued for the whole grace window and used
up queue capacity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: retry an in-flight versions pointer when its grace runs out

The reconciler waited a full grace window after the deferral, so a
pointer first seen near the end of its grace stayed unrepaired for
almost twice as long.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: run the in-flight pointer grace from its local commit too

The grace was measured from the version id's mint time on the origin
cluster against the local clock, so a peer whose clock ran more than
the grace ahead, or a filer.sync backlog longer than the grace, saw a
just-synced pointer as stale and could remove or roll back the version.
The .versions entry's commit time is stamped by the local filer when
the pointer is stored, so it bounds the wait with the local clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: repair a pointerless .versions entry despite a recent commit

The in-flight grace protects a pointer whose version file has not arrived
yet. A .versions entry with no pointer names no such file, so a recent
commit of it must not hold back the rebuild of its pointer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: hold a stale-pointer repair while the live entry is still in grace

The heal checked the grace on the snapshot it took before the scan. A
.versions entry stored again with the same pointer during the scan
restarts the grace, so check it on the live entry the CAS is conditioned
on before persisting the repair.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: recheck the live grace before removing an empty .versions

The empty-directory cleanup checked the grace on the pre-scan snapshot,
so a pointer stored again during the scan could still have its
.versions removed. Re-read the entry and leave it while its grace lasts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:51:53 -08:00
Chris LuandClaude Opus 5.5 e01133bfa3 ec_balance: keep node addresses out of the task ID so tasks can be persisted (#13062)
* ec_balance: keep node addresses out of the task ID

The ID embedded both host:port node addresses, and the admin's task
persistence rejects any ID containing ':', so every ec_balance task
failed to save on each state change and lived only in memory. The
volume, shard, timestamp and index already make the ID unique; the
nodes stay in the task's Reason and params.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: test that a detected ec_balance task saves and loads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 12:58:08 -08:00
77333a5578 s3: match copy-source ETag conditions with the shared helper (#13054)
* s3: match copy-source ETags as the read and write paths do

validateSourceConditionalHeaders compared the source ETag to the header
value with strings.Trim, so x-amz-copy-source-if-none-match: W/"<etag>"
did not match and an unchanged source was copied instead of answered
with 412. An If-Match list that contained the source's ETag was
rejected for the same reason. RenameObject shares the helper, so
x-amz-rename-source-if-* behaved the same way.

Use util.ETagListMatches, which the GET and PUT paths already use:
strong comparison for If-Match, weak for If-None-Match, and the quoted
tag lists RFC 9110 allows.

* s3: drop the history comment from the copy-source ETag checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: skip the truncate manifest test on freebsd like its fake filer

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-27 12:48:08 -08:00
397a156104 security: a fips.mode setting that Go checks against GODEBUG and the Rust binaries apply to TLS (#13029)
* util: refuse to start when fips.mode in security.toml disagrees with GODEBUG

security.toml gains [fips] mode = "off" | "on" | "strict", also settable
as WEED_FIPS_MODE: one setting that states the FIPS 140-3 mode of every
process in a deployment, so the Rust binaries, which do not run on the Go
runtime, can follow it. Go processes keep taking their behaviour from
GODEBUG=fips140 and now check it against the setting:
LoadSecurityConfiguration and `weed worker` exit when "off" runs without
fips140=off, "on" without fips140=on, or "strict" without fips140=only,
naming the setting and the GODEBUG value it needs. An unknown value is
refused; unset or empty changes nothing.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rust: fips.mode with FIPS-mode TLS in weed-volume, weed-worker and weed-vector

seaweed-common gains a fips module: FipsMode resolved from fips.mode in
the security.toml a binary uses, with WEED_FIPS_MODE over it. Each binary
resolves it once at startup, logs it and installs the matching rustls
provider as the process default, refusing to start on an unknown value or
when another provider was installed first.

Under "on" and "strict" the provider is aws-lc-rs filtered to the lists
Go's crypto/tls applies in FIPS mode: TLS 1.3 AES-GCM suites and TLS 1.2
ECDHE AES-GCM suites (no ChaCha20-Poly1305), X25519MLKEM768,
SecP256r1MLKEM768, P-256 and P-384 (no plain X25519), Go's ten signature
schemes (no ML-DSA). Configurations SeaweedFS builds require the Extended
Master Secret in that mode, and the volume server refuses a non-FIPS suite
in tls.cipher_suites instead of falling back. sw-client installs the same
provider instead of ring. Unset or "off" keeps aws-lc-rs's default
provider unchanged.

This is behavioural parity only: the provider still runs on the
non-validated aws-lc-rs build.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: refuse a fips.mode that is not a string

viper's GetString turns an array or a table into "", so mode = ["strict"]
under [fips] skipped the GODEBUG check while the Rust binaries refused the
same file. RequireFipsMode now reads the raw value (ViperProxy.Get, under
its lock) and exits when it is not a string, naming its source; an absent
or empty value still means unset, and WEED_FIPS_MODE still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rust: read fips.mode with the parser that reads the JWT keys

seaweed_common::fips::resolve parsed security.toml with the toml crate,
while the volume server reads the rest of the file with its own lenient
loader. A file with [fips] mode = "on" beside an unquoted value the loader
accepts resolved to off and logged "fips.mode unset", although the JWT
keys from the same file were applied. Each binary now reads fips.mode
with the loader it uses for everything else and hands the value to
resolve: the volume server through its line parser, the worker and vector
engine through their parsed Security table, which already refuses a file
that is not TOML. A security.toml the volume server finds but cannot read
stops startup. A missing setting is still off, and WEED_FIPS_MODE still
wins. seaweed-common no longer depends on toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sw-client: offer only FIPS signature schemes with insecure_skip_verify

With https.client.insecure_skip_verify, reqwest installs its own verifier,
which advertises a fixed scheme list including SHA-1 and Ed448 whatever
the process provider allows. In FIPS mode the volume transport now builds
its rustls configuration itself on the process provider: the server
certificate and host name are not checked, as the setting asks, but
handshake signatures are verified with the provider's algorithms, only its
schemes are offered, and TLS 1.2 requires the Extended Master Secret.
Outside FIPS mode the reqwest path is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-common: sign only with Go 1.27's FIPS schemes, allow ML-DSA

The FIPS provider kept aws-lc-rs's key provider, so a FIPS-mode listener
signed handshakes with whatever scheme its key and the peer agreed on,
outside the list the provider verifies with. Keys now load through a
provider that limits each key to the FIPS signature schemes and refuses a
key that can sign none of them, such as Ed448; the volume server and the
worker's gRPC TLS name the certificate and key files in that error.

The lists follow Go 1.27.4, which go.mod now requires: its
defaults_fips140.go allows ML-DSA-44, -65 and -87 as signature schemes and
ML-DSA certificate keys (for Go's native module only), so they are allowed
here as well. Go also allows MLKEM1024 but does not enable it by default,
so it stays out of the key exchange list as in Go's defaults. "off" keeps
the default key provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: skip the truncate manifest test on freebsd like its fake filer

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-27 12:47:44 -08:00
dependabot[bot] 977513cf35 build(deps): bump github/codeql-action from 4.39.3 to 4.39.4 (#12930)
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>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-27 08:55:12 -08:00
Chris Lu 781288cf11 s3api: ignore custom x- query parameters on bucket requests (#13046) 2026-11-27 02:42:37 -08:00
Yip Leo eb655f46ba mount: merge a flush's folded chunks as the chunks, not as a new manifest (#13043)
* mount: merge a flush's folded chunks as the chunks, not as a new manifest

A flush folds the handle's chunks into manifests before it commits, and
installs the folded list in the handle. When the commit finds that a
peer changed the entry, mergeContentEntry replays the handle's changes
since its base onto the peer's entry: a chunk not in the base counts as
the handle's own write, a base chunk missing from the handle as one it
dropped. A manifest the flush just made of base chunks therefore goes in
as a write of the handle's, with every chunk it holds:

- after a peer rewrote the whole file (a bloat merge, stamped with the
  oldest data it holds) or dropped chunks, the manifest brings the old
  chunks back, and where their stamps are newer they hide the peer's
  bytes;
- after a peer folded the same chunks, the entry holds both manifests.

Since #12462 a flush folds every 256 small chunks, so two mounts that
append to one file, as the ranks of a training job often do with its
log, reach this.

The flush now records what its fold packed (chunkFold). The merge sees
the folded chunks instead of the new manifests, so the fold is no change
at all; the merged entry goes out unfolded, and the next flush folds it
again. When the commit fails, the fold is taken back out of the handle,
whose base still has the chunks, so a later merge or flush does not take
the manifests for writes either. Their blobs are left unreferenced, as a
failed fold leaves them.

* mount: rebase a merged flush onto the entry the filer stored

Review follow-up. A merged commit sends the merged chunks unfolded, and the
filer can fold them before it stores the entry (cleanupChunks). The flush
installed the request in the handle, but took the stored entry as the
handle's base (ackedBase), so the handle held flat chunks against a base
that lists a manifest. A later merge, such as a peer's truncate reaching the
dirty handle, would take those chunks for writes of the handle's and
publish them again.

The handle is now rebased onto the stored entry it takes as its base, in
both flush paths. rebaseEntry still gets the request, so chunks attached
after it was taken are kept.

TestFlushMergeInstallsTheEntryTheFilerStored: a peer's chmod refuses the
first commit, the merged retry sends 256 flat chunks, and a filer that folds
them stores a manifest; the handle and its base must both hold the stored
entry. It fails with the request installed.
2026-11-26 22:48:58 -08:00
424c67ad06 mount: truncate a manifest the cut goes through as the chunks it holds (#13042)
* mount: truncate a manifest the cut goes through as the chunks it holds

Truncating a file shortens every chunk the new size cuts through, a
manifest chunk included. A manifest's span only says where its chunks
lie: reads resolve the chunks inside it at their own offsets and sizes,
so the bytes past the cut stay readable. Once the file grows over them
again without writing them, by an extending truncate or a write past the
end, they come back where zeros belong.

Reproduced with weed mount on a local cluster: 700 lines appended with
one close() each, so the small-chunk fold put the first 256 into a
manifest; then a truncate to the first 100 lines and an ftruncate past
the old end. The extended range read 8,580 bytes of the cut lines
instead of zeros, through both mounts of the file. Since #12462 any file
grown by a few hundred small appends has manifests; before it, only
files of 10,000 chunks did.

A truncate now opens each manifest the cut goes through, nested ones
too, and cuts the chunks it holds. The manifest leaves the entry, and
the filer deletes it with the chunks past the cut when the entry is
stored. A manifest shortened by an earlier truncate first gives up the
chunks past its own span. If a manifest cannot be read, the truncate
fails with EIO and the file is left as it was.

* mount: keep a truncate's expanded chunks from merges, read its manifests with a token

Review follow-ups:

- The chunks a truncate takes out of a manifest are not in the handle's
  base, which lists the manifest. A merge onto a peer's entry took them for
  writes of the handle's, so after a peer cut the file shorter and the filer
  queued the rest for deletion, the handle could publish references to
  those chunks again; the gap check passed because plain chunks covered the
  range. Before the expansion, the manifest across the cut refused that
  merge. A truncate that expands a manifest now marks the handle as having
  rewritten its chunks, so the merge is refused when the peer changed
  chunks, at the next flush and when the peer's event reaches the handle.
- A truncate by path, with no open handle, read the manifest before its file
  id was registered for a filer-issued read token, so a mount reading with
  -volumeReadAuth sent the read without one and the truncate failed with
  EIO. The entry's chunks are registered under its path first.
- All manifest reads of one truncate share one one-minute deadline, instead
  of a minute each.

TestTruncateThroughManifestCutsItsChunks runs SetAttr with and without an
open handle: it fails without the registration (no handle) and without the
rewrite mark (open handle). TestMergeRefusesTruncateExpansionOverPeerTruncate
shows the merge that published a peer-dropped chunk, and its refusal.

* mount: answer a truncate interrupted while reading a manifest with EINTR

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-26 22:47:52 -08:00
Chris LuandClaude Opus 5.5 be8eb02ac0 util: remove multipart temp files parsed on the idle-timeout pause's request copy (#13044)
* util: remove multipart temp files parsed on the paused request copy

net/http removes the temporary files of a multipart form parsed on the
Request it passed to the handler. PauseIdleTimeoutWhileHandling hands the
handler a shallow copy when the request has a body, so a form parsed
there (ParseMultipartForm, or FormValue on a multipart body) left its
temporary files behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: test that the idle-timeout pause removes multipart temp files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: point the multipart temp-file test's temp dir at Windows' TMP and TEMP too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:47:05 -08:00
Chris LuandClaude Opus 5.5 f2e9e49842 master: stop volume growth from leaking volumes into a just-deleted collection (#13035)
* topology: stop a grow once a delete fences its collection

A grow request creates its volumes one after another and resolves the
collection by name for each, so once the collection was deleted the rest of
the request recreated it. The request now keeps the collection it started
in and holds a per-collection fence shared while it creates each volume. A
delete can raise the fence exclusively, which waits out the volume in
flight, and the request stops at its next volume. A collection dropped only
because its last layout emptied is followed to the one published under its
name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: fence volume growth before deleting a collection

The delete listed the collection's servers, fanned out DeleteCollection, and
only then dropped the collection from the topology. A grow still running
created its next volumes during or after the fan-out, on servers that had
already been cleaned or were not in the list, and those volumes registered a
new layout for the deleted collection that nothing removed. A bucket deleted
right after its first write leaked most of its initial volumes this way.

The delete now raises the collection's growth fence first, so the volume in
flight registers and is deleted with the rest, and the grow stops. A failed
fan-out lifts the fence, since the collection stays in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: refuse assigns from a collection being deleted

The delete waits for the volume a grow is creating before it lists the
collection's servers, and the collection's writable volumes stayed
assignable meanwhile, so a write could land in a volume about to be
deleted. The delete now raises the fence before it waits, and assigns
check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: list only collections that hold a volume layout

A grow request publishes its collection before its first volume
registers, so one that created nothing left a collection with no
volume in the list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: queue no grow for a collection being deleted

PickForWrite returned the layout's shouldGrow before it checked the
fence, so an assign on an empty layout of a collection being deleted
still queued a grow. That grow could run after the delete finished and
recreate the collection. Check the fence right after the pick, before
any early return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: keep an emptied collection published while growth holds it

DeleteLayout unpublished a collection as soon as its last layout
emptied, even while a grow held it or a delete had fenced it. The
volume in flight then registered by name into a new collection that
the delete never listed servers for, and the delete's final
DeleteCollection dropped it from the topology while it stayed on disk.
Unpublish an empty collection only when no grow or delete holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: fence the collection still published under the name

An emptied-layout cleanup that passed its fence check could unpublish the
collection while the delete waited to fence it. The delete then fenced and
listed an orphaned object, while growth published a new collection under
the name that no fence held. Topology.FenceGrowth re-checks publication
once the fence is up and moves to the collection published since.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: run one delete of a collection at a time

Two deletes of one collection both fenced it and fanned out by name. Once
the first removed it, a write could recreate the collection, and the
second delete removed the new one's volumes and topology entry.
FenceGrowth now waits for a delete already running on the collection and
finds nothing once that delete removed it; a delete that failed hands
the collection to the one waiting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: stop a delete another delete beat to the collection

A delete that fenced the collection but had not yet checked that it was
still published retried when it was not, for the collection an emptied
layout drops. A delete that removed it in between also left it
unpublished, so the retry fenced and returned the collection a write had
recreated under the name since. finish(true) now marks the collection
deleted before it unpublishes it, and the retry stops at that mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: keep the name fenced through the EC pass of a delete

The normal pass unpublished the collection and let growth back in before
the EC pass ran. The EC pass deletes by name on every server holding the
collection's shards, and DeleteCollection on a server also drops its
normal volumes, so a write recreating the bucket in between could land a
volume that the EC pass then deleted. A second delete of the name, finding
no collection, also ran its own EC pass by name.

deleteCollection now fences the name once, before either pass, and lifts
or ends the fence after both. finish(true) unpublishes the collection then.
A name with EC shards only gets an empty collection to fence, so an assign
under it is refused too, and a delete that finds nothing skips both passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: wait for the second delete's lock instead of sleeping

The overlapping-delete tests slept before acting on the first delete. A
second delete scheduled late started after the collection was replaced, or
after the first delete was already over, so the tests could fail or pass
without the overlap they check. They now wait until the second delete is
blocked on the delete lock, read from the goroutine stacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* topology: empty the layout through UnRegisterVolumeLayout in the test

The test called DeleteLayout, whose signature differs in builds that key
layouts by more than replication, TTL and disk type. UnRegisterVolumeLayout
reaches the same cleanup from a VolumeInfo and has one signature everywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:46:28 -08:00
Chris LuandClaude Opus 5.5 8053e77813 s3api: decide existing-object-tag denies on the object's tags (#13038)
* s3api: report a bucket policy Deny on existing object tags

HasExistingObjectTagDeny tells whether a bucket policy has a Deny statement
conditioned on s3:ExistingObjectTag/<key>, so the auth layer knows when a
deny may turn on tags it has not read yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: decide existing-object-tag denies on the object's tags

The auth layer evaluates the bucket policy before the handler reads the
object, so s3:ExistingObjectTag/<key> resolves to a missing tag. A Deny
with a negated condition (StringNotEquals, StringNotLike,
StringNotEqualsIgnoreCase, Null true) then matched every object and was
final, even one whose tag satisfies it, as in the deny-until-scanned-clean
pattern.

When that early evaluation denies and the policy has such a Deny, look up
the object's entry and evaluate again with its tags. A missing object or a
failed lookup keeps the deny. Copy sources and per-key checks that go
through authorizeObjectKeyAction get the same treatment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: give identity checks the object tags a Deny was decided on

With IAM integration, VerifyActionPermission evaluates the mirrored bucket
policy again alongside the identity's policies, from a condition context
built from the request alone. The negated existing-tag Deny matched there
once more and denied an object tagged to pass it.

evaluateBucketPolicy now returns the request carrying the tags it read,
and RequestConditionValues reports them as s3:ExistingObjectTag/<key>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck in-flight tag conditions on the version served

An in-flight request is authorized again when access changes. The entry
lookup read the version current by then, so a newer version tagged to
pass the Deny could keep a download of an older, denied version running.
The handler's entry recheck now records the entry it authorized on the
tracked request, and the re-check decides on that entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: load the bucket before deciding an object request on its policy

On a bucket whose policy was not loaded yet, the early bucket policy check
found no policy and skipped the object-tag lookup, so the identity checks
saw the request without the object's tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep an owned copy of the entry a tracked request served

Handlers change the entry's metadata after the check, for example when
storing new tags, so revalidation read a map the handler was writing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:58:10 -08:00
aaca5c8c0a s3: verify SigV4 header values with each SDK's Trimall (Go, Java, botocore) (#13036)
* s3: trim only ASCII spaces in SigV4 canonical header values

signV4TrimAll used strings.Fields, which also splits on Unicode spaces
(U+00A0, U+202F, ...). A signed header whose value holds one inside, such
as an x-amz-meta-* filename from a macOS screenshot ("... at 2.20.09 PM"),
got a different canonical request than the client signed, and the request
failed with SignatureDoesNotMatch. Trim and compress only ' ', as the AWS
SDKs do (aws-sdk-go-v2's v4.StripExcessSpaces).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: verify SigV4 with both clients' Trimall for non-ASCII-space whitespace

The AWS SDK for Go v2 collapses only ASCII spaces in a signed header value and
trims the edges with strings.TrimSpace; botocore turns every whitespace
character into a space. Match the Go SDK first (now also trimming Unicode
whitespace at the edges) and, when it gives a different canonical request,
retry with the previous strings.Fields form so botocore signatures keep
verifying.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: pass the header value trim to getCanonicalRequest and getCanonicalHeaders

Fold canonicalRequestWith and canonicalHeadersWith into the existing
functions instead of keeping them as wrappers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: also verify SigV4 header values with the AWS SDK for Java Trimall

The Java SDKs collapse runs of spaces and tabs but keep Unicode spaces, so
a value with both a tab and a U+00A0/U+202F matched neither the Go SDK nor
the botocore form. It is tried between the two, so a value with only one
kind of whitespace still computes at most two signatures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Bear1110 <14165451+Bear1110@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-26 21:57:31 -08:00
e743f99bb5 util: keep a request's context while its handler works quietly past the idle timeout (#13040)
* util: keep a request's context while its handler works quietly past the idle timeout

A request that the server works on for longer than the listener's idle
timeout, without reading or writing, lets that timeout end net/http's
background read: the read the server keeps waiting while a handler runs,
to see a client hang up. net/http takes the failed read for the client's
connection failing and cancels the connection's context, so the request in
progress, and every later request on the kept-alive connection, run with a
canceled context. #10212 covered a long write-only response, whose writes
now extend the read deadline; an answer that has not started yet has
nothing to extend it.

On the S3 gateway (-idleTimeout 120 s) such requests are the ones that
answer only when their work is done, e.g. a large CopyObject into a
versioned bucket, which the copy keep-alive of #12862 does not cover. After
one, the next requests on that connection fail within a millisecond: a
ListObjectsV2 answers 500, a GetObject and a PutObject 499
ClientDisconnected while the client is still connected. The filer's HTTP
listener has a 10 s idle timeout by default.

PauseIdleTimeoutWhileHandling, which newHttpServer now installs next to the
ConnContext hook it already sets (S3, filer, IAM and master HTTP), takes
reading out of the activity timeout from the moment a request's body has
been read to its end (at once when it has none) until its handler returns:
the client is waiting for the answer, so a connection that carries nothing
means the server is at work. Reading a body, writing an answer and waiting
for the next request stay under the timeout, and a client that closes its
connection still cancels the context. Over HTTP/2 the frame reader keeps no
deadline while such a handler runs and gets it back when the last one
returns.

Tests: weed/util/net_timeout_test.go (a quiet handler over HTTP/1.1, TLS
and HTTP/2, and the next request on the same connection; the same after a
1 MiB body; a stalled body, an idle connection, an idle HTTP/2 connection
and a client hang-up still end as before; concurrent requests; a waiting
read held by the pause and released at its end; the context loss without
the wrapper) and weed/command/server_http_test.go (newHttpServer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: serve through newHttpServer so quiet handlers keep their context

weed webdav serves a util.Listener with an idle timeout (10 s by default)
but built a bare http.Server, so it had neither ConnContext nor the idle
timeout pause. A COPY or MOVE of a large file answers only once it is done,
and like the S3 and filer handlers it then lost its context, and so did
every later request on the connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: pause the idle timeout for HTTP/1.x requests only

HTTP/2 has no background read to protect: when its connection carries
nothing for the timeout, the frame reader's deadline closes the connection,
and no later request runs on it. That deadline is also what ends a stream
whose client stopped reading, since the answer waits for flow-control
credit, not on the socket, where the write deadline would end it. With the
pause on HTTP/2 requests, a download whose client stopped reading held its
handler and connection until the client acted, and a stream that declared
content-length 0 but never ended could hold its handler the same way.

Pause only HTTP/1.x requests; HTTP/2 keeps the timeout it had.

Tests: TestStalledDownloadStillTimesOut over HTTP/1.1, TLS and HTTP/2 (the
HTTP/2 case was still waiting after 8 s with the pause on HTTP/2) and
TestOnlyHTTP1RequestsArePaused; the HTTP/2 quiet-handler cases are gone,
with them the HTTP/2 subtest that flaked under -race.
TestPauseUnderConcurrentRequests gets a 1 s idle timeout, so that a request
waiting for its turn on a slow run does not find its connection closed.

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-26 21:56:12 -08:00
1f8ad7016f filer: compare garbage chunks by needle identity (#12992)
* Normalize chunk identities during garbage comparison

* Keep replication chunk respellings observable

* filer: skip the needle identity index when nothing is subtracted

Every compaction subtracted its retained chunks from an often empty
covered list, parsing and re-formatting each retained file ID first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: skip the identity subtraction at the compaction call site

Returning early from doMinusChunks on an empty minuend stopped
MinusChunks from calling GetFileIdString on the new entry's chunks.
After CreateEntry of a new file, the caller's chunks then kept the
FileId that BeforeEntrySerialization cleared, so tus completion built
its still-referenced set from empty IDs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: match needle spellings through DoMinusChunks instead of a new function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: DoMinusChunks always matches chunks by needle

Drop the byNeedle parameter so DoMinusChunks keeps its two-argument
signature and every caller, including ones added on master since,
compares equivalent file ID spellings as the same needle. The needle
normalization moves from the server scope checks to filer.ChunkIdentity
so both share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filersink: match replicated source file IDs by needle

compareChunks no longer reports a respelled source chunk, so the
replica keeps the SourceFileId it was copied under. Removing chunks the
source dropped and judging stale backup chunks now compare that ID by
needle, otherwise a later removal in the other spelling would leave the
replica's chunk behind.

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-26 17:25:55 -08:00
github-actions[bot] f927436567 docs: regenerate star history chart 2026-11-27 00:34:29 +00:00
dependabot[bot] 68e99fe04d build(deps): bump github.com/ydb-platform/ydb-go-sdk/v3 from 3.155.1 to 3.157.1 (#12925)
build(deps): bump github.com/ydb-platform/ydb-go-sdk/v3

Bumps [github.com/ydb-platform/ydb-go-sdk/v3](https://github.com/ydb-platform/ydb-go-sdk) from 3.155.1 to 3.157.1.
- [Release notes](https://github.com/ydb-platform/ydb-go-sdk/releases)
- [Changelog](https://github.com/ydb-platform/ydb-go-sdk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ydb-platform/ydb-go-sdk/compare/v3.155.1...v3.157.1)

---
updated-dependencies:
- dependency-name: github.com/ydb-platform/ydb-go-sdk/v3
  dependency-version: 3.157.1
  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-26 13:25:45 -08:00
39675b2faf filer: hide remote rename source paths from scoped responses (#13010)
* filer: redact remote rename source from scoped responses

* Preserve scoped remote rename markers

* Consolidate scoped marker replacement coverage

* Refuse scoped whole-entry guards during remote rename

* Keep coded create refusals for guarded scoped writes

* Make scoped subscription batch coverage deterministic

* filer: refuse scoped conditions that compare the remote rename source

IF_EXTENDED_NOT_EQUAL clauses and ExpectedExtended on Create, Update
and DeleteEntry could still compare a guess against the hidden marker,
so a scoped client could confirm the source path it redacts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: refuse scoped condition gates on the remote rename source

An IF_EXTENDED_TIME_ELAPSED gate applies its time check only when the
gate value matches, so a gate on the marker also confirms a guess.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a pending rename source out of remote copy errors

A failed copy of a pending remote-only rename named the marker's source
location, which the backend error repeats, and rename RPCs return that error
to scoped callers. Log the full error and return one naming only the paths
the caller supplied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: let a scoped local overwrite end a pending remote rename

Scoped replacements kept the hidden rename source marker even though a
scoped entry can never stay remote-only, so the marker was stale on the
local copy and every later scoped IF_ENTRY_EQUAL write was refused. Drop the
preservation and let the overwrite clear the marker as other local writes do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* codespell: ignore poligon only inside URLs

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-26 12:31:02 -08:00
0fb1387226 s3: compare If-None-Match weakly, as the filer and volume servers do (#13033)
* s3: compare If-None-Match weakly, as the filer and volume servers do

The S3 gateway matched conditional ETags by trimming quotes, so a weak
tag such as W/"etag" in If-None-Match never matched and a revalidating
GET got 200 instead of 304. Move the filer's RFC 9110 matcher to
weed/util and use it in the gateway: weak comparison for If-None-Match,
strong for If-Match. The routed write condition now sets AllowWeak on
IF_ETAG_NOT_MATCH so the check under the object lock agrees with the
gateway's pre-check.

* s3: split write-condition ETag lists the way the gateway matches them

etagList split on every comma and kept empty elements, so the filer's
locked If-None-Match check (now a weak comparison) could match a fragment
of one quoted tag, or an empty element, that the gateway's pre-check
ignores. A PUT with If-None-Match: W/"<etag>,x" passed the pre-check and
then got 412 under the lock. Reuse the gateway's quote-aware splitter and
drop empty elements.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Mansur Akhmadi <10739460+mansur-akhmadi@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-26 12:30:33 -08:00
Chris LuandClaude Opus 5.5 7738ea7f45 s3: keep a bucket policy change from aborting its own request (#13034)
* s3: keep a bucket policy change from aborting its own request

The bucket metadata event re-checks every request in flight on the
bucket, including the PutBucketPolicy, DeleteBucketPolicy or DeleteBucket
request that made the change while it is still answering. A deny-all
policy, or the removal of the policy that granted the requester access,
then closed that request's connection after the change was stored; the
client saw a reset and its retry was denied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep re-checking a policy change until it stores it

Exempting the policy-changing actions at admission let a request whose
key was revoked while it read its body still replace or delete the
policy. The request stays tracked now and untracks itself right before
it stores its change; if it was aborted by then, it stores nothing.

DeleteBucket untracks itself before the delete, which also covers the
identity re-check its bucket-scoped action pruning triggers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:29:48 -08:00
dependabot[bot] 01b88ad2f9 build(deps): bump go.etcd.io/etcd/client/pkg/v3 from 3.7.3 to 3.7.4 (#12927)
Bumps [go.etcd.io/etcd/client/pkg/v3](https://github.com/etcd-io/etcd) from 3.7.3 to 3.7.4.
- [Release notes](https://github.com/etcd-io/etcd/releases)
- [Commits](https://github.com/etcd-io/etcd/compare/v3.7.3...v3.7.4)

---
updated-dependencies:
- dependency-name: go.etcd.io/etcd/client/pkg/v3
  dependency-version: 3.7.4
  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-26 12:29:11 -08:00
dependabot[bot] b42a5ca24e build(deps): bump github.com/rabbitmq/amqp091-go from 1.16.0 to 1.17.0 (#12928)
Bumps [github.com/rabbitmq/amqp091-go](https://github.com/rabbitmq/amqp091-go) from 1.16.0 to 1.17.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.16.0...v1.17.0)

---
updated-dependencies:
- dependency-name: github.com/rabbitmq/amqp091-go
  dependency-version: 1.17.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-26 12:28:42 -08:00
dependabot[bot] 5be58fccd7 build(deps): bump github.com/apache/arrow-go/v18 from 18.8.0 to 18.9.0 (#12926)
Bumps [github.com/apache/arrow-go/v18](https://github.com/apache/arrow-go) from 18.8.0 to 18.9.0.
- [Release notes](https://github.com/apache/arrow-go/releases)
- [Commits](https://github.com/apache/arrow-go/compare/v18.8.0...v18.9.0)

---
updated-dependencies:
- dependency-name: github.com/apache/arrow-go/v18
  dependency-version: 18.9.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-26 12:28:22 -08:00
8d975574d4 docker: let the caller's GODEBUG fips140 setting override the entrypoint's default (#13026)
docker: let the caller's GODEBUG fips140 setting override the default

entrypoint.sh appended fips140=on after the caller's GODEBUG, and Go
applies the last of repeated settings, so `docker run -e
GODEBUG=fips140=only` ran with fips140=on, and fips140=off stayed on. The
default now goes first.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-26 08:47:56 -08:00
Chris LuandClaude Opus 5.5 c2c5aac943 test: fall back to a Maven Central mirror for the Spark Lance connector (#13031)
spark-submit resolved the Lance bundle and its dependencies through Ivy
from Maven Central only, so a refused Central request failed the run in
seconds with "module not found". --repositories adds the Google mirror
after Central in Ivy's resolver chain.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:43:09 -08:00
Chris LuandClaude Opus 5.5 9c17e0038d volume(rs): sign a fresh write JWT for each replica forward (#13030)
* volume(rs): sign a fresh write JWT for each replica forward

The primary checks the write JWT when the request arrives, then reads the
body. A body slower than the JWT lifetime (10 s by default) left the
forwarded Authorization header expired, so replicas answered "wrong jwt"
and the write failed with 500. With a write signing key, each forward now
carries a JWT signed right before it, after the replica lookup, for the
base file id the request was authorized for. A raw jwt= query field, which
the replica reads before the header, is no longer forwarded on writes.
Without a signing key the incoming Authorization header passes through as
before. Deletes are unchanged.

Mirrors the Go volume server change in #13028.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): take the replica forward key from the write auth snapshot

The replica JWT key was read from the guard again after the body was
read, so a reload that enabled write signing in between could sign
replica forwards for an upload that was never authenticated. Read it in
the same guard snapshot as the write's JWT check, as Go's PostHandler
does with writeSigningKey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): drop jwt query fields by decoded name on write forwards

Go's GetJwt decodes query names and reads jwt before the Authorization
header, so a forwarded %6Awt=x would still override the fresh JWT on a Go
replica. Drop every field whose decoded name is jwt from a write forward.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:42:33 -08:00
Lennart K. M. Schulz a409877b8f volume, operation: refresh the write JWT for replica forwards and filer-proxy retries (#13028)
* volume, operation: refresh the write JWT for replica forwards and filer-proxy retries

A write JWT is checked when a request arrives, but a slow chunk can take longer to stream in than the JWT lives.
The volume server then forwarded the already expired JWT to its replicas, which rejected it with wrong jwt, and the client retried through the filer with its own filer JWT, which by then had expired too.
Only a 401 marked as an expired volume JWT re-minted the filer JWT, so the 500 from the failed replica forward led to retries that could never succeed.

The volume server holds the signing key and has already authorized the request for this file ID, so it signs a fresh JWT for the forward; without a signing key it forwards the incoming one as before.
A filer-proxy upload re-mints its filer JWT before every retry, whatever the previous failure was.

Refs #6220

* volume: mint the replica forward JWT right before each forward

A JWT minted before the uncached master lookup spends part of its lifetime on that lookup, so the replica can still see it expire; minting inside the forward path gives each replica request its full lifetime.
Minting stays unconditional rather than forwarding a still-valid incoming JWT, which could expire in flight and reintroduce the failure.
The cost is a key rotation constraint: a new write signing key must be verify-only on every volume server before any server makes it current.

The base file ID trim moves into one helper so the authorization check, the expiry classification and the mint cannot disagree on which file ID a write JWT covers.
2026-11-26 08:42:25 -08:00
Chris LuandClaude Opus 5.5 d0661afad8 mount: refuse SSE-KMS and SSE-C objects the native read path cannot decrypt (#13027)
* mount: refuse SSE-KMS and SSE-C objects the native read path cannot decrypt

The native read check only recognized SSE-S3, so objects the S3 gateway
stored with SSE-KMS or SSE-C were read chunk by chunk and the mount
returned their ciphertext with success. Detect every S3 server-side
encryption type, from the object metadata or any chunk, and answer
open, read and copy_file_range with ENOTSUP unless the object is SSE-S3
and -sseS3Read routes it through a gateway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop S3 encryption markers when a file is truncated to zero

A full truncate removes the encrypted payload, but the object metadata
still named SSE-C, SSE-KMS or SSE-S3, so the plaintext the mount wrote
afterwards was refused on read. Clear those markers in SetAttr and
truncateEntry when the size becomes zero, and reset the handle's cached
classification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:41:20 -08:00
35caf2542c operation: report a delete result for volumes the lookup cannot locate (#12488)
* weed/filer: retry deletes when volume replicas are offline or missing

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>

* operation: assert one delete result per file id in the no-location test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: Tyagiquamar <mohdquamartyagi@gmail.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:38:30 -08:00
e9a5d733b1 weed: report host THP policy; build: declare Go 1.27.4 to match the releases (#13025)
* weed: report the host transparent huge page policy at startup

Go maps the heap with MADV_HUGEPAGE, so the host THP policy applies to a
SeaweedFS process whether or not the operator asked for it, and the advice in
the Go GC guide depends on the heap size. Operators had no way to see which
mode a node actually runs in.

Log enabled/defrag/khugepaged.max_ptes_none once at startup from the
long-running commands, and print the Go toolchain in `weed version` so a
support bundle identifies the runtime that produced the binary. Nothing
changes the policy: THP is host-wide, and GODEBUG=disablethp=1 remains the
only per-process control.

Refs #5437

* build: declare Go 1.27.4, the toolchain the releases already use

The 4.55 release binaries report go1.27.4 (`go version -m` on the published
tarball), while go.mod still said 1.26.6, the Dockerfiles pinned golang:1.26,
and the release workflows left the Go version to the action default of "the
latest stable at build time". A source build, a container and a downloaded
tarball therefore ran different toolchains from the same tag, and the next
release could silently pick up another one.

Set the go directive to 1.27.4 in the root module and in the four modules that
build in CI, bump the 16 Dockerfiles, and pin goversion: 1.27.4 in the 16
release and dev action steps.

`go mod tidy` now emits the two require blocks Go 1.27 expects; no dependency
version changed. Go 1.27's gofmt realigns 8 files.

* weed mini: report the THP policy after quieting stderr

The startup line ran from the dispatch point before runMini applied
quietMiniLogs, so every weed mini start on Linux printed it to stderr,
which mini keeps for the welcome banner, warnings and errors. Log it
from runMini after quietMiniLogs so it lands in the log file only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: report whether the Go heap can use huge pages

The runtime advises only GC metadata with MADV_HUGEPAGE and leaves the
heap arenas to the host default, so under enabled=madvise the heap stays
on small pages. The log still printed go_heap_disabled=false there, which
reads as "the heap uses THP". Report go_heap_thp, true only under
enabled=always without GODEBUG=disablethp, and drop the struct comment
that said the heap is mapped with MADV_HUGEPAGE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: count an inherited PR_SET_THP_DISABLE in go_heap_thp

A launcher can disable THP for the process with prctl, and children
inherit it, so enabled=always alone does not mean the heap gets huge
pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: read GODEBUG disablethp the way the runtime does

The runtime applies GODEBUG left to right, so with
disablethp=1,disablethp=0 the heap keeps THP, while the helper stopped at
the first disablethp=1. The helper also missed other nonzero values such
as disablethp=2, which the runtime treats as disabled, and trimmed spaces
around keys, which the runtime keeps. Take the last disablethp with an
integer value, treat any nonzero value as disabled, and match keys
exactly. The parser now takes the GODEBUG string, so it is tested without
changing the environment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: honor per-size THP policies in go_heap_thp

Since Linux 6.8 each anonymous huge page size has its own policy in
hugepages-<size>kB/enabled, and only "inherit" follows the top-level
knob. A 64kB size set to "always" gives the unadvised heap huge pages
under a top-level "madvise" or "never", and a 2048kB size set to "never"
takes them away under "always", but the log judged only the top-level
value. Read the per-size policies and report go_heap_thp=true when any
size reaches the heap. Under a top-level "never", the "disabled by the
host" line is now printed only when no size reaches the heap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: report go_heap_thp=unknown when the process setting is unreadable

If PR_GET_THP_DISABLE fails, for example because a seccomp profile
rejects it, the process THP setting is not known, but the log treated it
as allowed and could print go_heap_thp=true. Print go_heap_thp=unknown
in that case. It stays false when the host or GODEBUG already rules out
heap huge pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: report go_heap_thp=unknown when a per-size THP policy is unreadable

An unreadable hugepages-<size>kB/enabled was skipped, so the log could
say the host disabled THP while that size allowed it. Keep it as an
empty mode and report unknown unless a readable size already allows
huge pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: take the Go version from go.mod in tests and releases

posix-compliance pinned GO_VERSION 1.26 and built go 1.27.4 modules only
through the GOTOOLCHAIN auto-switch; nine workflows used go-version ^1.26 and
the kafka jobs ran in golang:1.26-alpine. Read the version from go.mod with
go-version-file, as the other setup-go steps already do, moving checkout ahead
of setup-go where it came after so the file exists. The posix report takes the
version from the setup-go output.

The release and dev builds pinned goversion 1.27.4 in 16 places. The pinned
go-release-action reads the go directive when goversion is go.mod, so the
binaries now follow go.mod without a second copy of the version.

* weed: report the THP policy from every long-running command

mount, worker, iam, master.follower, the filer sync/backup/remote/replicate
daemons and the mq agent and kafka gateway keep serving after startup like
the commands already listed; mount is likely where heap size matters most.

fuse is not listed: its first process starts a child with the same arguments
and waits, so logging at dispatch would print the line twice. It logs in
runFuse just before handing over to runMount, which only the child reaches.

---------

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-26 08:36:36 -08:00
77a6787335 Bound upload memory: admission by size, gateway holder writes, 503/SlowDown back-pressure, body deadline (#13021)
* util: one admission rule for upload limits

* operation: mark gateway fan-out holder writes as client traffic

* volume: bound upload admission, limit gateway holder writes, 503 on timeout

* volume: charge unknown-length uploads half the budget, document client wait cap

* s3, filer: admit uploads by inFlight+size and charge unknown lengths a chunk

* s3: answer a volume overload as SlowDown with Retry-After

* operation: cut an upload whose body crawls below the minimum rate on any host

* operation: make the slow-commit deadline test honour the request context

* s3: stop chunk uploads when the client goes away

* operation: treat a body deadline cut as back-pressure, not a same-holder retry

A body that crawls past the body deadline returns from retriedUploadData at
once, like an overload, and counts toward the single reassign the chunk loop
and the filer retry gate give back-pressure. A watchdog cut keeps its retry on
a fresh conn. Both still match ErrUploadStalled and stay reassignable.

* operation: apply the body deadline only to uploads that opt in

UploadOption.BodyDeadline and ChunkedUploadOption.BodyDeadline turn the
body deadline on; S3 chunk uploads (relay and fan-out) and the filer's chunk
loop set it. Mount, filer.sync, filer.copy and UploadWithRetry keep the stall
watchdog only, as before the deadline existed.

* s3, operation: check a chunk cancelled with its client is deleted from every holder

A volume commits on a context that ignores the cancel, so a chunk whose
caller went away after sending the body may still land. The chunk loop
already deletes the fid from every holder after a failed attempt; pin that
for the relay and fan-out paths and for an S3 PUT whose client goes away.

* s3: count a request's declared bytes in the circuit breaker byte limits

The per-bucket and global byte counters go back to the declared length (an
unknown length counts one chunk), so a bucket bytes limit still rejects a
single PUT larger than it. Only the upload budget uses the capped gateway
charge.

* s3: answer copy chunk overloads as SlowDown, tidy the client-gone checks

CopyObject and UploadPartCopy map a volume overload or an exhausted stall to
SlowDown, as PutObject does. The client-gone log check matches the mapper's
context.Canceled test, the truncated-body case drops a check the first case
already makes, and the Retry-After test reads the headers actually sent.

* filer, volume: clamp the filer charge chunk, set the upload gauge under the lock

A filer with -maxMB 0 charges its default chunk size instead of nothing. The
volume server sets its in-flight upload gauge inside the critical section.
The upload limit tests wait until the waiter is parked before releasing,
check handleUploadRequest gives its charge back, and use CI-safe bounds.

* volume: cap the Rust server's client upload-slot wait at 5s

Same cap as the Go volume server's volumeClientUploadWaitCap, so a gateway's
body deadline never fires before the 503.

* operation: reflow the body deadline comment

* volume(rs): count a gateway's src=client holder write against the upload limit

Mirrors operation.IsReplicaForward: only a primary-to-replica forward
skips the upload budget; a gateway's ?type=replicate&src=client fan-out
waits like any client write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): admit uploads by inFlight+size, reserved atomically

Mirrors the Go volume server's waitForUploadSlot: an upload is admitted
by util.UploadAdmits (idle server, or inFlight + size within the limit)
and reserves its bytes in the same step, so concurrent waiters cannot
all pass one check. Primary-to-replica forwards and unlimited servers
are counted but never refused. UploadLimitCond counts once per waiting
upload, and the wake-up is armed before each check so a release in
between is not missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): charge an unknown-length upload against the upload limit

Mirrors the Go volume server's uploadCharge: a chunked upload without
Content-Length reserves one file's worth of budget, at most half the
limit and at least 1 byte, instead of 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): a zero -inflightUploadDataTimeout waits the 5s client cap

The Go volume server now reads 0 as the 5s cap (its flag help says so);
the Rust server used a 2s wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): close a rejected large or unknown-length HTTP/1 upload

Mirrors the Go volume server's uploadRejectCloseThreshold: the 503 for
a body over 256 KiB, or one without a length, carries Connection: close
instead of keeping the connection for a body nobody reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): drop src from a primary's replica forward

A client upload carrying src=client kept it on the forward, so replicas
treated the forward as gateway fan-out and could refuse it after the
primary had already appended. Go's ReplicatedWrite builds a fresh query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep the upload admission CAS buildable on rust 1.91.1

Atomic try_update is stable only since 1.95.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): refuse an upload the in-flight counter cannot hold

A replica forward added its charge with fetch_add, so a Content-Length
near i64::MAX wrapped the shared counter negative and let later client
uploads past admission. The forward now reserves with a checked add and
answers 503 when the size does not fit; the client CAS adds only after
admission passes. With no upload limit the counter only feeds the gauge,
so it keeps wrapping arithmetic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: refuse an upload the in-flight counter cannot hold

A replica forward added its charge unchecked, so a Content-Length near
math.MaxInt64 wrapped inFlightUploadDataSize negative and let later
client uploads past admission. Under the lock the reservation now
checks that the counter can hold the charge and answers 503 otherwise,
matching the Rust volume server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: keep the request body on a rejected upload

Replacing r.Body with http.NoBody hid the server's early close of the
unread body from net/http before Go 1.27, so it skipped the FIN-then-wait
close and reset the connection under a client still sending. Go 1.26.6,
the version go.mod declares, then failed
TestUploadLimit503ReachesGoClientForLargeBody with a write error instead of
the 503.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: compare upload admission without forming inFlight+size

* operation: reassign a chunk after a 429 as after a 503

* s3: do not count a chunk assignment the client cancelled as a filer failure

* filer: charge an upload by its request chunk size, and an inline upload by its whole body

* s3: hold an aws-chunked body to its X-Amz-Decoded-Content-Length

* volume: answer a rejected small-body upload without waiting for its body

* s3: fill the upload budget before testing that a release wakes every waiter

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:34:47 -08:00
41f1c25d01 s3api: drop bucket size gauges on an instance that lost the metrics lock (#13019)
* s3api: drop bucket size gauges on an instance that lost the metrics lock

Only the S3 instance holding the s3.leader lock collects bucket sizes and
quota state, once a minute. An instance that loses the lock and keeps
running never clears what it set. bucketMetricTTLControl drops a bucket's
gauges only after 10 minutes without activity, and every request the
instance serves for the bucket counts as activity. So for the buckets
clients keep using through it, its bucket_size_bytes,
bucket_physical_size_bytes, bucket_object_count, bucket_quota_bytes and
bucket_read_only series stay at the values it collected last, next to the
new holder's current ones. Summing a gauge over instances counts those
buckets twice, and taking the max shows a bucket that has shrunk since at
its old size.

On every tick without the lock, reset these five gauges. Only the
holder's collection sets them, so an instance that never held the lock
loses nothing, and one that lost it stops reporting within a minute.

In a cluster with seven S3 instances, one kept 10 to 14 buckets at their
old values for four days after losing the lock; at one point the max
over instances put a bucket 37 TB above its size.

TestBucketSizeMetricsTickWithoutLockDropsGauges sets the gauges for two
buckets, checks that a tick with the lock leaves them, and that a tick
without it removes all five. Without the reset it fails for each gauge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: shorten the bucket size metrics lock-loss comments

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-26 08:31:16 -08:00
Chris LuandClaude Opus 5.5 d2276f531e master: apply the whitelist to management gRPC RPCs (#13022)
* master: gate operator-only management RPCs on the whitelist

CollectionDelete, DisableVacuum, EnableVacuum, VolumeGrow,
ResumeVolumeGrowth, LeaseAdminToken and ReleaseAdminToken now call
checkGrpcAdminAuth, matching the whitelist their HTTP counterparts
already enforce. VolumeGrow stays open to the in-process growth loop,
and callers on the local gRPC socket of weed server/mini are local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: admit unknown masters over KeepConnected only from the whitelist

A KeepConnected registration as a master pulls that address into the
raft quorum. Accept it from any caller only for this master and its
-peers; any other master address now needs a whitelisted caller, the
same check RaftAddServer applies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: test that every RPC is gated or listed with a reason

Port the volume server's coverage test so a new master RPC cannot skip
checkGrpcAdminAuth without an explicit exemption. The proto and AST
helpers now take the proto file and receiver name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: admit callers on the local gRPC socket

weed server and weed mini route same-host gRPC dials through a unix
socket, whose peer address carries no IP. With -whiteList set the
volume server refused the in-process master's AllocateVolume, so no
volume could be grown. The Rust volume server serves gRPC over TCP only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: match a KeepConnected master against configured peers by gRPC endpoint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: bind the local gRPC socket for the owner only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: warn when a deleted bucket's collection is left on the master

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pb: bind the local gRPC socket in a private directory before moving it into place

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: report an unconfirmed bucket collection delete as such

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:27:35 -08:00
Chris LuandClaude Opus 5.5 a00dbff13b sftp: apply the bucket's default Object Lock retention to uploads (#13017)
* s3_objectlock: read a bucket's default retention from its entry

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: give uploads into an Object Lock bucket its default retention

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: match uploads against the cleaned buckets folder

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:25:48 -08:00
Chris LuandClaude Opus 5.5 87ee3c57cb s3: keep the EOF read out of the timed body in the put stage test (#13016)
* s3: do not delay the EOF read in the put stage timing test

TestPutStagesRecordEachStage checks that the storage stage is at least
5ms. That stage is the second chunk's assign wait (20ms) minus the final
read that only returns EOF, which slowReader also delayed by 10ms. When
busy goroutines hold every P, the reader's wakeup can lag the assign's
by as much as a preemption slice, and storage drops below the floor.

slowReader now delays only reads that return data, so the EOF read is
instant and storage covers the whole assign wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep the EOF read out of the timed body in the put stage test

Skipping the delay on the EOF read still left that read inside
timedBody, so a stall there was subtracted from storage. Feed the upload
through an eight-byte limit instead: the final EOF comes from the limit
reader without reaching the timed body, so storage always covers the
second chunk's full assign wait. slowReader goes back to delaying every
read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:24:58 -08:00
dcce121d95 weed fix.recover: recover needles past damaged .dat regions (#13002)
* feat: weed fix -verify to resync past damaged regions in .dat

Plain `weed fix` walks .dat by trusting each needle header, so a damaged
region in the middle loses or misindexes everything after it, and a torn
or garbage tail ends up in the index and keeps the volume read-only.

-verify reads every needle, checks structure and CRC32, and on a failure
searches forward at needle alignment for the next verifiable needle. Each
skipped region is reported as zero-fill / garbage / garbage+zeros with its
length, zero windows and the fid of the needle that was hit. The index is
rebuilt from verified needles only (old one kept as .idx.bak); -truncateTail
cuts trailing garbage so the load-time integrity check passes, -dryRun only
reports. Works with the 5BytesOffset build.

* feat: add weed fix.verify, a read-only check of .dat files

Runs the same needle/CRC verification and resync scan as `weed fix -verify`
but never writes: no .idx rebuild, no truncation. Takes folders and/or .dat
files, filters with -collection / -volumeId, prints the damaged regions
(optionally to -report) and exits 0 when clean, 3 when damage was found and
1 when a file could not be verified. The scan options are shared with
`weed fix -verify`.

* feat: weed fix -compact, verify and compact a damaged volume in one pass

-compact implies -verify. While the .dat is scanned, every verified needle
gets an index entry, and from the first damaged region in the middle of the
file the needle bytes are streamed into a new .cpd as well (the intact prefix
before it is copied as one block). The result is a .dat without the damaged
regions and an append-ordered .idx that matches it exactly, so a full volume
scrub no longer complains about the .dat size. The compaction revision is
bumped like a vacuum does.

A volume without damage is left untouched, and damage only at the tail is just
cut off in place, so neither costs a .dat copy. The old .idx is kept as
.idx.bak and the old .dat as .dat.bak (-deleteOriginal removes it). The free
space needed for the new .dat is checked before anything is written, a failing
swap is rolled back, and progress is printed every 30s.

* refactor: reuse backend, super block and throttler code in weed fix -compact

- create the .cpd with backend.CreateVolumeFile and preallocate the bound of
  the new .dat; the result is truncated to its real length at the end
- read the super block with super_block.ReadSuperBlock (also in the verifier)
  and write the bumped compaction revision with SuperBlock.Bytes()
- throttle the .dat writes with util.WriteThrottler (-compactionMBps)
- fsync the directory before and after swapping the new files in

ReadSuperBlock cannot read a super block with extra data, so such volumes are
rejected with its error instead of being handled by a hand-written parser.

* refactor: drop helpers that duplicate existing code in weed fix -compact / fix.verify

- util.FsyncDir instead of a local fsyncDir
- io.NewOffsetWriter instead of a hand-written WriterAt adapter; the throttle
  now sits in one small writer wrapper used for both the prefix copy (via
  io.CopyBuffer) and the streamed needles, replacing the manual copy loop
- needle.NewVolumeId instead of strconv for volume ids parsed from file names

* fix: resync in weed fix -verify must not accept payload-less look-alikes

After damage, a few bytes of a needle's tail followed by the next record's
header could parse as a payload-less needle and be confirmed only because the
file ended right after it, so a made-up key got into the index and swallowed
the real delete record behind it.

A payload-less candidate is now accepted without a verifiable successor only
if it is a size-0 tombstone ending exactly at the end of the file (or, with a
set timestamp, leaving less than a header); a set but implausible v3
timestamp rejects it. Anything else needs the next needle to verify.

* test: recovery integration tests for damaged .dat heads (#5674, #12914)

- zero-filled head (aligned and cut next record): all survivors indexed,
  region reported as zero-fill, trailing tombstone kept
- plain weed fix stops at the first bad header (#12914 item 1) while
  -verify recovers the needles behind it
- a needle rewritten after a damaged region is indexed at its newest copy
- a zeroed superblock fails with an explicit unsupported-version error and
  fix.verify counts it as not verifiable (exit 1)
- v1/v2 needle layouts verify cleanly

* fix: reject a super block extra in fix -verify

A super block extra describes an erasure-coded layout; the .dat behind it was
re-striped into .ecXX shards and is not a plain needle file. Scanning it as
one silently produced damage reports instead of telling the operator the file
is out of scope. Return an explicit error instead.

* fix: guard fix -verify/-compact against pending compaction commits and -dir.idx

- refuse to start while a .cpc marker exists: an interrupted vacuum commit is
  pending and the volume server must reconcile it first (roll forward/back);
  writing a rebuilt .idx or new .cpd/.cpx over that decision would race it
- clear a stale .cpc after a completed swap so it can never be rolled forward
  later (defensive; the start guard already refuses this state)
- spell out in the help and print after a rebuild that the index is written
  next to the .dat: with a separate -dir.idx directory the .idx must be moved
  there and any stale .ldb dropped
- tests: refusal leaves the marker and writes no .idx; a completed swap clears
  a marker that slipped past the guard

* refactor: narrow this change to weed fix -verify

Drop weed fix.verify and weed fix -compact from this change; they follow in their own pull requests. -report, -windowMB and -zeroWindow go with them: the scan uses fixed windows and prints its report to stdout.

* fix: weed fix -verify: address review findings

- -maxNeedleSizeMB limits only guesses made while resynchronising; a record
  reached at a known boundary may be as large as the file allows
- a v2/v3 record whose parsed fields do not add up to its size, or a live
  record without data, is damage: a zero fill over the data length used to
  pass as an empty file because the CRC is only checked when there is data
- a stamped v3 delete record found after damage stands on its own when its
  time is believable, not older than the last verified record and followed
  by zero padding, so a delete before a damaged tail is not lost
- a read error while searching for the next needle fails the run instead of
  ending the scan and treating the rest as a garbage tail
- keys whose newest record is damaged while an older copy is indexed are
  reported as stale-version warnings
- the rebuilt index is staged as .idx.tmp and swapped in when complete; a
  stale .ldb next to it is removed so the volume server rebuilds it
- -ignoreError reports a volume that cannot be verified and goes on
- -truncateTail does not cut a tail it could not read and removes a partial
  tail backup
- volume ids are parsed as uint32
- the test fixture stamps every record the way the volume server does

* fix: weed fix -verify: prove deletes found after damage, swap the index safely

- a delete record found while resynchronising must prove itself: a v3 one
  needs a believable time not older than the last verified record and zero
  padding (every v3 writer stamps deletes); a v1/v2 one needs the following
  records to reach data that passes its CRC, or the exact end of the file.
  Stray bytes in a zero-filled region used to pass as deletes of live keys.
- the rebuilt index is fsynced before the swap, the previous one is kept as
  a hard link, and the new one replaces it in one rename, so a live .idx
  exists at every moment
- .sdx and .rdb caches are removed with the .ldb
- -verify exits non-zero when it found damage, like plain fix and -verifyCrc
- with -ignoreError a file name whose volume id does not fit uint32 is
  reported and the batch goes on
- the help and the printed hint say that a volume server prefers an .idx
  next to the .dat over the one in -dir.idx

* fix: reject weed fix flag combinations -verify cannot honour

-verify -remoteFile skipped an explicit .dat and reported success, -dryRun
and -truncateTail were silently ignored without -verify, and -dryRun -ecx
still rebuilt EC indexes. Check the combinations before any file is touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: apply -volumeId before rejecting an out-of-range volume file name

With -volumeId set, an unrelated file such as 4294967296.dat aborted the
run before the filter could skip it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: check the data length before reading a record body in fix -verify

A damaged size field at a known record boundary made the scan allocate and
read a body of that size before rejecting it. Check that the data length
after the header fits the record first, as the resync probe already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: accept a v1/v2 delete chain that reaches the end of the file on its last probe

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep an implausible needle timestamp out of the fix -verify resync baseline

The data CRC does not cover the v3 timestamp, so a corrupted one passed and
then rejected every genuine delete record found after later damage. Report
it as a warning instead of using it as the lower bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: stop fix -verify on a read error at a known record boundary

An EIO while reading a record was treated like damaged bytes: the scan
resynchronised past the unread record and the rebuilt index dropped it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: sync the fix -verify tail backup before truncating the .dat

A crash right after the truncate could persist it before the backup's data
or directory entry, losing the cut bytes from both files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: let fix -verify -truncateTail retry when a tail backup already exists

After a backup succeeded and the truncate failed, the next run hit the
existing backup and could not get past O_EXCL. Keep the first backup and
save the tail under a new name, as the index backup does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: drop stale index caches before fix -verify swaps in the new index

Removing them after the rename left a window where a crash paired the new
.idx with the old .ldb, whose newer LOG skips the replay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: pin fix -verify fixtures to needle version 3

-verify reads v1 to v3 records, so its fixtures should not follow the
build's current needle version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse fix -verify on remote-tiered volumes

A remote-tiered volume is read from its remote .dat through the existing
.idx, so rebuilding that index from a local .dat would point it at the
wrong bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: pick a free backup name when fix -verify retries within one second

backupName fell back to path.bak.<unix time> without checking it, so a
second retry in the same second reused that name and the exclusive
create (or the .idx hard link) failed. Add a .<n> suffix until the name
is free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse fix -verify when the volume info cannot be read

An unreadable or unparsable .vif may name a remote tier, so treat it like one
and keep the existing index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: pass weed fix -verify options explicitly

* feat: move weed fix -verify into a weed fix.recover command

* docs: weed fix.recover help, point weed fix at it

* fix: keep the volume file helpers below runFix

Leaves the region between VisitNeedle and runFix as on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: build fix.recover fixtures at needle version 3

fix.recover reads needle versions 1 to 3, so its tests must not follow
GetCurrentVersion; writeFixTestVolume now takes the version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: whitefox <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-26 08:24:05 -08:00
25f7e8a0fd filer: refuse chunk appends onto inline and remote-only entries (#12993)
* filer: refuse unsafe chunk appends

* filer: report append representation preconditions

* filer: cover cached remote append eviction safety

* filer: cover lazy remote append refusal

* filer: refuse HTTP appends and offset writes onto remote-only entries

An HTTP append or offset write onto a remote-only entry stored the new
chunk with nothing below it, so reads returned zeros where the remote
bytes were and the entry stopped being remote-only. Small appends failed
with a retryable "inline file changed" error instead.

Refuse both with a client error, matching AppendToEntry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: AppendToEntry appends after a sparse tail

AppendToEntry placed new chunks at the end of the existing chunks, so a
file extended past them by a truncate got the appended bytes inside its
logical length instead of after it, and its size did not grow. Use the
entry size, as the HTTP append path does.

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-26 08:22:46 -08:00
Chris LuandClaude Opus 5.5 d2ae75516c notification: keep chunk cipher keys out of webhook payloads (#13014)
* filer_pb: scrub cipher keys from both entries of an event

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* notification: keep chunk cipher keys out of webhook payloads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:21:09 -08:00
Chris LuandClaude Opus 5.5 50fd5c0185 codespell: accept the Yandex Disk sandbox URL path (#13015)
* codespell: accept the Yandex Disk sandbox URL path

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* codespell: ignore poligon only inside URLs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:18:50 -08:00
f079b68f2b filer: grpc_require_token with authenticated filer-to-filer peer calls (#13011)
* filer: require bearer tokens for configured gRPC calls

* filer: authenticate owned peer RPCs with per-call admin tokens

* filer: retain scoped forwarding refusals with required authentication

* filer: preserve tokenless HTTP forwarding outside require mode

* filer: honor clock tolerance for gRPC admin fallback

* filer: preserve caller token on lock owner forwards

* filer: forward caller auth on target ping

* filer: authenticate startup peer digest checks

* filer: verify required subscription bearers independently of mTLS

* filer: assert exact caller bearer on forwarded ping

* filer: sign peer tokens with the gRPC verification key

peerContext signed filer-owned RPCs with jwt.filer_signing.key only. With
grpc_key as the only key and require-mode on, peer calls went out tokenless
and were refused. With both keys set, peers that verify with grpc_key and
lack the shared-key admin fallback refused the shared-key token even with
require-mode off. Sign with the key filesystem gRPC verifies, and keep the
shared key for metadata subscriptions, whose verifier accepts admin tokens
signed only with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a subscription token's scope over mTLS in require-mode

Require-mode admitted a dedicated subscription bearer without the mTLS
shortcut, but the handler re-checked it with the certificate, which
granted the full stream past the token's prefixes and expiry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: delete uploaded chunks when the write owner refuses authentication

A forwarded HTTP append or offset write that the owner refused as
Unauthenticated kept its new chunks as if the outcome were unknown,
orphaning them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: hand the admitted subscription scope to the handler

The handler re-verified a dedicated subscription token after reading the
request. If the token expired in between, an mTLS peer fell back to the
certificate and got an unrestricted stream. The interceptor now passes
the scope it admitted, and the handler refuses it once expired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: accept grpc_key admin tokens on metadata subscriptions

A filer with only grpc_key signs peer subscriptions with it, but the
subscription verifier checked admin tokens against the shared key only,
so with a subscribe key set the aggregator's peer streams were refused.
An unscoped grpc_key token already has full filer gRPC access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: delete the generated manifest when the write owner refuses authentication

A forwarded HTTP append that crossed the manifest threshold left the
manifest blob it had uploaded orphaned when the owner refused the call
as Unauthenticated. The blob alone is deleted, since the manifest also
lists committed chunks.

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-26 08:18:28 -08:00
github-actions[bot] 519c2af3c8 docs: regenerate star history chart 2026-11-26 02:08:47 +00:00
a1764358cf filer, mount: keep a hard-linked file to one link id and count its names on the filer (#13006)
* filer, mount: keep a hard-linked file to one link id and count its names on the filer

A hard link's bookkeeping was done by the client. To link a file a mount
reads its entry and sends two writes, an update of the source and a create
of the new name, both with a link id and a count of the file's names. Two
clients that link one file at the same moment each worked from the entry
as it was before the other's writes:

- With no link id on the entry yet, each made one up. The second update
  moved the source to its id, the store took the name off the first, and
  the first client's new name was left alone on it: one file's chunks
  under two link ids.
- With a link id there, both read the same count and sent it plus one.
  The record counted one name fewer than the file had. Any write through
  a name carried the client's copy of the count and replaced the record
  the same way.

Either way the delete of the last counted name deleted the record and the
chunks while another name still read them.

The filer's own store now counts the names of a hard-linked file itself
(countLink): one more when the name written did not hold the link before,
the same when it did or when a rename moves it there (WithMovedLink), one
for a record that starts. The count sent is not used, and the entry gets
the count stored, so the response and the event carry it. The lookup of
the name, the count, the record and the name are stored as one change of
the record (changeLinkRecord), which DeleteHardLink goes through as well:
under a lock per link id, and in a transaction where the store refuses a
commit over a change made since it began, run again when it does. A
wrapper around a copy of some entries, such as a mount's metadata cache,
sees only some of the names and stores the count it is given.

UpdateEntry refuses to give a name that holds a hard link another link id
that no file has yet (refuseSecondHardLink). The mount sends a file's
first link's update as a unary RPC, which keeps that refusal apart from
an I/O failure, reads the entry again and links under the id the file has
by now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: take a replicated update's link id without refusing it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: look a path-specific name up outside the record's transaction

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: check the leveldb open and close it in the hard link test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: send a refused first link again from the entry as stored

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a first link's refusal over the next filer's error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: count a hard link's names next to the clients' count instead of in its place

The filer's count replaced the one clients send, which lost two things
that count did by being worked out ahead:

- A link's first write, the update of the source, carries the count with
  the new name in it already. While the second write is on its way that
  kept a delete of the source from being taken for the delete of the
  file's last name (lastLinkDropped goes by the count it read), and the
  chunks from being deleted under the name about to come. Counted only
  when it arrived, the new name was stored with chunks that were gone:
  104 of 300 rounds of a mount linking a file while another deletes it.
- A write of a name the store refused had counted the name already, and
  sent again counted it once more.

The filer now keeps its count of the names in a key of its own next to
the record (linkNames), written once the name is stored, and the record
gets whichever is higher: the count the client sent or the names counted.
It is never lower than what the client alone would have left, and never
lower than the names the file has. A record from before has its count
recorded as the names when it is first written again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: send a refused first link again with the file's inline content

The second attempt builds the new name's create from the entry as the
filer has it by now: attributes, chunks and extended attributes. A file
the filer keeps inside its entry has its bytes in Content, and the create
is what the filer writes the link's shared record from, so without them
the record lost the file's content.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: store a path-specific name before the record's lock is let go

A second create of the same new name on this filer took the lock between
the first one's count and its name write, missed the name, and counted it
again: the file's record and chunks then outlived its last name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: keep a link's names key out of the keys of a directory's entries

The key began with the link's random id. One that began as the root's
entry keys do in a store keyed by path put the names' 4 bytes in the
root's listing, and it failed to decode: listing / and the etcd scan
under fsck failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: record a hard link's name before it is stored, and take it off if it is not

The names counted for a hard link were recorded once the name was stored.
On a store without transactions a failure of that write left the name
stored and not counted, and the write sent again found the name there and
did not count it either: the names recorded stayed one below the names
stored, the side a file is deleted under a name from.

They are recorded first now, inside the change of the record that counted
them, and a name the store then does not take is counted off again
(storeCountedName). A failure halfway leaves them one above the names
stored, and the file leaked. A name in a path-specific store is recorded
with the record as well, and counted off in a change of its own.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: keep a hard link's name counted when a failed write stored it

A write whose deadline passes after the store took the name returns an
error, and counting the name off then left the names one below the names
stored. A later write with the count from before the link lowered the
record to them, and the file was deleted under a name it still had. Read
the name back first, and keep it counted where that cannot be told.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: carry the stored RemoteEntry into the name a retried first link adds

The retry rebuilds the new name from the entry the file has once another
client linked it, but kept the RemoteEntry of the entry first read.

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-25 17:54:56 -08:00
73e335a073 test/s3: run rclone fstests in CI with an expected-failures list (#13013)
* test/s3: result checker for rclone fstests

* test/s3: run rclone fstests against SeaweedFS with expected failures

* ci: add rclone fstests workflow

* test/s3: catch parent-only failures and panics in rclone fstests check

* test/s3: check parent assertions and skips in rclone fstests, widen paths

* test/s3: drop issue numbers from the rclone expected-failures notes

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-25 17:32:38 -08:00
fb0a734dc4 feat(remote_storage): add Yandex Disk as a remote storage backend (#13012)
* feat(remote_storage): add a Yandex Disk backend

Yandex Disk joins s3/gcs/azure as a remote storage type, so it can back
remote mounts and sink replication (filer.remote.sync, filer.remote.gateway)
without a separate sink.

The Disk API has no buckets and no place for a file's mtime: a top-level
folder under yandex_root plays the bucket, and the entry's modification time
and content encoding travel as custom resource properties (seaweedfs_modified,
seaweedfs_content_encoding; rclone_modified is read too). The client also
handles the API's asynchronous operations (202 + operation polling), the
short-lived, single-use download links (a fresh link per read and per retry),
single-PUT uploads, mkdir -p of an S3-style key's parents, server-side copy
for a remote-only rename, and a ranged read that refuses a short body.

A caller-supplied endpoint goes through the guarded client like the s3 and
azure endpoints.

* feat(shell): configure and issue Yandex Disk tokens

remote.configure gains the yandex flags (token, client_id, client_secret,
root, trash, app_folder, endpoint). A refreshable token is issued in two
steps without a browser on the server: -yandex.oauth_url prints the
authorization url and keeps the app credentials, -yandex.code exchanges the
copied code for a token and stores it. The token and the client secret are
masked in the configuration listing.

docs/remote-storage-yandex.md walks through the OAuth app, both token flows,
the mount and replication commands, and the platform's limits.

* fix(remote_storage): handle missing Yandex folders on stat, copy and upload

A missing object is confirmed against the bucket folder rather than its
immediate parent, as the gcs client does: a key whose subfolder does not
exist yet (a rename destination) is a missing object, not a vanished mount,
and the sync only proceeds on ErrRemoteObjectNotFound.

CopyFile creates the destination's parent folders, so a remote-only rename
into a folder the remote does not have yet succeeds. The Disk API answers a
missing parent with 409 DiskPathDoesntExistsError; upload and copy treat it
like a 404, and the fake answers the way the API does.

An operation poll refreshes the token once on 401 and then fails, instead of
polling without a pause until the operation deadline.

* fix(remote_storage): retry a locked Yandex resource

A folder that is still being deleted asynchronously answers a write with
423 DiskResourceLockedError for a moment. The client now retries it with the
same backoff as 429/5xx/509, and the error stays transient for the sync's
upload retry when the client's retries run out.

* fix(remote_storage): harden the Yandex backend after review

Traverse reports objects only, like the s3, gcs and azure clients: its
callers (remote.cache, remote.copy.local) read the stamp of every entry, and
a folder came with none.

Deletes no longer reach what they were not meant for. A Disk API delete is
recursive, so DeleteFile keeps a folder that took a file's place on the
remote, and DeleteBucket removes an empty bucket folder only, the rule S3 and
GCS apply to a bucket.

CopyFile keeps the destination until its replacement exists: it copies with
overwrite and removes the old object (to the trash when configured) only when
the service kept it anyway. It refuses to replace a folder, treats a copy
onto itself as done, and carries the source's resolved modification time,
including rclone_modified and the service's own time.

Every metadata request and operation poll has a deadline that covers
reading the answer, and a token refresh or code exchange has its own, so a
stalled endpoint cannot block the client. Redirects are checked like the
transfer links, an endpoint that would send the token over plain http is
refused unless it is on a loopback host, a 202 without an operation link is
an error, and a read with an offset and no size starts at the offset.

* chore(seaweed-volume): keep only the Yandex fields in the remote.proto copy

* yandex: retry a failed operation poll

One throttled, failed or timed-out status poll ended a wait of up to 30
minutes while the operation kept running on the service, so a large
delete or copy was reported failed and redone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* yandex: refresh a token once for concurrent 401s

Every request rejected with the same access token replaced the token
source, so N concurrent 401s refreshed, and rotated the refresh token,
N times.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* yandex: retry an operation poll whose answer was cut short

A status poll that got its 200 headers but lost the connection before the
JSON body ended failed with io.ErrUnexpectedEOF, which the poll retry did
not treat as transient, so the wait ended while the operation kept running.

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-25 17:31:14 -08:00
5e796fa985 mount: keep a file's inline content when it is written to or resized (#13009)
* mount: keep a file's inline content when it is written to or resized

A small file the filer keeps inside its entry (-saveToFilerLimit, or
?saveInside=true on the upload) has its bytes in the entry's content and
no chunks. A mount dropped the content at the first write to the file, or
copy into it, and published the write's chunk alone: the bytes the write
did not cover read as zeros from then on, for an append as for two bytes
in the middle. A change of size left the content as it was. Grown, the
file read no further than its content on the mount and as zeros through
the filer; cut and grown again, it had the bytes that were cut off back.

The content now becomes a write of the handle's own, older than the one
about to change the file, and is flushed with it as a chunk
(bufferInlineContent: Write, CopyFileRange, Fallocate). SetAttr cuts it to
a smaller size, and stores it as a chunk before the file grows past it
(resizeInlineContent).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: store resized inline content in chunks of the mount's chunk size

A file that grows past its inline content had the content stored as one
chunk, whatever its length, where a buffered write is split at the
mount's chunk size: content longer than a volume server takes in one
upload could not be stored, and the file could not grow.

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-25 17:29:28 -08:00
bd1f24a09b mount: carry a file's inline content into the name a hard link adds (#13008)
* mount: carry a file's inline content into the name a hard link adds

A small file the filer keeps inside its entry (-saveToFilerLimit, or
?saveInside=true on the upload) has content and no chunks. To link it a
mount updates the source and creates the new name, and the filer writes
the link's shared record from each of the two. The create carried the
source's attributes, chunks and extended attributes but not its content,
so the record was left with a size and nothing behind it: both names read
zeros from then on, through the mounts and through the filer.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: carry a remote-only file's RemoteEntry into the name a hard link adds

A file under a remote mount that is not cached yet has no chunks and no
content; its RemoteEntry is what sends a read to fetch the object. The
create of the new name left it out, so the hard link's shared record lost
it and both names read zeros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: cache a remote-only file before a hard link gives it a new name

The filer resolves a remote object from the name a read goes through, and
the new name has no object of its own, so a read through it failed until
the source name had been read. The link now has the filer cache the
object first, so every name shares its local chunks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: cache a linked remote-only file through its open handle

The cache moved the stored entry off the base of a handle open on the
source, so the handle refused the link change and its next flush failed.
A handle with buffered writes now publishes them first, and the cache
goes through the handle as a read does, which moves its base along.

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-25 17:28:56 -08:00
8abfdf1e21 s3: abort in-flight requests whose access is revoked (#12986)
* s3: abort in-flight requests whose access is revoked

S3 checks access when a request starts, so a download or upload that
started before an identity, policy or bucket policy change runs to its
end. With -s3.abortRevokedRequests the gateway re-checks the requests it
is serving after such a change and aborts the ones now denied: an
HTTP/1.x request has its connection closed, an HTTP/2 request is
canceled.

The re-check looks the identity up again and repeats only authorization,
not the signature check, so clock skew or an expiring presigned URL never
cuts a long transfer. Off by default.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* s3: check revoked requests against whole reloads and configured identities

- A re-check pass holds reloadMu, so it never sees identities installed
  before their policies are synced.
- STS and JWT sessions are not tracked: re-validating their token checks
  its expiry, which a re-check cannot tell from a revocation.
- A request whose access changed while it was being admitted is checked
  again once it is tracked.
- The identity source comes from how the request authenticated, and a
  rotated secret revokes the requests signed with the old one.
- An aborted HTTP/2 request also has its body closed.
- Browser form uploads, which their handler authorizes, are not tracked.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* s3: track SigV2 requests that carry a session token

SigV2 never reads a session token, so a configured key that sent one was
classified as a session and skipped the re-checks. Only SigV4 resolves a
token, and it marks one it tolerated for a configured key ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: let the admission-race test pass only through the generation check

The re-check that the change schedules could run after the request was
tracked and abort it, so the test passed without the generation check.
Wait for that pass to take its snapshot before the request starts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: drop the executable bit from the revocation test file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: bump the re-check generation before its scope can be taken

scheduleRevalidation released t.mu before bumping the generation. A
pass already kicked could take the new scope in between, before a
request was tracked, and that request then saw the old generation and
was never checked again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: judge a re-checked request as of when it was admitted

A re-check evaluated aws:CurrentTime and a key's expiration at the time of
the pass, so an unrelated change aborted a transfer whose time-bounded
grant expired after it started. The re-check's copy of the request now
carries its admission time, which RequestConditionValues uses for
aws:CurrentTime and aws:RequestTime, and a key's expiration is compared
with it too.

A test covers a revoked HTTP/2 upload: closing its body releases the
blocked read, and a download on another stream of the same connection
runs to its end.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* stats: let http.ResponseController reach the writer under StatusRecorder

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: reset a revoked HTTP/2 request's stream

A deadline in the past resets only that stream, so a download blocked
writing to a client that stopped reading is released too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: keep in-flight requests when their key's secret is rotated

A new secret for the same access key is a rotation, not a revocation.
Removing or deactivating the key, or losing the grant, still aborts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: always abort in-flight requests whose access is revoked

Drop -s3.abortRevokedRequests: the gateway tracks the requests it admits
and re-checks them on every change that can revoke access, so a revoked
client's transfers stop without a restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: a catch-up re-check does not advance the revocation generation

A request tracked after an access change scheduled its bucket's re-check
through the same path as the change, which advanced the generation again.
A request that began authenticating before that advance then scheduled
another bucket-wide re-check, so overlapping admissions could keep the
re-check loop busy, holding reloadMu, with no access change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Copilot <223556219+Copilot@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-25 17:27:04 -08:00
Chris LuandClaude Opus 5.5 802be6dd7b volume: vacuum keeps a needle's own unexpired TTL and checks against an independent index tally (#12987)
* volume: vacuum keeps a needle's own unexpired TTL on a volume without TTL

Vacuum measured a needle's expiry against the volume TTL. On a volume
without TTL that is zero, so every needle carrying its own TTL was
dropped by the first vacuum while reads still served it. Fall back to
the needle's own TTL and append time, the rule reads use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): vacuum applies a needle's own TTL on a volume without TTL

Rust vacuum kept every needle with its own TTL on a volume without TTL,
even long after reads stopped serving it. Use the read path's expiry
rule there, matching the Go vacuum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: check vacuum against a tally taken while loading the index

The compacted-size check summed its expected bytes inside the loop that
copies, so an entry the traversal never visited was missing from both
sides and the check could not see it. Tally the live entries while
replaying the .idx rows, count every copied, expired and unreadable
needle, and fail when they do not add up to the snapshot. The explicit
accounting also covers volumes with a TTL, so they are checked too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): check vacuum against a tally taken while loading the index

Mirror the Go change: tally the live entries while replaying the .idx
rows, count every copied, expired and unreadable needle, and fail when
they do not add up to the snapshot, on volumes with a TTL too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: treat a TTL flag without TTL bytes as no TTL

A record can set the TTL flag and end before the TTL field, leaving
Ttl nil. Checking such a needle's own TTL panicked in reads and, now,
in vacuum on volumes without TTL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: log each TTL-expired needle vacuum drops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): log each TTL-expired needle vacuum drops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:20:37 -08:00
Martin Lettry e13f36275b filer: rename a directory that holds a hard link on SQL stores (#13001) 2026-11-25 13:18:02 -08:00
Gal Be 432826f1b2 filer: allocate the interval points of readResolvedChunks at once (#12995) 2026-11-25 13:16:23 -08:00
ff80650b85 feat(helm): optional volumeAttributesClassName on every PVC (#12996)
* feat(helm): optional volumeAttributesClassName on every PVC

The chart's claims only take storageClass, size and annotations, so
provisioned performance (IOPS/throughput on GKE Hyperdisk, EBS gp3,
Azure Premium v2) can only be set through a custom StorageClass. A
VolumeAttributesClass is the Kubernetes way to do that and can be
changed later without recreating the volume.

Every claim the chart renders now takes an optional
volumeAttributesClassName next to its storageClass: master.data/logs,
filer.data/logs and the deprecated filer.volumeAttributesClassName,
admin.data/logs, volume.dataDirs[]/idx/logs (and volumes.<name>), and
allInOne.data. It is rendered only when set, so default renders are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: quote volumeAttributesClassName so names like 2026 or null stay strings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* helm: say existing claims need a patch to change their volumeAttributesClassName

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-25 13:13:58 -08:00
37c0b2f162 webdav: store a real md5 for each uploaded chunk (#12988)
* webdav: store a real md5 for each uploaded chunk

Chunks written through the shared gateway uploader had no md5, so the
file ETag was built from empty digests: every overwrite of a multi-chunk
file kept the same ETag (If-None-Match answered 304 for new content) and
single-chunk files had no ETag at all. Ask the uploader for Content-MD5,
as mount and filer.copy already do.

* webdav: quote the ETag it serves

DAV:getetag and the ETag header must be entity-tags. A bare digest never
matches a client's quoted If-None-Match or If-Match in http.ServeContent,
and single-chunk files now carry a digest instead of webdav's quoted
fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: serve no filer ETag built from chunks without digests

Files written before chunks carried an md5 all hash to the md5 of empty
digests plus their chunk count, so unrelated files with as many chunks
share one tag and a conditional GET can answer 304 for changed content.
Leave the tag to webdav's modtime and size fallback for those.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: answer a PUT with the ETag of the content it committed

webdav.Handler stats the file before Close uploads the last chunk and
updates the entry, so every PUT answered the empty created entry's tag
and an If-Match with it failed against the stored file. Close now
records the committed entry's tag on the PUT outcome and the response
writer sends it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: serve no filer ETag for inline content without an md5

filer.ETag hashes only the chunk list, so every inline entry without
Attributes.Md5 gets the empty-list tag. Fall back to webdav's own tag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: upload the PUT test's chunk during Close

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: tag inline content without an md5 by its bytes

The modtime+size ETag webdav derives matches two equal-size contents stored
in one second, so a replace could answer 304. util.Md5 follows the
cluster's digest, which fips140=only keeps off MD5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: tag chunks stored without digests by their file ids

The modtime+size ETag webdav derives matches two equal-size files stored
in one second. A rewrite stores new chunks, so their file ids and
placement tell contents apart.

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-25 13:13:07 -08:00
Chris LuandClaude Opus 5.5 a5e52b68f1 server, filer, s3: log downloads the client hung up on below error level (#12991)
* server: log a response the client hung up on below error level

A client that closes a download early (a video player seeking, a browser
cancel) fails the next response write with a broken pipe, a connection
reset, or an HTTP/2 stream close, and ProcessRangeRequest logged each one
as an ERROR. net/http cancels the request context once a write to the
client fails, so a canceled context now logs at V(3); a failure under a
live request still logs as an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: log a stream the client hung up on below error level

The filer logged "failed to stream content" as an ERROR for every
download a client closed early, next to ProcessRangeRequest's own line.
It now goes through the same check, so only a failure under a live
request reaches the error log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: log a GET the client hung up on below error level

A client closing a download early made GetObject log two ERROR lines,
from streamFromVolumeServers and from GetObjectHandler, and the SSE copy
paths logged a third. The write fails with a broken pipe or connection
reset rather than context.Canceled, so the canceled-stream check missed
it. net/http cancels the request context once a write to the client
fails, so streamCanceled also treats a canceled request as the client
leaving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: log a canceled chunk read below error level

A ranged S3 GET reads through ChunkReadAt with the request context, so a
client hanging up cancels the chunk fetch and the reader logged
"fetching chunk ...: context canceled" (and, when the lookup was the
step canceled, "operation LookupFileId ... failed") as an ERROR. A read
whose caller canceled it now logs at V(3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:12:03 -08:00
Chris LuandClaude Opus 5.5 7da99cd760 sts: honor the provider role mapping for web identity roles it names (#12982)
* sts: honor the provider role mapping for web identity roles it names

AssumeRoleWithWebIdentity only checked the role's trust policy, so with
trust policies that allow the provider without claim conditions any
token from that provider could assume any of its roles, including ones
the provider's roleMapping assigns to other claim values. Bearer auth
already uses the mapped roles. A role named by the mapping (a rule or
the default role) is now issued only to tokens the mapping gives that
role; roles the mapping does not name keep the trust-policy-only check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sts: trim role mapping targets when checking which roles the mapping names

Bearer auth trims mapped roles, so a padded target still assigns that
role; without the trim the web identity check treated the role as
unnamed and left it to the trust policy alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sts: compare the provider's mapped roles as a list, not a comma-split string

The OIDC provider joins mapped roles with commas, and role names may
contain commas, so splitting the joined attribute could match a piece of
one mapped role against a different role, or miss the mapped role.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sts: check the session role in the web identity role mapping test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:08:50 -08:00
Chris LuandClaude Opus 5.5 7638cf2f66 mount: keep the data past a sparse file's first hole when merging chunks (#12978)
* mount: merge each run of a sparse file's data, not just the run before its first hole

The chunk stream reader ends at a hole, so the merge stopped there and
replaced every chunk with ones covering only the data before the first
hole. Read and save each contiguous run of visible data on its own, and
leave the holes between runs unwritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: skip the small-chunk merge for a sparse file

The merge reads the chunks through the stream reader to its end, which
stops at a hole, and keeps only the chunks before its start offset, so
an append to a sparse file lost the data past the first hole after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:07:45 -08:00
1815f140b6 fips140=only: refuse JWT signing keys and S3 secrets too short for HMAC (#12912)
* fips140=only: refuse HMAC keys too short for FIPS mode where they are configured

Under GODEBUG=fips140=only, hmac.New panics on keys shorter than 112 bits
(14 bytes). A short JWT signing key starts fine and then kills weed server
on the first write (the master's Assign mints a volume JWT in an
unrecovered gRPC handler), and an S3 secret of 8 or 9 characters (the
SigV4 signing key is HMAC keyed with "AWS4"+secret) makes every request
from that identity panic in its handler.

Only under crypto/fips140.Enforced():

- security.toml: LoadSecurityConfiguration exits with an error naming the
  setting when a jwt.signing / jwt.filer_signing key, read key or
  previous key is under 14 bytes. LoadFilerJwtFromFile (filer.sync
  -a.security/-b.security) returns the same error, and
  Guard.UpdateSigningKeys keeps the keys in effect on a reload that
  brings in a short key.
- S3: SigV4 (header, presigned, streaming seed and POST policy) answers
  InvalidAccessKeyId, as for an inactive key, when the credential's
  secret is under 10 characters, and logs the access key. Loading such a
  credential logs a warning; it stays loaded and stored.
- IAM CreateAccessKey (IAM API, embedded IAM, admin UI) requires a
  caller-supplied SecretAccessKey of at least 10 characters.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fips140=only: check jwt.filer_signing.subscribe.key and the imgproxy key too

The filer verifies metadata subscription tokens with
jwt.filer_signing.subscribe.key and `weed shell fs.meta.token` signs them
with it, so under GODEBUG=fips140=only a short value panics on first use;
LoadSecurityConfiguration now refuses it with the other JWT keys. `weed
image` signs imgproxy URLs with HMAC keyed with IMGPROXY_KEY;
gateway.New refuses a key under 14 bytes in that mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: warn about JWT keys too short for fips140=only outside that mode

Outside GODEBUG=fips140=only a JWT signing key under 14 bytes works, so
LoadSecurityConfiguration (every weed command but fuse) and
LoadFilerJwtFromFile now log a warning naming the setting instead of saying
nothing: such a key is refused under fips140=only, and a future release may
refuse it in every mode, so the warning asks for a rotation to a longer key
with previous_key while it still works. A short previous_key holds the old
key during that rotation, so its warning only asks to clear it afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: refuse a short secret under fips140=only with AccessDenied, not InvalidAccessKeyId

InvalidAccessKeyId says the access key does not exist, so a client refused
for a secret too short for fips140=only went looking for a missing key. The
new ErrFips140SecretTooShort answers AccessDenied (403) with "This access
key cannot be used while the server runs in FIPS 140 mode. Ask the
administrator for a new secret." The message leaves out the length rule:
the refusal comes before the request's signature is checked, so any caller
that knows the access key ID would learn the secret is short. The embedded
IAM API maps it to AccessDenied as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: log an S3 secret too short for fips140=only at error level

Under GODEBUG=fips140=only every request signed with such a key is refused,
so the identity is unusable; the load-time message is an error, not a
warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util, security: name every JWT key too short for fips140=only in one error

CheckFips140SigningKeys stopped at the first short key, so a cluster with
two short keys failed at startup, was fixed, and failed again on the next
one. CheckFips140HmacKeys checks every setting and names each short key
("jwt.signing.key is 10 bytes, jwt.filer_signing.key is 8 bytes; ..."); with
one short key the message is unchanged. Guard reloads use it as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fips140=only: say what happened, to what and what to do in the short-key messages

The messages about S3 secrets and JWT keys too short for FIPS 140 now start
from the process's mode, name the key, its owner or file, the limit, and the
fix:

- loading S3 identities: "this process runs with GODEBUG=fips140=only, and
  refuses all S3 requests signed with access key ... (identity ...) because
  its secret is shorter than the 10 characters FIPS 140 needs for SigV4
  secrets; give that access key a new secret of at least 10 characters";
- a refused request logs its request ID, which the client gets back, its
  client IP (as the audit log records it, s3err.RemoteIP) and the identity;
- the startup refusal names security.toml's path and every short key, and
  links the wiki section on replacing them with or without downtime;
- the startup warning outside fips140=only says the server would not start
  in that mode, and links the same section.

A short previous_key no longer gets a warning outside fips140=only: it holds
the old key while switching to a longer one, and under fips140=only the
startup refusal names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: a reload under fips140=only drops short previous keys, not the new keys

UpdateSigningKeys refused the whole key set when a previous key was too short,
so a volume server kept its old keys while the filer's volume signer, which
gets no previous keys, took the new ones; proxied chunk reads then failed with
401. Short current keys still keep the keys in effect. A short previous key is
dropped with an error log instead: nothing under fips140=only can sign with it,
so no token is lost, and every server ends up with the same current keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: check only the filer keys filer.sync uses in its security files

LoadFilerJwtFromFile checked every JWT setting in a -a.security/-b.security
file, so under fips140=only filer.sync refused to start over a short volume or
previous key it never uses. It now checks jwt.filer_signing.key and its read
key, after the fallback to the process-wide configuration, which startup
checks already.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer a short secret under fips140=only with SignatureDoesNotMatch

A distinct answer before the signature is checked told anyone who knows an
access key ID that its secret is short. The refusal now runs where the
signature would be checked, after the permission, expiry and signed-header
checks, and answers the SignatureDoesNotMatch a wrong signature gets. The
server log keeps the cause, the request ID and the client. This drops
ErrFips140SecretTooShort and its IAM mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security, filer: keep Basic Auth on a reload whose JWT keys are refused

When a reload under fips140=only refused the new filer JWT keys, the filer
still removed Basic Auth, so a configuration that switches from Basic Auth to
short JWT keys left the filer with neither. UpdateSigningKeys and
ReloadSigningKeys now report whether the new keys are in effect, and the
filer drops Basic Auth only when they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: do not install a volume read key too short for fips140=only

A reload installed jwt.signing.read.key into the read-signing cache without a
length check, so under fips140=only a short key made later chunk reads panic
signing with it. loadJwtConfig now leaves the key in effect when the new one
is too short.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: keep the volume read key when the volume guard would refuse the reload

Under GODEBUG=fips140=only a volume server's reload keeps its keys when
jwt.signing.key or jwt.signing.read.key is too short. The read-key cache
checked only the read key, so it could sign reads with a key the volume
servers had not taken. It now checks the same two keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: build the short-key list in one append in CheckFips140HmacKeys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep the blank line before the permission check in verifyV4Signature

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: skip TestFIPS140OnlyShortSecret under real fips140=only enforcement

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-25 13:07:15 -08:00
Carlos Leyva 5b300ea909 filer: scope metadata subscriptions to a token's prefixes (#12931)
* filer: scope metadata subscriptions to a token's prefixes

* filer: check scoped updates before preparing chunks

* filer: recheck scoped WORM policy after chunk preparation

* filer: preserve scoped event parents and recheck update authority
2026-11-25 13:05:53 -08:00
Chris LuandClaude Opus 5.5 dd443065fe admin: keep stored plugin job data and config from read-only sessions (#12973)
* admin: return compact plugin job detail to read-only sessions

Read-only sessions got the stored parameters, labels, description and
result output of a job, while job listings already leave them out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: require admin access to read plugin job type config

The stored config holds literal values such as the admin script, so a
read-only session must not read it, the same as it cannot write it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* plugin worker: log only the command name in admin script activities

The activity timeline is readable by read-only sessions, and command
arguments can carry secrets; the full command lines stay in the output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep only the command name in admin script running activities

Activities stored before the worker change, and activities sent by
workers that have not been upgraded, still carry full command lines.
Reduce them when they are loaded and when they arrive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: redact admin script activities whose report omits the job type

A progress report for a tracked job can leave the job type out; use the
tracked job's type so the command arguments are still dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: keep a test comment on its test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: require the job-type-less admin script report to be recorded

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: type untracked admin script progress from the pending execution

A progress report that carries neither a job type nor a tracked job id
still belongs to the execution the admin sent under its request id; use
that job type so its admin script activities lose the command arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: redact running executor activities whose job type is unknown

A report that arrives after its execution timed out or was cancelled can
carry only a request id. Its job type cannot be resolved any more, so
treat it like an admin script report and keep only the command name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: test the plugin config route on a bare handler in its own file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin: match the unredacted admin script message exactly 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-25 13:04:51 -08:00
612e170caf perf(s3tables): read bucket policy from the listing (#12949)
* s3tables: read bucket policy from the listing

ListTableBuckets looked up every listed bucket again to read its policy, which is already on the listed entry: one extra filer lookup per bucket.

Co-Authored-By: Claude Opus 5.5 noreply@anthropic.com

* s3tables: cancel the list test helper's context

The handler stops reading the filer listing once a page is full, so a
call made with a context that is never cancelled leaves that stream
open until the connection closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: drop the list tests' note about master

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-25 13:01:28 -08:00
Chris LuandClaude Opus 5.5 dbc64144ca mount: support NFS re-export file handles after inode eviction (-nfsExport) (#12979)
* mount: update go-fuse for the export support option

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: optionally retain the paths of forgotten inodes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: answer lookups of "." and ".." for file handle decoding

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: add -nfsExport to negotiate export support and retain forgotten inodes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test file handle lookups of "." and ".."

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fail a file handle lookup when its path now holds another file

A "." lookup resolved a forgotten inode by its remembered path, so a
file created at that path since was served to the old handle. Compare
the entry's inode with the handle's and answer ESTALE on a mismatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: register a file handle's inode under the table lock

A "." lookup checked the file at the remembered path and then registered
it with Lookup, which hands back whatever inode holds the path by then.
LookupHandle takes the reference on the handle's own inode, or enters it
at the path only while no other inode holds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: keep a forgotten inode's retained path across a rename

A rename whose source inode the kernel had already forgotten left the
retained path at the old name, so its file handle failed with ESTALE.
An index from retained path to inode lets MovePath move it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: register a file handle only at its current retained path

A rename between resolving a forgotten inode's path and registering it
moved the retained entry, yet LookupHandle still entered the old path.
It now compares the path with the retained one under the table lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: drop the target a forgotten inode is renamed over

Moving a forgotten inode's retained path onto a live name left the
replaced inode mapped there. Once a retained entry moves, the target is
taken apart as for a live source and reported as replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: test that a renamed path-inode file fails its file handle closed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* go.mod: use the go-fuse v2.9.5 release

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:58:56 -08:00
7c33a8449f volume: check a CRC32C of each chunk upload, in every digest mode (#12999)
* volume: check a CRC32C of each chunk upload, in every digest mode

In sha256 digest mode the uploader sends no Content-MD5, so the volume
server and its replicas store a chunk without checking that its bytes
arrived as sent. The uploader now sends X-Seaweed-Content-Crc32c, the
std-base64 of the big-endian CRC32C of the bytes Content-MD5 is checked
against (the file data after undoing Content-Encoding: gzip; the
ciphertext for ciphered chunks), in both digest modes. Uploads that
forward a stored needle (IsReplication) carry only a value the primary
volume server checked.

The Go and Rust volume servers refuse a mismatch or a malformed value
with 400, as they refuse a wrong Content-MD5, and forward the checked
value to replicas, which check it again. A gzipped upload without
Content-MD5 is checksummed while its size is counted, without holding
the uncompressed bytes. Servers that predate the header ignore it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): keep the first part's headers when no part has a filename

Go's parseUpload falls back to the first multipart part with its
Content-Type, Content-MD5 and Content-Encoding. The Rust fallback dropped
them, so a gzipped part without a filename was stored as plain bytes and
its X-Seaweed-Content-Crc32c was checked against the compressed body.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): read the RFC 2231 filename* of a multipart part

Go's uploader names a part with mime.FormatMediaType, which writes
filename*=utf-8''... for a non-ASCII name, and Go's Part.FileName()
decodes it. multer reads only filename, so the Rust volume server missed
the file part and lost its name, gzip encoding and Content-MD5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: send replicas the CRC32C of a rewritten JPEG

Once the orientation fix rewrites a JPEG, the client's CRC32C no longer
covers the bytes the primary forwards, so the replica got no checksum.
Send the CRC32C of the stored bytes instead, in Go and Rust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): read filename* only outside quoted parameter values

A quoted name such as "note; filename*=utf-8''decoy" split at its
semicolon and was taken for the part's filename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): refuse a decoded filename* with control characters

A percent-encoded CR/LF in the name would end the header block of the
part the primary forwards to its replicas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: read the forwarded CRC32C with the replica response in the test

A failing assertion left the CRC32C in the one-slot channel, so the next
subtest's replica blocked instead of the test reporting the failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume(rs): use naïve for the non-ASCII filename test data

codespell reads the ASCII part of café as a misspelling of calf.

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-25 12:53:04 -08:00
Carlos Leyva c0f3182046 filer: run scoped UpdateEntry checks before chunk preparation (#12965)
* filer: check scoped updates before preparing chunks

(cherry picked from commit cede961372)

* filer: recheck scoped WORM policy after chunk preparation

(cherry picked from commit 9d2e6c775c)

* filer: recheck scoped update authority after chunk preparation
2026-11-25 12:50:41 -08:00
Chris LuandClaude Opus 5.5 d95f5e67fb mount: refuse an exclusive create of a name another mount holds (#12966)
* mount: create at the filer only where no entry is stored

A create sent to the filer at open time (mknod, and every create under
EagerFilerCreate) went without OExcl, so the filer stored it as an update
of a file another mount had created there: open without O_EXCL emptied
that file and mknod replaced it. Send OExcl, report EEXIST, and drop the
cached listing so the reopen finds the stored entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: store an exclusive create at open

A create is deferred to the first flush and checks only this mount's
view, so two mounts could both open the same new name with
O_CREAT|O_EXCL. Send an exclusive create to the filer at open instead,
where OExcl refuses the name another mount already stored. Writeback
keeps deferring: it assumes one writer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:50:12 -08:00
Chris LuandClaude Opus 5.5 04b2698db2 iam: end a role session's bucket-policy access with its role (#12968)
A bucket-policy Allow skips IsActionAllowed and only asks
IsPrincipalActionExplicitlyDenied for an overriding Deny. That check
validated the session token and its revocation but not the role ID the
session was issued for, so a session kept a bucket policy's grant after
its role was deleted or replaced by a role of the same name.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:49:48 -08:00
Chris LuandClaude Opus 5.5 977a5d26f8 iam: match policy resources case-sensitively (#12974)
Object keys and bucket names are case-sensitive, so a statement naming one
resource must not cover a key that differs only in case. Actions still
match case-insensitively.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:49:36 -08:00
Chris LuandClaude Opus 5.5 36aea0020e weed fix: add -verifyCrc to index needles with damaged data as deleted (#12972)
* fix: add -verifyCrc to leave needles with damaged data out of the index

weed fix reads only record headers, so a needle whose data was damaged is
indexed and fails on every read. With -verifyCrc it reads each body and
checks it; a needle that fails is not indexed, an older copy of its key is
not brought back, and fix exits non-zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read each record to verify it, so a read error fails instead of dropping it

The scan passes a body buffer even when reading it failed, so -verifyCrc
took bytes it never read for damage. Read the record through a handle of
its own, drop it only when its bytes are corrupt, and fail the scan on any
other read error. -verifyCrc needs the local .dat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: -verifyCrc rejects a record with a size but no data

A needle with no data is written with size 0, and the CRC covers only the
data, so a record whose data size was zeroed parsed cleanly and skipped
the CRC check. Treat it as corrupt, as the tail repair does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: index a needle that fails -verifyCrc as deleted

Leaving it out of the index let loading the volume read the bytes past
the last indexed needle as an interrupted append: the older copy of the
key came back and the damaged record was cut. Handle it like a delete
marker, so with -includeDeleted its tombstone keeps the key deleted and
the loader leaves the .dat alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:49:16 -08:00
Chris LuandClaude Opus 5.5 d6a657cd92 weed compact -method data: copy past an unreadable record like -method index (#12970)
* storage: resume data compaction past an unreadable record

Compacting by data follows record headers through the .dat, so one corrupt
header ended the scan: the compaction failed, or, when the header's size
jumped past the end, every record after it was dropped. Compacting by index
copies past such a record.

When the scan stops on a corrupt header or jumps past live records, resume
it at each live record the index places further on. A read error still
fails the compaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: do not copy a record whose header size disagrees with the index

A live record whose header carries a damaged size was copied with that
size, and the compacted volume indexed a needle it could not read. The
index records each live record's size, so a header that disagrees is
damaged: skip it, and let the scan resume at the next live record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: verify a live record's body instead of comparing its size with the index

Data compaction copied a record whose body failed to parse, and the size
check dropped an intact record when only its index row was wrong. Read the
body only for the record the index points at, drop it on the same errors
-method index drops on, fail on any other read error, and keep the size
the record itself carries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: resume data compaction at every live record the scan did not reach

The resume started past the last header the scan parsed, so a corrupt size
that landed on a later valid header lost the live records it jumped over.
Track the records the scan copied or dropped, resume at each live record it
did not reach in .dat order, and stop a resumed scan at a record an earlier
pass already handled so nothing is copied twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* command: read the compacted volume's version from its super block in tests

Compaction can write a different needle version than the source volume,
so parse the .cpd with the version it records instead of the current one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: do not walk a run of damaged headers again on every resume

A record whose header id is damaged is not marked as handled, so each
resume at one of a run of such records walked the rest of the run before
reaching a copied record, which is quadratic in the run length. Remember
the offsets resumed scans pass, skip resuming at them, and stop a resume
when it reaches one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: count the resumed scans' reads in the damaged-run test

The kept keys come out the same when every resume walks the rest of the
run, so bound the reads made through the volume's data backend instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* storage: drop a record whose header size runs past the end of the .dat

Reading such a record sized its buffer from the corrupt header: a size
near 2 GiB allocated that much on 64-bit and panicked in makeslice on
32-bit. Check the record end against the file size first and drop the
record as unreadable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* needle: compute ReadBytes slice bounds in int

NeedleHeaderSize+size was Size arithmetic and wrapped for a damaged size
near MaxInt32, so the slice panicked instead of failing the read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* needle: fail ReadNeedleBlob for a size that does not fit in an int

On 32-bit a damaged size near MaxInt32 made the buffer length negative
and panicked in makeslice. Return ErrorSizeInvalid instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* needle: compare DataSize bounds in uint64

On 32-bit builds int(DataSize) is negative for a damaged DataSize of
0x80000000 or more, which passes the bounds check and panics on the
slice instead of returning ErrorCorrupted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:48:55 -08:00
Chris LuandClaude Opus 5.5 0f6e07c4d0 s3api: refuse a marker delete on a stored version's physical path (#12981)
* s3api: refuse a marker delete on a stored version's physical path

A delete of "<key>.versions/v_<id>/" was answered AccessDenied only when the
version file held neither chunks nor remote data, and since the check for a
file rather than a directory moved to the front, not even then: the delete
reported success. The version-file check now runs first, as it does for the
same key without the slash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test a marker delete on a chunked version file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:47:54 -08:00
f7b70d477d ci: run the S3 suites in every digest mode with both volume servers (#13000)
* ci: run the S3 suites in every digest mode with both volume servers

The sha256 digest (-filer.digest=sha256) and GODEBUG=fips140=only had no
S3-level CI run, and the Rust volume server none in any digest mode.
s3-digest-matrix.yml builds weed with GOFIPS140=v1.0.0 and weed-volume once,
then runs the basic ceph s3-tests list and the etag and checksum Go suites in
md5, sha256 and fips140only cells, each with the Go and the Rust volume
server and JWT signing on. test/s3/digest_matrix/start_cluster.sh starts a
cell's cluster.

The basic ceph test list moves to test/s3/compatibility/s3tests_basic.txt,
shared with s3tests.yml. The etag suite computes expected ETags with
util.NewMd5For(S3_DIGEST), so it checks each cell's digest; the checksum
suite skips SHA-1 when S3_FIPS140_ONLY=1. Three ceph tests whose answer the
mode changes on purpose are deselected in the cells of that mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: run the digest matrix when the protos or the S3 fixtures change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: keep newTrailerChecksumClient's 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>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-25 12:47:24 -08:00
e07e34ef09 ci: add optional Graphify code-graph workflows (code-only, no secrets) (#13005)
* ci: add optional Graphify code-graph workflows

Build a code knowledge graph with the open-source Graphify CLI in code-only mode (tree-sitter, no API key or secret) on a daily schedule, cache graphify-out/ between runs, and upload graph.json.gz, graph.html and GRAPH_REPORT.md as a workflow artifact. Attach the same bundle to published releases.

graph.json is about 150 MiB, above GitHub's 100 MiB file limit, so the graph is not committed; graphify-out/ is ignored.

* ci: keep the Graphify cache bounded and align the release build

- Set GRAPHIFY_NO_BACKUP=1. Hub-named community labels make graphify treat
  the graph as curated and snapshot it into graphify-out/<date>/ before every
  overwrite, without pruning; the cache would grow by ~100 MiB a day. The
  cache path also excludes graphify-out/20*.
- Cluster once on a cold build (extract --no-cluster, then cluster-only), and
  label the release graph the same way as the scheduled one instead of
  "Community N" placeholders.
- Release builds restore the default branch's cache (restore only) and run an
  incremental update instead of a cold extract.
- Add workflow_dispatch with a tag input to graph-release.yml for releases
  created with GITHUB_TOKEN, which do not trigger the release event.
- Use actions/cache@v6 and actions/setup-python@v7 like the rest of the
  repository; drop setup-uv and the full-history checkout.
- Bundle graph.html only when graphify generated it.

* ci: graph: build from a full extraction on every run

graphify update re-extracts only the files that changed since the
cached build. Go function ids include the file stem, so after a
function moves to another file, callers in unchanged files keep edges
to the old id, and the cache chain never resets that drift. A cold
code-only build takes about five minutes on a hosted runner, so drop
the cache and always extract. GRAPHIFY_NO_BACKUP only mattered for
the cached graphify-out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: graph: attach the release bundle from a separate write job

graph-release.yml ran graphify and its dependencies with a
contents: write token persisted in the checkout's git config. Build the
release bundle in the read-only graph job and upload it from a job that
only downloads the artifact. The release asset is now the same bundle
as the daily artifact, graph-health.json included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: graph: do not persist the checkout token

Nothing after the checkout talks to a git remote, so keep the token out
of .git/config where graphify could read it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: graph: keep artifact and asset names valid for any tag

A dispatched tag such as release/v4.0 made an artifact name with a
slash, which upload-artifact rejects. Name the artifact after the
commit again and replace slashes in the release asset name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: graph: never call an LLM

cluster-only auto-detects a labeling backend from API-key variables and the
claude CLI; locally it picked up the claude CLI. Set GRAPHIFY_BACKEND=none so
the build stays code-only even if a runner image provides one; communities
keep hub-node names.

---------

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-25 12:46:14 -08:00
9ffb5fe185 filer, s3, filer.sync: one digest per cluster, set by the filer's -digest and followed by its clients (#12913)
* util, filer: choose the digest at filer startup with -digest

NewMd5 and NewSha1 returned SHA-256 cut to size whenever the process ran
under GODEBUG=fips140=only, so the kind of digest a cluster stores followed
each process's own environment. They now follow a digest mode set once at
startup: util.SetDigest("md5"|"sha256"), or "" to keep following
fips140.Enforced(). The default is unchanged.

weed filer -digest, weed server -filer.digest and weed mini -filer.digest
set it; fips140=only refuses md5 at startup. The leveldb2/leveldb3
directory-key marker follows the mode, as do the places that compare a
NewMd5 digest with Content-MD5 or pass it on as one: S3 PutObject, filer
HTTP uploads, the Content-MD5 the filer returns, and the uploader's
Content-MD5 to volume servers. Places that verify Content-MD5 with a real
MD5 (volume servers, S3 request bodies and archive uploads) keep keying on
fips140.Enforced(), since they can check it whenever MD5 is available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer, command: report the filer's digest and make its clients use it

GetFilerConfigurationResponse carries the filer's digest mode in a new
field 16, digest. weed s3, mount, webdav, sftp, iam and filer.copy adopt
it before they serve or write, so a gateway started with a different
GODEBUG writes the same kind of ETag and chunk digest as the rest of the
cluster. A process under fips140=only refuses a filer that reports md5. A
filer that reports no digest predates the field; the client then keeps
its own mode and logs a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.sync, s3 sink: keep digests within one kind

filer.sync copies entry digests and ETags as they are, so syncing a filer
with digest sha256 into one with md5 left SHA-256 ETags in the md5
cluster. It now reads both filers' digests and refuses to start when they
differ, with a warning when either filer does not report one.

The S3 sink sent the entry digest as Content-MD5 unless its own process
ran under fips140=only. From a sha256 source into a target that checks
Content-MD5 every single-part upload failed with BadDigest and the backup
retried it forever. It now asks the source filer for its digest once and
forwards the entry digest only when that is md5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.meta.backup, filer.backup, filer.replicate: keep digests within one kind

filer.meta.backup opened its backup store in its own digest mode, so a copy
of a sha256 filer made by a process outside fips140=only got MD5 directory
keys and could not be opened as that filer's store. It now adopts the source
filer's digest before the store opens.

filer.backup and filer.replicate with a filer sink copied entry digests into
the target filer without comparing digests, as filer.sync did before. Both
now refuse, and exit, when the source and target filers report different
digests. replication.CheckDigestsMatch is the shared check; filer.sync uses
it too.

weed server and weed mini apply -filer.digest before they start the master
and volume server, so every part of the process hashes with one digest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer, filer.sync: refuse a peer filer with another digest; exit on mismatch

Filers peering through the meta aggregator now compare digests. A peer with
a store of its own would replay entries holding the other kind of digest
into this filer's store, so its changes are refused and the reason logged
on every reconnect. A fresh filer bootstrapping from such a peer refuses the
copy, so a new filer whose digest differs from the existing filers' exits at
startup. A peer on the same store writes into it directly, and refusing its
stream would only starve this filer's subscribers, so that mismatch is
logged as an error and the stream kept.

filer.sync exits with status 1 when the two filers use different digests,
as filer.backup and filer.replicate do: it is a configuration error a
restart cannot fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: -digest help says a store keeps the digest it was created with

The help text said existing data keeps the digest it was written with,
which reads as if the flag could be changed on a store with data. Stores
that hash keys stop finding existing entries under another digest, so the
text now says to set it when the store is created, and that switching means
copying the metadata into a new store with fs.meta.save and fs.meta.load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer, s3, replication, admin, iceberg: address review of the digest checks

- A filer checks its peers' digests on every start, not only at the fresh-store
  bootstrap: the store signature is written when the store opens, so a fresh
  filer refused at bootstrap restarted as an initialized store and served
  without its peers' files.
- Under digest sha256 with MD5 available (not fips140=only), a client's
  Content-MD5 is checked against a separate real MD5 of the body, in S3 object,
  part and directory-marker uploads and in filer HTTP uploads. It goes
  unchecked only when no MD5 can be computed.
- filer.backup and filer.replicate exit only on a DigestMismatchError; a filer
  that cannot be reached is retried, so a backup started before its target is
  up resumes once the target answers.
- The admin file browser and Iceberg compaction write chunks into a filer they
  do not follow at process level. They read that filer's digest and pass it to
  the chunk upload (ChunkedUploadOption.Digest), so their content and chunk
  digests match the filer's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer, s3 sink: retire digest-refused peers; no Content-MD5 for an unknown digest

- A peer refused for its digest counts as unreachable: the check now runs
  before notePeerReachable and its error wraps errPeerUnreachable, so the
  subscribe loop retires the peer from the low watermarks after the usual
  grace instead of keeping its zero watermark, which held every aggregated
  subscriber at the settled horizon.
- When the source filer's digest cannot be read, the S3 sink no longer sends
  the entry digest as Content-MD5: it may be a SHA-256 digest the target
  would reject.
- TestCheckPeerDigest skips the cases that need MD5 locally under
  GODEBUG=fips140=only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg, util: tests for the per-filer digest

The Iceberg tests' fake filer serves GetFilerConfiguration, which uploads now
call to read the target filer's digest; it reports none, as a filer that
predates the setting does. TestNewContentMd5 computes a real MD5, so it skips
under GODEBUG=fips140=only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: bound each startup peer digest read with a timeout

CheckPeerDigests read each peer's configuration with the caller's context,
which at startup has no deadline, so a peer that accepted the connection but
never answered held the filer's startup. Each read now has its own
peerDigestReadTimeout (10s, inside the one-minute announce cap), after which
the peer is logged and skipped like an unreachable one.

setDigestForTest restores the previous digest setting instead of the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util, s3, filer: one-shot digests for data held in memory

Md5For hashes with md5.Sum or sha256.Sum256 instead of writing into a
hash.Hash, and the Content-MD5 checks of S3 directory markers and of filer
uploads saved inside the filer use BodyMd5Of on the bytes they already hold.
Streaming uploads keep their io.TeeReader.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: hash Content-MD5 on the upload's digest hash, not on its body

teeContentMd5 wrapped the request body in a TeeReader before
uploadRequestToChunks. CodeQL's go/reflected-xss query follows the body
from r.Body through the chunk upload to upload_content.go's
w.Write(prepared.data), which it resolves to the response-writer
wrappers in s3vectors, s3tables, webdav and server/common.go. Those
flows exist on master from other sources (extract, tagging, the
multipart POST); the wrapped body put them through lines this PR
changed, so CodeQL reported six of them as new.

newUploadHash now builds the digest hash that uploadReaderToChunks and
the inline-append paths already tee the body into, and adds the
separate MD5 there; uploadBodyMd5 reads it back for the check. The body
reaches uploadRequestToChunks as on master. Behaviour is unchanged:
under digest sha256 with MD5 available, Content-MD5 is checked against
the body's MD5, including empty and inline appends.

Checked with CodeQL 2.27.6 (go-queries 1.6.16, ReflectedXss.ql) on this
tree: no flow of the nine reflected-XSS results passes a changed line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* replication: keep the ReadFilerSignature name and return the digest with it

Renaming it to ReadFilerSignatureAndDigest left its other callers with an
undefined function. Keep the name and add the digest to what it returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: keep HashToInt32 off the digest mode

HashToInt32 names things that processes derive on their own, such as a
mount's local socket path and MQ partition key hashes. weed mount adopts
a -digest=sha256 filer's digest before it names its socket, while
weed shell mount.configure keeps md5 and dialed a different socket.
Follow GODEBUG only, as before the digest setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.meta.backup: wait for the source filer's digest instead of exiting

A backup with a saved offset used to start its stream loop and retry
until the source filer answered. Reading the digest first made it exit
when started before the filer. Retry the read; exit only when the
digest is refused.

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-24 20:17:26 -08:00
Chris LuandClaude Opus 5.5 4c49dea692 test: detect the chunk merge in the merge-read FUSE test without a zero stamp (#12975)
The test took a single chunk stamped 0 as the sign that a flush merged
the file. Merged chunks now carry the stamp of the oldest data they hold,
so the loop never saw the merge and the test failed before reading.
Take a flush that leaves one chunk where several were stored as the merge.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:16:34 -08:00
Chris LuandClaude Opus 5.5 1ddc01d93f filer: match the read-only rule on the entry path a write lands on (#12969)
* filer: check the read-only rule on the path a POST or PUT writes

A write to an existing directory without a trailing slash stores the
entry under it (the multipart file name, or the base name on PUT), but
the read-only rule was only matched on the request path, so a rule on
the directory's slash-terminated prefix did not apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: check the read-only rule on the copy destination entry

Copying into an existing directory stores the entry under it, so match
the read-only rule on that final path rather than only the request path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: check the read-only rule on the path saveMetaData persists

saveMetaData resolves the target path with its own directory lookup, so
a directory created after the early check could still route the entry
under a read-only prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:14:20 -08:00
Chris LuandClaude Opus 5.5 79ddcb49e6 filer: send a delete that misses locally to the write owner (#12967)
* filer: record which peers share this filer's store

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: send a delete that misses locally to the write owner

Exclusive and conditional creates are stored on the path's write owner.
With separate filer stores, a delete sent to another filer before it has
replayed the create found nothing, reported success, and left the entry
on the owner, from where it replicated back. Such a delete now goes to
the owner, unless the owner runs on this filer's store. A forwarded
delete is applied only by the filer its own ring names as the owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: delete a directory marker on its write owner

The marker is read on the key's write owner, but the delete went through the
connected filer. When the marker still has children, the filer refuses the
delete and the marker is demoted by a lookup and an update on that same
client. A connected filer that has not caught up with the owner misses the
marker there and reports success, so the owner keeps listing the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: also delete a directory marker on its prior owner

While a ring change is in its cooling-off window, the routed read can find
the marker on the key's prior owner before it reaches the new one. The
delete went only to the new owner, so a nonempty marker was demoted on a
filer that did not have it, and the prior owner kept listing the key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: check a directory marker on the prior owner before deleting it there

The prior owner's delete ran unchecked and through the failover walk. When
the new owner held an empty marker and the prior owner already held the
object without the slash, the delete removed that object's data. And when
the prior owner could not be reached, another filer reported the delete
done while the marker stayed on the prior owner.

The prior owner's entry is now read on that filer and judged like the
routed one before anything is deleted, and its delete runs on that filer
only. A prior owner that cannot be read fails the delete for the client to
retry, which lasts at most the ring's cooling-off window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: probe a marker's prior owner when its write owner misses

A miss on the write owner returned success before the prior owner was
checked, so an unreachable prior owner that still held the marker left it
in place behind a reported delete. The miss now falls through to the
prior-owner probe, which fails the delete when that filer cannot be read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: check the entry a marker delete removes on the filer it runs on

The read that decides the delete can be answered by another filer than
the delete: the owner write walk fails over when the owner's channel does
not come up. Each delete now reads its filer's own entry first and leaves
an entry holding uploaded data alone, as the routed read already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: send no marker delete to a filer that misses the marker

A filer that misses passes the delete on to the key's write owner, which
applies it without the marker checks and may hold uploaded data under the
key. The delete now runs only where the entry was checked; a miss on an
entry the read found fails the delete for the client to retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: leave the object without the slash alone when deleting its marker

A marker delete removed the entry unless it carried chunks or remote data,
so the object "dir" stored inline, or empty and known only by its promotion
mark, went with a delete of "dir/". A plain file or a prefix object holds
the key without the slash, as reads already treat it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:13:39 -08:00
Yip LeoandClaude Opus 5.5 64cc7f5142 filer: break two reader cache budget deadlocks that wedge mount reads (#12950)
* filer: free a closed file's chunks for a download waiting on the budget

A weed mount stopped answering reads for three days. Its goroutine dump:
351 downloads waited in ReaderCacheBudget.reserve, all 31 releases sat in
SingleChunkCacher.destroy waiting for one of them, all 100 reads waited for
one of them as well, and a few goroutines spun in reserve's eviction loop.
The stuck reads filled the 128 FUSE background slots, so every read of the
mount blocked.

Closing a file runs ReaderCache.destroy, which takes the file's chunks out
of the map and then destroys them one at a time. When it reaches a download
waiting for budget first, it waits for that download, and the budget the
download needs can be held by the file's other chunks, which are out of the
map as well:
- Eviction skips a finished chunk that is out of the map. removeUnpinned
  refuses it, so reserve puts it back on the idle list and retries at once.
  When a stream is positioned in it, remove() does nothing, so reserve only
  takes it off the idle list.
- A download that fails is never evictable, and a download destroy()
  cancels fails too. remove() does nothing for one that is out of the map,
  so its reservation stays until destroy() reaches it.

Since #12616, destroy() cancels the waiting download when nothing reads
it. It does not when a stream is positioned in the download because the
read that started it gave up, for example because its process was killed:
closing a ChunkGroup does not release the streams.

Eviction now destroys a chunk that is out of its file's map instead of
skipping it. Whoever took it out destroys it too, and destroy() is safe to
run twice. A download that fails gives its reservation back at once, also
when it is out of the map.

TestReaderCacheDestroyWhileDownloadWaitsForBudget closes a file while one
of its downloads waits for budget, 30 rounds per case. When the waiting
download is a prefetch nobody read, the test passes on master. When a
stream is positioned in it, it hangs on master, both when the downloads
holding the budget are prefetches the close cancels (the release fixes
this) and when streams are positioned in them too (the eviction fixes
this). TestReaderCacheBudgetStress runs reads (some given up midway),
prefetches, failing downloads and close/reopen on four files that share a
budget of four chunks; it hangs in 10 of 10 -race runs on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: do not wait for a dropped download while holding another chunk

A read registers on its new chunk and only then drops the chunk its stream
left (unpin, removeConsumed). When that chunk's download had not finished,
removeConsumed cancelled it and then waited for it in destroy(), still
holding the new chunk. The download could be evicting that very chunk for
budget: reserve falls back to a chunk a stream is positioned in, and
destroying it waits for its reads, this one included. Neither went on.

A dropped chunk whose download has ended is still destroyed at once. One
still downloading, cancelled when it was dropped, is destroyed by a
goroutine once the download gives up, so the read goes on.

TestReaderCacheBudgetStreamsStress moves eight streams between four chunks
under a budget of two and gives up a third of the reads midway. In 20 -race
runs it hangs 4 times on master and 8 times with only the previous commit,
in this cycle; with this change it does not hang.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 20:10:59 -08:00
github-actions[bot] 7fb12e9a7a docs: regenerate star history chart 2026-11-25 02:39:36 +00:00
Chris Lu e22704d25e mini: bind Admin and WebDAV to -ip.bind by default (#12971)
weed mini is a single-host sandbox whose other components already
listen on -ip.bind without authentication. Moving the unauthenticated
Admin UI and WebDAV to loopback broke setups that open them from
another machine on a private network. -admin.allowInsecureBind and
-webdav.allowInsecureBind now default to true; set them to false to
keep an unauthenticated Admin or WebDAV on loopback. The Admin worker
gRPC control plane still defaults to loopback.

Claude-Session: https://claude.ai/code/session_011UpvahFvcQGAmXWpPrXZY1
2026-11-24 17:49:44 -08:00
Salomon Henke Andersen 85fcde9b0d helm: reload S3 identities with a SIGHUP sidecar instead of restarting (#12945)
* helm: reload S3 identities with a SIGHUP sidecar instead of restarting

The chart restarts the filer and S3 pods when the content of
existingConfigSecret changes, so every identity change briefly takes S3
down, completely so with a single filer. SeaweedFS reloads the identities
file on SIGHUP.

filer.s3.configReloader and s3.configReloader, off by default, add an
s3-config-reloader sidecar that sends SIGHUP to SeaweedFS when kubelet
updates the mounted file, turn on shareProcessNamespace, and stop
hashing the existing Secret into checksum/s3config. The sidecar uses the
component's image and container security context, so it runs as the same
user as SeaweedFS, and it logs a warning when it cannot signal it.

* helm: address review of the S3 config reloader

- Default the configReloader map to dict, so a release upgraded with
  --reuse-values from a chart without it still renders.
- With the reloader and existingConfigSecret, leave checksum/s3config off
  the pod, so values of the Secret the chart generates cannot restart it.
- README: the restart comes from the next Helm upgrade, the timing holds
  for the kubelet's default settings, and a reload re-creates the KMS
  providers, which replaces the in-memory keys of the local provider.

* helm: describe Secret propagation as eventually consistent

Kubernetes gives no bound on when a Secret volume is updated, so the README gives typical delays instead, and says a revoked identity keeps working until then.
2026-11-24 15:55:11 -08:00
Chris LuandClaude Opus 5.5 fe816eaac8 mount, filer: stamp merged and manifest chunks instead of leaving them at 0 (#12962)
* filer: stamp a manifest chunk with the newest chunk it folds

mergeIntoManifest saved the manifest with tsNs 0, so manifest chunks
carried no modification time. Give it the newest ModifiedTsNs of the
chunks it holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: stamp merged chunks with the newest chunk they replace

maybeMergeChunks uploaded the rewritten chunks with tsNs 0, so any
older chunk that overlaps them later, like a covered chunk sent with the
commit, outranked the merge. Give them the newest ModifiedTsNs of the
chunks they replace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: stamp a merged chunk with the oldest data it holds

The newest stamp of the whole merge outranked a peer's pending write
that is newer than the bytes the merge carries for its range but older
than the newest of them. Stamp each merged chunk with the oldest visible
data in its range, or 0 over a hole, so such a write still shows while
chunks older than all of its data lose to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: find a merged chunk's range by binary search

Each uploaded chunk scanned the visible intervals from the front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:53:32 -08:00
928c744977 filer: ask the master for log chunks the volume map lacks (#12937)
* filer: ask the master for log chunks the volume map lacks

loadLogFileEntries reads the log chunks that SubscribeMetadata and
SubscribeLocalMetadata replay from the persisted log, and it looked each
chunk's volume up only in the filer's cached volume map. A volume missing
there fails with "volume N not found", which isChunkNotFoundError takes
for a deleted volume, so the replay skips the rest of the log file. Once
the same pass reads a later entry from a file whose volume the map does
hold, for any path, the subscriber's position moves past the skipped
file, and filer.sync, filer.backup, filer.meta.tail or an S3 gateway
never receive its events.

A live volume is missing from the map in two cases:

- A starting filer serves subscriptions once its gRPC port is up, but
  gets its volume map only when it registers with the master, and
  AnnounceOnceCaughtUp holds that until the peers found at startup have
  caught up (at most a minute). Until then the map holds only volumes
  the filer has looked up through the master for other reads.
- A failed chunk read sets the volume's cached locations aside and looks
  the volume up again, which a cache-only lookup answers with "not
  found", as #11964 found for NewChunkStreamReaderFromFiler.

Use GetLookupFileIdFunction, which asks the master on a miss, like the
streaming reader since #11964 and the replay's other lookups.

Asking the master adds one more way to fail: no answer, when the master
cannot be reached before the client's retries run out. That error still
reads "volume N not found", since no locations are known, but it says
nothing about the volume, and skipping would lose the file's events for
good. wdclient now marks it with ErrLookupUnanswered, and
isChunkNotFoundError does not count a marked error as not found: the
replay returns it, and the subscriber resumes from there once the master
answers. A volume the master says does not exist is still skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: trim the replay lookup comments

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-24 15:52:56 -08:00
Salomon Henke Andersen 56173079d4 helm: add shareProcessNamespace for the filer and S3 pods (#12944)
A sidecar in the filer or S3 pod cannot signal SeaweedFS, because every
container has its own process namespace and the chart has no setting to
share it. One use is reloading the S3 identities file with SIGHUP from a
sidecar that watches the mounted Secret.

filer.shareProcessNamespace and s3.shareProcessNamespace, off by default,
render shareProcessNamespace: true in the filer StatefulSet and the S3
Deployment.
2026-11-24 15:50:49 -08:00
Minsoo Kim fc4c7767f8 admin: make directory paths readable in file browser URLs (#12942) 2026-11-24 15:50:20 -08:00
800d80ed51 remote/s3: WEED_REMOTE_S3_CREDENTIALS=workload, the workload's identity only (#12939)
* remote/s3: WEED_REMOTE_S3_CREDENTIALS=workload, the workload's identity only

A remote of type s3 with no access key and no secret takes its credentials
from the SDK default chain, which looks at AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY first. A SeaweedFS process often holds keys of its own
there: `weed mini` and `weed server -s3` read their initial S3 identity from
those variables. On EC2, a remote mounted on an Amazon S3 bucket with the
instance's role (no keys) therefore signs with the server's local identity,
and every call answers InvalidAccessKeyId, while a filer.remote.sync of the
same remote, started without those variables, works with the role.

WEED_REMOTE_S3_CREDENTIALS=workload makes such a remote take the AWS
workload's identity alone: web identity when AWS_WEB_IDENTITY_TOKEN_FILE and
AWS_ROLE_ARN name one (EKS IRSA), then the ECS/EKS container credentials
endpoint or the EC2 instance metadata service, on an unguarded HTTP client as
the default-chain path already does. Environment keys and shared credentials
files are never read. Unset, nothing changes. Keys in the configuration win;
half a key pair and an unknown value are refused; other S3-compatible types
are not affected. The volume server's client cache key includes the variables
that choose the source.

* remote/s3: a configured web identity has no instance-role fallback

With AWS_WEB_IDENTITY_TOKEN_FILE and AWS_ROLE_ARN both set, a failed token
read or role exchange fell through the chain to the container endpoint or
IMDS, so requests were signed with the node's role.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* remote/s3: the workload credential session reads no shared files

SharedConfigDisable still loads the shared credentials file, so a selected
AWS_PROFILE whose role_arn lives there failed every workload client build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* remote/s3: exchange the web identity in the workload's region

The credential session took the bucket's region, so with regional STS a pod
whose only reachable STS endpoint is its own region could not sign for a
bucket in another one. AWS_REGION/AWS_DEFAULT_REGION win; the bucket's
region remains the fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: a container authorization token change rebuilds the guarded client

The container credential provider captures AWS_CONTAINER_AUTHORIZATION_TOKEN
and its _FILE path when it is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* remote/s3: the workload's web identity uses the regional STS endpoint

SDK v1 still defaults to the legacy global endpoint for most regions, so a
pod that reaches only its regional STS endpoint got no credentials. An
explicit AWS_STS_REGIONAL_ENDPOINTS keeps its say.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: a workload region or STS endpoint mode change rebuilds the guarded client

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* remote/s3: a workload-mode storage session reads no shared files either

A selected profile the SDK rejects still failed the storage session even
though it carries the workload's credentials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: hash AWS_ROLE_SESSION_NAME into the guarded credentials version

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: an IMDS endpoint or mode change rebuilds the guarded client

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: a keyed s3 remote's guarded version follows the credentials mode too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* volume: hash every AWS_* variable into a default-chain remote's guarded version

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-24 15:28:02 -08:00
Nguyễn Lộc PhúcandClaude Opus 5.5 noreply@anthropic.com 827a3d2a99 fix(s3api): validate ACL grant Permission (#12938)
s3api: validate ACL grant Permission

Reject a grant whose Permission is missing or not one of the five S3
values with a new MalformedACLError, and skip grants without a
permission when building GetAcl responses instead of panicking.

Co-Authored-By: Claude Opus 5.5 noreply@anthropic.com
2026-11-24 15:26:11 -08:00
07e1299f98 mount: add -idmap to allow ID-mapped bind mounts (#12922)
* mount: add -idmap to allow ID-mapped bind mounts

FUSE allows ID-mapped mounts only for a server that announces FUSE_ALLOW_IDMAP.
Once announced, the kernel sends uid and gid 0xFFFFFFFF on most requests after checking permissions itself, so the checks that read the caller treat that value as already checked.

* fuse: refuse an unsupported -o idmap before starting the child

The child exits on checkIdmap, but the parent waits for its readiness signal
and never returns, so weed fuse -o idmap hung on macOS and FreeBSD.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: refuse -idmap on Windows instead of ignoring it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fuse: take -o defaultPermissions as the mount flag

-o defaultPermissions=false was forwarded to the kernel as an unknown
option, which failed the mount, and left the flag at true, so
-o idmap,defaultPermissions=false passed the idmap 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-24 15:25:34 -08:00
Chris LuandClaude Opus 5.5 feb488a84d s3api: create the stored object's missing directory before a recovery answers success (#12963)
* s3api: create a recovered PUT's missing directory

The filer stores a new entry before its parent directories, and a parent
that fails to insert leaves the entry stored with an error returned. Both
PUT recoveries then find the stored entry and answer success, so the object
reads by key but no listing shows it, and an overwrite takes the filer's
existing-entry branch, which creates no parents either.

Before claiming the stored entry, create its directory when it is missing,
and answer an error when that fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: create a committed completion's missing directory

A CompleteMultipartUpload whose commit stored the object but failed on its
parent directory answered success through the committed-despite branch, and
a retry that finds the committed object answered success the same way.
Both now create the object's directory first and fail while it cannot be
created; the upload directory is kept, so the retry can finish the job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test recoveries that create the stored object's directory

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: check every directory level when repairing an object's parent

A repair mkdir stores the directory it creates before that directory's own
parents, so a failure there can leave a lower level stored without its
parent, and a retry that saw the lower level answered success. Walk from the
bucket down and create each missing level. A file left by a failed
prefix-object promotion is not a directory a listing descends, so it fails
the repair rather than passing as an existing directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: free unused parts when a completion's directory repair fails

The early return skipped the cleanup of parts the committed object does not
use, and the retry that finds the commit removes the remaining entries
metadata-only, so the unused parts' data leaked. Run that cleanup and keep
only the upload directory for the retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test the per-level parent repair and the failed repair's cleanup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: bound the parent repair with the recovery's lookup budget

The repair's filer calls ran on a background context, so a filer that
stopped answering held the object write lock without a deadline. The PUT
recoveries pass their lookup context, and the completion gives the repair
the same createLookupTimeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fail the parent repair when the bucket directory is missing

The filer creates missing ancestors for a directory create, so walking
down from an absent bucket directory would recreate a bucket deleted
during the write as a plain directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:25:00 -08:00
Chris Lu 7e9ca16f72 shell: show the cluster UUID as the cluster.status id (#12964)
* master: include the cluster UUID in TopologyInfo

VolumeList now returns the topology's persisted UUID alongside the
topology tree, so clients can show which cluster they are looking at.

Claude-Session: https://claude.ai/code/session_011UpvahFvcQGAmXWpPrXZY1

* shell: show the cluster UUID as the cluster.status id

The id line printed the topology root's fixed name, topo, which is the
same on every cluster. Print the cluster's persisted UUID instead, and
fall back to the old value for masters that do not report it.

Claude-Session: https://claude.ai/code/session_011UpvahFvcQGAmXWpPrXZY1
2026-11-24 15:23:49 -08:00
Chris LuandClaude Opus 5.5 bc6db95f19 s3_objectlock: scan listing pages before subdirectories, and stop skipping backslash and .uploads keys (#12961)
* s3_objectlock: read each listing page before scanning its subdirectories

The scan listed a subdirectory while the parent listing was still open.
On a store with one connection, such as SQLite, a parent page that
filled its stream window kept the connection the child listing needed.
Pages now skip chunk lists, since only the lock metadata is read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3_objectlock: scan names that contain a backslash

With backslashes allowed in object keys, a key such as a\b is stored
under that name. The scan skipped it, and every key below such a
prefix, as if the name were a path separator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3_objectlock: scan keys below a .uploads prefix

The scan skipped every directory named .uploads, so an object stored
below a key prefix such as a/.uploads/ was never checked. It now skips
only the directories of pending multipart uploads, whose lock settings
belong to an object that does not exist yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3_objectlock: keep only what the scan reads in a buffered page

A page now stays in memory while its subdirectories are scanned, and a
listing still carries the contents of files stored inline in the
filer. A page keeps only each entry's name, directory flag and extended
attributes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3_objectlock: scan objects stored below a pending upload directory

A key such as .uploads/<upload id>/c is an ordinary object, and the
scan skipped it along with the upload directory it sits in. The scan
now descends into upload directories and ignores only the lock
settings an upload directory holds for its future object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3_objectlock: exempt upload directories only while under .uploads

A renamed upload directory keeps its multipart key, so outside .uploads it
is checked like any other directory marker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:10:45 -08:00
Chris LuandClaude Opus 5.5 5f97a9d088 mount: keep an unpublished create's writes, unpublished, when a peer renames onto its name (#12960)
* mount: publish an unpublished create's writeback drain after a peer rename onto its name

With -writebackCache, the drain flushes metadata only while the saved path
still maps to the handle's inode. Another mount renaming its file onto the
name of a file this mount created and has not published moves that path to
the peer's inode, so the drain skipped the flush and dropped the writes
without an error or a failed-metadata record.

A local rename or unlink of a draining handle waits for the drain or marks
it, so for an unpublished create a lost mapping means another mount's file
took the name. Skip the guard for it: the create-if-not-exists commit then
keeps a recovery record when the name is taken and publishes when it is free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(fuse_dlm): accept only EEXIST on O_EXCL as an early second-create refusal

The concurrent create test returned early on any error from the second open,
so an EIO, or an open failure in the O_TRUNC case, passed without writing
either payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: refuse publishing an unpublished create after a peer renames onto its name

Another mount's rename onto the name of a file this mount created but has
not published takes that name. The create used to publish there later with
create-if-not-exists as soon as the name was free again: after a local unlink
of what the name showed, it reappeared, and after a move of its directory it
landed under a path no longer reachable. markHandleReplaced now records that
the name was taken, and the publication check refuses the handle from then
on: a writeback drain keeps a recovery record and default mode fails close.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:09:19 -08:00
Chris LuandClaude Opus 5.5 dbbf2907a6 webdav: refuse to delete, move or overwrite entries under Object Lock or WORM (#12959)
* webdav: refuse to delete entries under Object Lock or WORM

DELETE removed versions under legal hold or retention and WORM files that
the S3 API and the filer HTTP API refuse to delete. Check the entry, and
for a collection everything below it, then pin the delete to the Object
Lock state that was checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: refuse to move entries under Object Lock or WORM

MOVE could rename a locked version or WORM file away, move a directory
holding them, or replace a protected target. Check the source, a source
directory's contents and the target before the rename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: refuse to overwrite entries under Object Lock or WORM

PUT and COPY replaced a locked or WORM file with a fresh entry, dropping
its content and its lock. Check an existing file before creating over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: pin an upload's final update to the Object Lock state it read

An upload writes the whole entry back when it closes. A hold or retention
set on the new object while the upload was buffering would be dropped, so
the filer now refuses the update if that state changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: recheck an upload's target when it commits instead of pinning it

The precondition on the final update sent it to the path's write owner,
while the placeholder create stayed on the connected filer. With
separate filer stores the owner could miss the placeholder and refuse
the update, leaving an empty file. The upload now rechecks the target
right before the update, as the SFTP upload does, and the update stays
local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: share the WORM retention and subtree checks

FilerConf.WormEnforced and IntersectsWorm replace the copies in the filer
server and mount; ReadFilerConfFromClient reads filer.conf over a filer client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp, webdav: use the shared Object Lock and WORM helpers

Both servers now call FilerConf.WormEnforced, IntersectsWorm,
ReadFilerConfFromClient and s3_objectlock.ObjectLockState instead of
keeping their own copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:08:06 -08:00
Chris LuandClaude Opus 5.5 763c3d1bdf s3tables: keep files a deleted table or view did not write (#12953)
* s3tables: let DirHoldsFiles count only files older than a cutoff

A non-zero cutoff skips files created at or after it, and Iceberg metadata
files directly under the walked directory's metadata/ folder, which a create
stages before its record exists. Existing callers pass the zero time and
keep counting every file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep files a deleted table or view did not write

DeleteTable purged the table's directory (or its decoupled data location)
recursively, and DeleteView purged the view's directory, so files that
were already there when the record was created, or that were written under
a view, went with it. Those files now stay: the record's attributes are
cleared and the directory is left as a leftover. A table still purges the
files it wrote after its create, and its staged metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: skip the drop purge of a location holding older files

DropTable and DropView purge the dropped entry's location after the
catalog delete. A location that holds files older than the table, or any
file other than metadata for a view, is left alone, matching DeleteTable
and DeleteView.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: count a file from the record's own second as older

File creation times have second granularity, so an upload made in the
same second as the table's create compared equal and was purged. An
equal second now counts as older, and the view cutoff no longer needs the
extra second.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: count S3 objects stored on directories in DirHoldsFiles

A trailing-slash key, or a file promoted to a directory by a child write,
is an S3 object on a directory entry. The walk only counted plain files,
so a delete purged such objects, including one on the purged path itself.
They now count like files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep every non-metadata file under a deleted view

A view writes nothing but its metadata files, so a file under it counts
whatever its creation time, including one stamped ahead of this clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: count a file from the record's own second as the record's

File times are whole seconds, and a writer's first file (an insert right
after a create, or a CTAS writing in the second it staged) often shares
the record's second. Counting it as older kept the table's own files on
drop, so a re-create at the location found it non-empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: date a staged create's table from its stage

The engine writes a staged create's first files before the commit
registers the table, so they predate its record and a drop kept them.
The commit now passes the time the stage marker recorded, in process
only, and the table's CreatedAt starts there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: say a view name holds plain files instead of a table

A view deleted over files it did not write leaves its directory without
a catalog record. CreateView reported that directory as a table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: keep a view location's metadata files older than the view

A view writes its metadata only after its record, so a metadata file from
an earlier second at the location is not the view's and keeps the
directory on a drop, like any other file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: test that a view drop keeps older metadata at its location

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: date both view drop test files from one record time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: drop only the table or view record the lookup read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: test a drop whose record is replaced after the lookup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: check the location claim again after the drop scan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* iceberg: test a location claimed while the drop scans it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:06:40 -08:00
Chris LuandClaude Opus 5.5 5354acbe1b s3api: recheck existing-object tag conditions on overwrites (#12951)
* s3api: recheck existing-object tag conditions on PutObject overwrites

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck existing-object tag conditions on POST Object overwrites

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck existing-object tag conditions on CompleteMultipartUpload

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck existing-object tag conditions on the CopyObject destination

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test tag-conditioned PutObject Deny on overwrites

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: evaluate the copy destination policy before bucket default encryption headers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck the self-copy snapshot's tags before committing it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck multipart completion tags only when it commits a new object

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck zip extraction members instead of the archive key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: load the bucket before PutObject's policy checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test the tag-conditioned PutObject Deny on a cold bucket

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: complete a real multipart upload in the overwrite tag-policy test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck the entry a trailing-slash multipart key completes onto

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test the tag recheck for a multipart key ending in a slash

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: recheck the copy destination's tags under the write lock before commit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test a copy over a destination tagged while the copy ran

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:05:50 -08:00
Chris LuandClaude Opus 5.5 da46e334dd s3tables: give tag condition keys the tags they read (#12958)
* s3tables: load bucket tags for bucket-level policy checks

GetTableBucket, ListTableBuckets, DeleteTableBucket, Get/DeleteTableBucketPolicy
and the bucket maintenance operations built their policy context without the
bucket's tags, so aws:ResourceTag and s3tables:TableBucketTag conditions in the
bucket policy never matched there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: evaluate aws:ResourceTag against the bucket on bucket-scoped checks

Namespace operations, ListTables, CreateTable, table rename targets, CreateView,
ListViews and absent-target checks authorize against the bucket ARN but left
ResourceTags empty, so an aws:ResourceTag Deny in the bucket policy never
matched. Table and view targets keep their own (or no) tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: test aws:ResourceTag Deny on bucket-scoped operations

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: pass CreateTableBucket's tags to IAM policy conditions

The IAM authorization path built its request context without the requested
tags, so a role or user policy conditioned on aws:RequestTag or aws:TagKeys
never matched CreateTableBucket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: test aws:RequestTag on the IAM authorization path

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: pass request tags as scalars so policy variables expand

expandPolicyVariables substitutes only scalar values, so a slice left
${aws:RequestTag/<key>} unexpanded and a matching Allow failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: read a listed bucket's policy and tags from one lookup

The tags came from the listing while the policy was read afresh, so a
policy could be judged against tags from an older version of the bucket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: recheck the bucket tags when deleting the bucket policy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3tables: test a tag change between policy deletion's check and its write

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:59:03 -08:00
Chris Lu 4e89e94535 S3 Vectors: opt in to indexed-only searches (#12932)
* vector: restrict indexed-only searches to shared index coverage

* vector: expose indexed-only queries through a compatible backend RPC

* s3vectors: accept signed indexed-only search requests

* s3vectors: document indexed-only queries and exercise SDK signing

* vector: expose restricted ANN execution for enterprise ownership

* vector: score unscored hits within the query scope

* s3vectors: verify search mode in the SigV4 authenticator

* s3vectors: resolve table descriptors for indexed-only queries

* vector: recover short results within a fragment restriction

* vector: avoid a fragment prefilter for fully indexed unfiltered queries

* docs: remove the boto3 signing hook after query errors

* vector: recover short indexed-only results with full coverage
2026-11-24 12:58:13 -08:00
Chris LuandClaude Opus 5.5 1f1d6d057b webdav: optional Basic Auth; mini keeps unauthenticated WebDAV on loopback (#12956)
* webdav: optional HTTP Basic Auth from [webdav.basic_auth]

WebDAV reaches the filer over gRPC, so neither the filer JWT nor the
filer's Basic Auth covers it, and it had no authentication of its own.
With a password set in [webdav.basic_auth], every request needs it.
Without one, startup warns when the gateway listens beyond loopback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mini: bind WebDAV to loopback unless Basic Auth is set

weed mini starts WebDAV by default on -ip.bind, which is 0.0.0.0, so
anyone on the network could read, write and delete all bucket data even
with S3 IAM on. Without [webdav.basic_auth], bind it to 127.0.0.1, as is
done for the unauthenticated Admin UI. -webdav.allowInsecureBind keeps
the network bind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* command: treat a bracketed IPv6 loopback as loopback

-ip.bind='[::1]' failed net.ParseIP, so mini moved an unauthenticated
WebDAV or Admin listener off it to 127.0.0.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security.toml: note TLS for WebDAV Basic Auth

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:57:50 -08:00
Chris LuandClaude Opus 5.5 b0c8bc93dd sftp: honor Object Lock and WORM on delete, rename, overwrite and setstat (#12954)
* sftp: refuse to delete entries under Object Lock or WORM

rm and rmdir sent DeleteEntry with no protection check, so an SFTP user
could delete versions under legal hold or retention, and filer.conf WORM
files, that the S3 API and the filer HTTP API refuse to delete. Check the
entry first and pin the delete to the Object Lock state that was checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: refuse to rename entries under Object Lock or WORM

A rename moved a protected version out of its .versions folder, or
replaced a protected target, which the delete check alone does not stop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: refuse to overwrite or setstat entries under Object Lock or WORM

An upload over an existing protected entry replaced its content, and a
setstat could truncate it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: let a rename onto itself succeed for a protected entry

The filer treats it as a no-op, so there is nothing to protect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: read WORM rules from a filer.conf stored in chunks

ReadFilerConf without a master client reads only inline content, so a
chunked filer.conf looked empty and WORM went unenforced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: pin setstat to the Object Lock state it checked

The update writes back the entry it read, so a hold set in between
would be dropped. The filer now refuses the update instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: recheck an upload's target when it commits, and refuse directories

The upload buffers until Close, so a hold set while it was open still
let it overwrite the entry. A PUT to a directory path also lands on a
child of that directory, whose protection was never checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sftp: refuse to rename a directory that holds protected entries

A directory rename moves every descendant, so checking the directory
alone let it carry locked versions away from their keys, or WORM files
out from under their rule. Refuse when a WORM rule covers the subtree,
as the filer does for scoped tokens, or when an object in it is under
Object Lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3_objectlock: scan a literal .versions directory recursively

A directory named exactly .versions was listed as flat version files, so a
locked object nested below it was missed by the subtree and bucket scans.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:37:57 -08:00
Chris LuandClaude Opus 5.5 488bdafbbb mount: decide chown's set-id clearing by the caller, keep it on directories (#12955)
* mount: decide chown's set-id clearing by the caller, keep it on directories

SetAttr read input.Uid as the caller, but in SetAttrIn that field is the new
owner; the caller is input.Caller.Uid. Root giving a file away cleared its
SUID/SGID bits, a user giving a file to root kept them, and every chown to a
non-root owner cleared the SGID bit of a directory, which Linux keeps so new
entries go on inheriting the group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: let Linux decide chown's set-id clearing

The mount does not handle killpriv, so Linux sends the cleared mode with a
chown that must drop the set-id bits. Clearing them again by caller dropped
the SGID bit Linux keeps on a file without group execute when a user changes
only its group. Other systems keep the caller rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:36:05 -08:00
Dean Chen ae60559da9 mount: keep the furthest dirty stop when a read spans chunks (#12957)
PageWriter.ReadDirtyDataAt walks the requested range one chunk at a
time but overwrote maxStop with each chunk's result. When an earlier
chunk had dirty data and a later chunk in the same read was clean, the
clean chunk's 0 replaced the earlier stop, so the caller under-reported
how much of the buffer the dirty pages filled.

Take the maximum across chunks instead.

Fixes #12946
2026-11-24 12:34:58 -08:00
Yip Leo da9518718f mount: keep an unpublished create's writes when another mount takes its name (#12943)
A file created on a mount is published to the filer at flush; until then its
handle is dirty and has no base. When another mount creates the same name and
its event arrives first, invalidateOpenFileHandle skips the branch that keeps
a dirty handle's writes, because that branch needs a base. It falls through,
destroys the handle's dirty pages and installs the other mount's entry as the
base. The flush then has nothing to publish, and close() returns 0 although
the writes are gone. A delete or rename of the name by another mount marks the
handle deleted or moves it, with the same result, and a rename onto the name
has onEntryInvalidation mark it deleted.

The filer holds nothing of such a file, so an event at its name is about
another file. Leave the handle alone. Its create-if-not-exists commit then
reports a taken name as a conflict (close() fails with EIO, or with
-writebackCache the request is kept in failed-metadata), and publishes as
usual when the name is free.

Part of #12941.
2026-11-24 12:33:10 -08:00
493348e759 filer: retry a chunk delete that a replica in maintenance mode refused (#12935)
* filer: retry a chunk delete that a replica in maintenance mode refused

The filer sends BatchDelete to every replica on its own, and BatchDelete does
not replicate. A volume server in maintenance mode refuses it with "volume
server X is in maintenance mode", which the deletion pipeline took for a
permanent error, so the delete was dropped while the other replicas had
already applied it. That replica then kept the needle live for good, which
breaks EC encode ("no union") until volume.check.disk -syncDeleted repairs it.
Maintenance mode is what a rolling upgrade puts each volume server into, so
every filer delete in that window was lost on one replica.

Treat the maintenance-mode refusal as retryable. The retry runs after the
server leaves maintenance mode; the replicas that already deleted the needle
answer it as not modified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-volume: refuse in maintenance mode with Unknown, as the Go server does

The Go server refuses with a plain error, which arrives as Unknown. The
Rust server sent Unavailable with no details, which Go clients take for
a dead channel: each refused BatchDelete closed the filer's shared
connection to the server and cancelled the other RPCs on it. The message
is unchanged, so the filer still retries the refused delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ec: stop describing a Rust maintenance refusal as Unavailable

Both volume servers now refuse in maintenance mode with Unknown, so the
orphan sweep's Ping disambiguation comments no longer name Rust.

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-24 12:31:52 -08:00
0f3a9b315c filer: assignment tokens and chunk proofs for scoped writes (#12923)
* filer: assignment tokens and chunk proofs for scoped writes

* filer: tighten scoped chunk identities and write boundaries

* filer: apply gRPC key removal on config reload

* filer: prevent scoped chunk alias and remote append data loss

* filer: guard scoped writes across stored data representations

* filer: preserve lazy scoped admission lookups

* filer: avoid summing chunk counts for map capacity

* filer: keep a scoped assign in its path's collection

A scoped token could name another bucket's collection in AssignVolume and
upload chunks there, charging that bucket's quota and losing them when that
collection is deleted. A scoped caller now gets the collection its path
resolves to; naming a different one is refused before the master call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: rotate gRPC keys and bind chunk proofs to collections

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:30:46 -08:00
975d79d57f filer: keep chunk coverage when timestamps tie in readResolvedChunks (#12940)
* filer: keep chunk coverage when timestamps tie in readResolvedChunks

When an overlapping chunk started with the same ModifiedTsNs as the
currently visible one, it was never inserted into the sweep queue, and
an END point removed whichever queued chunk had a matching ts rather
than the chunk that actually ended. Either way part of the file was
dropped from the visible intervals, and SeparateGarbageChunks could then
treat the still-live chunk as garbage.

Insert tied starts ahead of the existing tail so the visible chunk keeps
winning, and remove the queued entry for the chunk that is ending.

Fixes #12934

* filer: break readResolvedChunks timestamp ties by chunk order

On a tie the sweep let the chunk that started first keep the overlap, while
MergeIntoVisibles, which a section uses when a chunk is added after its
first read, lets the later chunk win. A later write that got the same
timestamp lost its overlap, and the two paths disagreed on which chunk's
bytes a read returns and which chunk is garbage. Ties now go to the later
chunk in the list, which also makes the order total.

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-24 12:29:25 -08:00
6f87fbffe5 build(deps): bump golang.org/x/term from 0.47.0 to 0.48.0 (#12924)
* build(deps): bump golang.org/x/term from 0.47.0 to 0.48.0

Bumps [golang.org/x/term](https://github.com/golang/term) from 0.47.0 to 0.48.0.
- [Commits](https://github.com/golang/term/compare/v0.47.0...v0.48.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  dependency-version: 0.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* telemetry: tidy go.mod for golang.org/x/sys v0.50.0

The x/term bump raises x/sys in the root module, which telemetry/server
replaces, so its build failed with "updates to go.mod needed".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@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-24 12:27:50 -08:00
caeadb2db2 mount: refuse RENAME_EXCHANGE instead of renaming over the target (#12921)
* mount: refuse RENAME_EXCHANGE instead of renaming over the target

renameat2(a, b, RENAME_EXCHANGE) asks for the two names to be swapped
atomically. Rename let the flag through and went on as a plain rename, so
a was moved over b, b's content was gone, and the call reported success.

The filer's rename moves one entry and cannot swap two, so the mount now
answers EINVAL, which is what renameat2(2) returns for a flag the file
system does not support, and callers fall back on it.

RenameWhiteout was 3, which is RENAME_NOREPLACE|RENAME_EXCHANGE; the flag
is 1<<2. Both values, and any other flag the mount does not implement,
now get the same EINVAL (3 answered ENOTSUP, 4 already EINVAL).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: trim the rename flag comments

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-24 12:24:39 -08:00
Chris LuandClaude Opus 5.5 93e7a81b01 mount: refuse names that are not valid UTF-8 instead of rewriting them (#12952)
The mount replaced every invalid UTF-8 run in a name with "_" so the name
could go into proto string fields. That mapped different names to one entry:
two legacy-encoded names shared one file, a write or unlink through an
invalid name hit an existing file with "_" in its place, and O_EXCL failed
with EEXIST for a name that did not exist.

Making such a name (create, mknod, mkdir, symlink, link, rename target) now
fails with EILSEQ, and looking one up or removing it answers ENOENT, before
anything is sent to the filer. Entries stored earlier under a rewritten name
stay reachable by that name.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:40:58 -08:00
9fc8a6aec2 mount: read SSE-S3 objects through the S3 gateway (#12909)
* mount: read SSE-S3 objects through an authenticated S3 gateway

* mount: check each comma-joined mount option against -sseS3ReadEndpoint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: read a mounted version file by its object key and version id

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: read a current null-version object without s3:GetObjectVersion

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: declare -sseS3ReadEndpoint with the other mount options so weed fuse accepts it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: require the canonical bucket path as the root of an SSE-S3 read mount

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: fall back to the null version when the current object is another version

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* master: list the S3 endpoint each S3 gateway advertises

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3: advertise the gateway's S3 endpoint to the master

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: find the S3 gateway through the masters instead of -sseS3ReadEndpoint

-sseS3Read turns gateway reads on. The reader lists the S3 endpoints the
filer's masters have registered, prefers HTTPS, and picks another gateway
when the current one cannot be reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: retry an unreachable S3 gateway read on a different gateway

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: warn when -sseS3Read falls back to a plain-HTTP gateway

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: do not retry an unreachable HTTPS gateway over plain HTTP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: tell HTTPS gateways apart by the parsed URL scheme

An S3 gateway advertised as HTTPS://host lost the HTTPS preference and
the plain-HTTP fallback guard, since the check matched the raw string.

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-24 10:32:18 -08:00
github-actions[bot] 93c6f8d64a docs: regenerate star history chart 2026-11-24 01:45:48 +00:00
89d5192831 filer: guard entry updates against rename/delete races (TiKV, FoundationDB) (#12918)
* filer: run an entry update again when a rename or delete of it commits meanwhile

UpdateEntry reads the entry, checks its preconditions against it, then
writes. The path lock keeps the two together only against writers of that
path on that filer. A rename or a delete sent to another filer does not
take it, and on any filer a rename or recursive delete of a directory above
the entry moves and removes what is below it unlocked. One that committed
between the read and the write had the write store the entry again at the
path it had left, and the update returned success: the entry back under a
directory that is gone, two names sharing chunks, or a file back after its
unlink returned.

Where the store refuses a conflicting commit, the read, the checks and the
write now run in one store transaction. The rename or delete wrote the
entry's key after it began, so the commit is refused with
ErrTransactionConflict and the update runs again, up to five times with
the rename's back-off, and answers from what is there now.

- filer.ConflictRefusingStore is how a store says so. TiKV does. Other
  stores, and entries in a path-specific store, run once without a
  transaction, as before.
- A refused run gives up its commit stamp and deletes the manifest chunks
  it folded the request's chunks into.
- Chunk deletion and the metadata event come after the commit, in the
  order they had.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: commit what an update's lookup removed, give up a failed run's manifests

From the review of 156a0078c.

FindEntry removes an expired entry and, for an expired S3 object, tells the
subscribers. Inside the update's transaction a NotFound rolled that removal
back while the event stayed, and the next lookup announced it again. What
the read answers the update with (the entry is not there, a precondition
does not hold) is now the run's result and not its failure: the run commits
whatever the lookup removed and UpdateEntry returns the answer. Only an
error of the write itself rolls back.

A run that fails after cleanupChunks folded the request's chunks into
manifests is rolled back, so nothing refers to them: it now gives them up
the way a run with a refused commit does. The cleanup tolerates a run that
got no further than its lookup.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* filer: leave an expired S3 object to a lookup outside a transaction

FindEntry's removal of an expired S3 object deletes a remote copy and
publishes a delete event at once. Inside a store transaction a refused
commit restores the entry but not those, so subscribers could keep a
delete for a path that still holds an entry. A lookup in a transaction
now only answers NotFound and leaves the removal to one outside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer: guard update retries and retain expired rename targets

Reject retries when the originally observed entry changes, so stale requests cannot restore chunks already deleted by a concurrent writer. Keep expired S3 overwrite targets visible to rename cleanup, and defer overwritten remote-object deletion until commit succeeds. Add regression coverage for concurrent updates and renames, both rename RPCs, remote data, and rollback.

* filer: extend conflict-checked entry updates to FoundationDB

Specify the optional capability in terms of entry/KV read-modify-write conflicts, without promising atomic bulk operations or blind-write conflicts. Opt FoundationDB into the update transaction path and normalize only known uncommitted conflicts. Add routing, error-classification, and live FoundationDB entry/KV conflict tests, and document its transaction boundaries.

* filer: prepare update manifests outside metadata transactions

* filer: keep update rereads from restoring renamed remote entries

---------

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>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-11-23 15:58:12 -08:00
6f248fc190 mount: keep a clean handle off the file a peer renamed over the one it has open (#12920)
* mount: keep a clean handle off the file a peer renamed over the one it has open

A peer renames another file over the one a handle has open here. When this
mount has looked the rename's source up, MovePath reports the handle's inode
as replaced and the handle is marked deleted. When it has not, which is the
usual case for "write a temp file, rename it over the real one" done on
another mount, MovePath has nothing to move and reports nothing. The event
for the target path then reaches the handle as an update: a dirty handle
refuses it, but a clean one installs the newcomer's entry, and everything
the descriptor does afterwards lands in the replacement: writes, mmap
writes, ftruncate, fchmod, fsetxattr.

A clean handle now takes an entry with another inode at its path for what it
is. The handle is marked deleted, as after a delete, and its inode gives the
name up as a replaced rename target does, so the kernel gets ESTALE for the
old inode, walks the path again and reaches the newcomer under an inode of
its own. An entry or a handle without an inode cannot tell and installs as
before, and so does an update in place, which keeps the inode.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: a replaced handle keeps a surviving hard link, a renamed one ignores its old name

From the review of a4c9a89a6.

- A hard-linked file replaced under one of its names lives on under the
  others. The handle follows it to a name this mount knows, as after a
  peer's unlink of one name, instead of being marked deleted.
- A handle that just followed its file's rename no longer reads the cache
  at the path it left. When another file had taken that name before the
  rename was applied to the handle, the handle was marked deleted (and
  before this branch, installed that file's entry).
- The replaced name is taken from the inode only while it is still the
  inode's (RemovePathOf): a rename on this mount may have handed it to
  another inode in between.
- The kernel keeps resolving the name to the old inode for as long as it
  trusts its lookup (entryValidSec). A chmod by path in that window went to
  the detached handle and reported success. The lookup is dropped with
  EntryNotify, from the invalidation worker after the handle's locks are
  released.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* mount: mark a replaced handle deleted only once its inode gives up the name

The worker looks the inode up by name before it takes the handle's lock,
so a rename on this mount can move the inode off that name in between.
The handle was then marked deleted while its file lived on under the new
name, and its flushes were dropped. RemovePathOf now decides: when the
name is no longer the inode's, the event is another file's and the
handle is left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: release the worker gate on every exit of the renamed-handle test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: check alias ownership before following surviving links

---------

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>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-11-23 14:19:08 -08:00
Chris LuandClaude Opus 5.5 c7cf9db27c fix/compact: stop at records past EOF, report -ignoreError failures, clean up failed compaction (#12915)
* fix: do not index a record that runs past the end of the .dat

A truncated .dat, or a header whose size points past the file end, left
weed fix indexing a needle the volume cannot serve. Stop the scan at such a
record instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: exit non-zero under -ignoreError when a volume fails

-ignoreError kept going but always exited 0, so an empty or partial index
looked like success. Record the failure in the exit status, and keep the
existing .idx when the super block could not be read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* compact: remove the partial .cpd/.cpx when compaction fails

A failed weed compact exited through glog.Fatalf and left a partial .cpd
next to the volume. Remove both outputs and report the failure in the
exit status instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: skip the end-of-file check for a volume on a remote tier

The scan reads the remote object when the .vif lists one, so a retained
local .dat is the wrong length to check records against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep a key deleted when its last record is truncated

Stopping before a truncated delete record left the key's earlier live
record in the index, so a deleted file came back. Drop the key instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: return the .idx open error from SaveToIdx

The bare return gave back the nil named result, so a failure to open the
index looked like a successful save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: exit non-zero when a record is cut off by the end of the .dat

A record past EOF ends the scan like a bad header does, so report it the
same way while keeping the index of the records before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* compact: close the volume before removing a failed compaction's output

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: remove a failed .idx only after SaveToIdx opened it

An open failure no longer reaches the caller's cleanup, so an existing
.idx that could not be opened is left in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 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>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:58:26 -08:00
9a98047e2a util/http: hedge a chunk read whose location goes quiet (#12917)
* util/http: hedge a chunk read whose location goes quiet

A chunk read tried its locations one at a time and read each answer to the
end. A response that stops arriving holds the read for as long as TCP takes
to recover: on a lossy path a lost segment costs at least the 200 ms
retransmission timeout, doubled for every further loss, and nothing gives
up on the connection meanwhile. A sequential reader waits for its chunks in
order, so one stalled chunk stops it, although a replica could send the
chunk in milliseconds. A location that never answers holds the read for the
transport's response header timeout.

In production this showed up as 13 GB checkpoint verifications, read back
serially with O_DIRECT through weed mount, crawling at 25-65 MB/s instead
of 300 MB/s and more, while the hosts of the volume servers saw 2-5% TCP
retransmissions. The volume servers' own GET latency stayed at a few
milliseconds: the stall is on the wire, after the handler has written the
chunk into the socket buffer.

hedgedChunkPass keeps the order and the move-on-at-failure of the old
loops. In addition, once every request in flight has been quiet for longer
than it may be, the read is asked of the next location as well, or, once
every location has been asked, again over a new connection of a location
whose server answered. A request may be quiet for 200 ms before its
response headers, while the server may still be reading the needle from a
busy disk, and for 100 ms in the body, which a healthy server sends without
pauses: half the minimum retransmission timeout, ahead of every wait for a
retransmission, while shorter pauses that recover on their own go by. The first complete answer wins, and the other requests are
cancelled. A read hedges at most twice.

The first request reads straight into the caller's buffer, as before.
Hedges read into pooled buffers, and a winning hedge is copied over only
after the request writing the caller's buffer has ended, so the buffer has
one writer at a time and is not written after the call returns.

Hedging is budgeted: every read earns a tenth of a token, a hedge spends
one, and at most ten are saved up, so hedges stay below about a tenth of
the reads when the whole cluster is slow. A location that had sent no
response headers when another one delivered the chunk is recorded as
unreachable, which leaves it to the background probe of #12776 to put it
first again, and counts as a failure for the location refresh. A body that
stalled after its headers does neither.

Measured with two volume servers whose outgoing links drop packets (netem,
MTU 1500, 0.2 ms delay), reading a 1 GiB file of 2 MiB chunks through weed
mount with dd iflag=direct bs=4M, before and after:

  bursty loss ~2.3% on both replicas   26-76 MB/s   162-193 MB/s
  random loss 3% on both replicas     106-119 MB/s  147-170 MB/s
  random loss 5% on one replica only   71-81 MB/s   157-158 MB/s
  no loss                             no change, 0-2 hedges per 512 reads

Under loss 4-8% of the chunk reads were hedged. A 50 ms body limit did
better on random loss (179-220 MB/s with 3% on both) but worse and less
steadily on bursty loss (108-206 MB/s), where it spent the hedge budget on
pauses that recover by themselves.

Callers: RetriedFetchChunkData on the streaming and the direct path, which
weed mount, the S3 gateway and the WebDAV server read chunks through.
Readers that stream a chunk to a writer as it arrives are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: account hedge buffers, go past a throttled hedge, cap hedges per read

Three review findings:

- A hedge reads into a buffer of its own, which weed mount's reader cache
  budget did not see, so stalled downloads could hold twice the configured
  memory. The reader cache now passes its budget in the context
  (WithScratchBudget), and a hedge first takes room for its buffer with
  ReaderCacheBudget.TryReserveScratch. Like a download, that evicts idle
  chunks no stream is positioned in, but it never waits and never evicts a
  pinned chunk or a download in flight: a hedge that does not fit is not
  sent. The room is returned when the buffer is freed, also for requests
  abandoned in the background.

- A hedge answered with 429 ended the asking, so the read waited out the
  stalled request although a third location was idle. The download limit
  behind a 429 is local to that server, so a throttled hedge now moves on to
  the next location; the 429 is still returned when nothing else delivers.

- Each retry pass earned a new budget share and started a new count of two
  hedges. Both now belong to the read (readHedges) and carry over its passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: note an error's headers as an answer, take a hedge token before room

Second round of review findings:

- A location that sent the headers of an error response (a 500, say) and
  then stalled its body was still taken for one that had not answered while
  StatusError waited for that body. Had another location delivered the chunk
  meanwhile, it was recorded as unreachable and the location list refreshed.
  The response headers are now noted as soon as Do returns, before the
  status is looked at.

- A hedge took room for its buffer before its token, and room can evict
  cached chunks. With no token left the room was given back, but the chunks
  were gone. The token now comes first, and is given back when there is no
  room.

- TestReaderCacheBudgetLendsScratchToHedges opens the gate of the download
  it holds in a defer, so a failed assertion cannot leave the cache's
  teardown waiting on it. TestChunkReadHedgeCapCoversRetries also checks that
  the read earned its budget share once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: do not take a location asked again for unreachable

A location whose response stalled is asked again over a new connection.
When the first request then recovered and delivered the chunk, the new
request had not answered yet, so the host that just served the chunk was
recorded as unreachable and the location list refreshed. A location any
request of the read heard from is no longer counted.

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-23 13:29:07 -08: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
1663 changed files with 173870 additions and 16581 deletions

No files matched your search

+3 -1
View File
@@ -1,6 +1,6 @@
[codespell]
# Ref: https://github.com/codespell-project/codespell#using-a-config-file
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go
skip = .git,.git-meta,.gitignore,.gitattributes,*.svg,go.sum,vendor,*.lock,*.css,*.min.*,.codespellrc,*_templ.go,./seaweed-block
check-hidden = true
# Ignore camelCase and PascalCase identifiers (very common in Go/Rust/JS
# source, e.g. allLocations, publishErr, ReadInside, FlushInterval).
@@ -22,3 +22,5 @@ ignore-regex = \b[a-z]+[A-Z]\w*\b|\b[A-Z][a-z]+[A-Z]\w*\b
# sme: local variable for a *streamMutateError in mount tests
# nin: AWS S3 Vectors "$nin" filter operator literal (API-defined, cannot rename)
ignore-words-list = visibles,fo,te,ser,bject,unparseable,keep-alives,tread,anc,ue,auther,thirdparty,unknwon,atleast,sme,nin
# poligon: Yandex Disk API sandbox URL path (https://yandex.ru/dev/disk/poligon/)
uri-ignore-words-list = poligon
@@ -16,6 +16,7 @@ runs:
if: inputs.target == 'x86_64-unknown-linux-musl'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y musl-tools
# C deps (aws-lc-sys) must compile against musl headers, not the host
# gcc's glibc headers — glibc's C23 redirects (__isoc23_sscanf,
@@ -26,6 +27,7 @@ runs:
if: inputs.target == 'aarch64-unknown-linux-musl'
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y gcc-aarch64-linux-gnu
echo "CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=aarch64-linux-gnu-gcc" >> "$GITHUB_ENV"
# Disable glibc fortify source — its __memcpy_chk etc. symbols don't exist in musl
+1 -1
View File
@@ -15,7 +15,7 @@ runs:
using: composite
steps:
- name: Install cosign
uses: sigstore/cosign-installer@v4.1.3
uses: sigstore/cosign-installer@v4.1.4
- name: Sign
shell: bash
+112 -22
View File
@@ -8,38 +8,44 @@ on:
- 'go.mod'
- 'go.sum'
- '.github/workflows/binaries_dev.yml'
workflow_dispatch:
# Let an in-progress dev build finish. A new push replaces only the pending
# run; cancelling mid-build left the dev release without assets.
concurrency:
group: binaries-dev-${{ github.ref }}
cancel-in-progress: true
cancel-in-progress: false
permissions:
contents: read
jobs:
cleanup:
permissions:
contents: write # for mknejp/delete-release-assets to delete release assets
prepare:
runs-on: ubuntu-latest
outputs:
build_time: ${{ steps.build_time.outputs.value }}
steps:
- name: Ref guard
if: github.ref != 'refs/heads/master'
env:
GH_REF: ${{ github.ref }}
run: |
echo "dev builds only publish from master (got $GH_REF)" >&2
exit 1
- name: Delete old release assets
uses: mknejp/delete-release-assets@v1
continue-on-error: true
with:
token: ${{ github.token }}
tag: dev
fail-if-no-assets: false
assets: |
weed-*
- name: Set BUILD_TIME
id: build_time
run: |
echo "value=$(date -u +%Y%m%d-%H%M)" >> "$GITHUB_OUTPUT"
build_dev_linux_windows:
permissions:
contents: write # for wangyoucao577/go-release-action to upload release assets
needs: cleanup
needs: prepare
runs-on: ubuntu-latest
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
goos: [linux, windows]
@@ -47,15 +53,17 @@ jobs:
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- name: Check out code into the Go module directory
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v2
- name: Set BUILD_TIME env
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> ${GITHUB_ENV}
- name: Go Release Binaries Large Disk
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -72,6 +80,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -87,8 +96,10 @@ jobs:
build_dev_darwin:
permissions:
contents: write # for wangyoucao577/go-release-action to upload release assets
needs: build_dev_linux_windows
needs: [prepare, build_dev_linux_windows]
runs-on: ubuntu-latest
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
goos: [darwin]
@@ -96,15 +107,17 @@ jobs:
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- name: Check out code into the Go module directory
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v2
- name: Set BUILD_TIME env
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> ${GITHUB_ENV}
- name: Go Release Binaries Large Disk
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -121,6 +134,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -132,3 +146,79 @@ jobs:
project_path: weed
binary_name: weed-normal-disk
asset_name: "weed-${{ env.BUILD_TIME }}-${{ matrix.goos }}-${{ matrix.goarch }}"
prune:
needs: [prepare, build_dev_linux_windows, build_dev_darwin]
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
RELEASE_TAG: dev
steps:
- name: Delete dev binaries from older builds
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
: "${BUILD_TIME:?BUILD_TIME is empty}"
case "$BUILD_TIME" in
[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]) ;;
*) echo "Invalid BUILD_TIME: $BUILD_TIME" >&2; exit 1 ;;
esac
release_tag="${RELEASE_TAG:-dev}"
if ! release_json=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$release_tag" 2>&1); then
case "$release_json" in
*"Not Found"*) echo "No $release_tag release; nothing to prune"; exit 0 ;;
esac
echo "Release lookup failed: $release_json" >&2
exit 1
fi
release_id=$(jq -r '.id // empty' <<<"$release_json")
if [ -z "$release_id" ]; then
echo "Release lookup returned no id" >&2
exit 1
fi
assets_file=$(mktemp)
trap 'rm -f "$assets_file"' EXIT
if ! gh api "repos/$GITHUB_REPOSITORY/releases/$release_id/assets" --paginate \
--jq '.[] | select((.name | startswith("weed-large-disk-")) or (.name | test("^weed-[0-9]"))) | [.id, .name] | @tsv' \
> "$assets_file"; then
echo "Failed to list release assets" >&2
exit 1
fi
total=$(awk 'END{print NR+0}' "$assets_file")
matching=$(awk -v s="-$BUILD_TIME-" 'index($0,s){n++} END{print n+0}' "$assets_file")
if [ "$matching" -eq 0 ]; then
echo "No assets carry stamp $BUILD_TIME; refusing to prune" >&2
exit 1
fi
build_key=${BUILD_TIME/-/}
kept=0; newer=0; deleted=0; gone=0; failed=0
while IFS=$'\t' read -r id name || [ -n "${name:-}" ]; do
[ -n "${id:-}" ] || continue
case "$name" in
*"-$BUILD_TIME-"*) kept=$((kept+1)); continue ;;
esac
if [[ "$name" =~ -([0-9]{8})-([0-9]{4})- ]] && [ "${BASH_REMATCH[1]}${BASH_REMATCH[2]}" -gt "$build_key" ]; then
newer=$((newer+1)); continue
fi
if out=$(gh api -X DELETE "repos/$GITHUB_REPOSITORY/releases/assets/$id" </dev/null 2>&1); then
deleted=$((deleted+1))
else
case "$out" in
*"Not Found"*) gone=$((gone+1)) ;;
*) failed=$((failed+1)); echo "Failed to delete asset $name ($id): $out" >&2 ;;
esac
fi
done < "$assets_file"
[ "$((kept+newer+deleted+gone+failed))" -eq "$total" ] || { echo "Processed $((kept+newer+deleted+gone+failed)) of $total assets" >&2; exit 1; }
echo "Kept $kept assets from this build and $newer from newer builds; deleted $deleted older assets; $gone already gone; $failed failures"
[ "$failed" -eq 0 ] || { echo "::warning::prune: $failed deletions failed"; exit 1; }
+2
View File
@@ -32,6 +32,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -46,6 +47,7 @@ jobs:
- name: Go Release Large Disk Binaries
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
+2
View File
@@ -32,6 +32,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -46,6 +47,7 @@ jobs:
- name: Go Release Large Disk Binaries
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
+2
View File
@@ -32,6 +32,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -46,6 +47,7 @@ jobs:
- name: Go Release Large Disk Binaries
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
+2
View File
@@ -32,6 +32,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -46,6 +47,7 @@ jobs:
- name: Go Release Large Disk Binaries
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
+2
View File
@@ -32,6 +32,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -47,6 +48,7 @@ jobs:
- name: Go Release Large Disk Binaries
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
+2
View File
@@ -32,6 +32,7 @@ jobs:
- name: Go Release Binaries Normal Volume Size
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
@@ -46,6 +47,7 @@ jobs:
- name: Go Release Large Disk Binaries
uses: wangyoucao577/go-release-action@279495102627de7960cbc33434ab01a12bae144b # v1.22
with:
goversion: go.mod # reads the go directive, so releases build with the toolchain go.mod declares
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
+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.5
# 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.5
# ℹ️ 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.5
+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.5
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.5
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
+1 -1
View File
@@ -15,4 +15,4 @@ jobs:
- name: 'Checkout Repository'
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
- name: 'Dependency Review'
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec
+4 -4
View File
@@ -31,16 +31,16 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Build weed binary
run: |
cd weed && go build -o weed .
+24
View File
@@ -125,6 +125,28 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 10s
--health-timeout 5s
--health-retries 5
mysql:
image: mysql:8.4
env:
MYSQL_ROOT_PASSWORD: root
ports:
- 3306:3306
options: >-
--health-cmd "mysqladmin ping -uroot -proot"
--health-interval 10s
--health-timeout 5s
--health-retries 10
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
@@ -136,6 +158,8 @@ jobs:
- name: Test
env:
RUN_REDIS_TESTS: "1"
RUN_POSTGRES_TESTS: "1"
RUN_MYSQL_TESTS: "1"
run: cd weed; go test -tags "elastic gocdk sqlite ydb tarantool tikv rclone" -v ./...
test-32bit:
+127
View File
@@ -0,0 +1,127 @@
name: Graph
# Builds a code knowledge graph with the open-source Graphify CLI and uploads
# it as an artifact; a published release, or a dispatch naming a tag, also
# gets it as a release asset. Code-only mode parses the repository with
# tree-sitter and needs no API key or secret. Only the release job holds a
# write token, and it runs no third-party code.
#
# A release created with the default GITHUB_TOKEN does not trigger this
# workflow; dispatch it with the tag in that case.
#
# The graph is not committed: graph.json is ~150 MiB, above GitHub's 100 MiB
# file limit.
on:
schedule:
- cron: "23 4 * * *"
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Release tag to build and attach the bundle to (empty: artifact only)"
required: false
type: string
concurrency:
group: graph-${{ github.ref }}-${{ inputs.tag }}
cancel-in-progress: true
permissions:
contents: read
env:
GRAPHIFY_VERSION: "0.9.112"
# Stable community ids across runs.
PYTHONHASHSEED: "0"
# Never call an LLM, even if a runner image ships an API key or the claude
# CLI: cluster-only auto-detects a labeling backend otherwise.
GRAPHIFY_BACKEND: "none"
TAG: ${{ github.event.release.tag_name || inputs.tag }}
jobs:
graph:
name: Build code graph
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@v7
with:
ref: ${{ env.TAG && format('refs/tags/{0}', env.TAG) || '' }}
persist-credentials: false
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: "3.12"
- name: Install graphify
run: python -m pip install "graphifyy==${GRAPHIFY_VERSION}"
# Always a full extraction: graphify update re-extracts only changed
# files, so callers in unchanged files keep edges to a function's old
# id after it moves to another file.
- name: Build the graph
run: |
# Cluster once: extract alone does not write the report or HTML.
# cluster-only names communities after their hub nodes
# (GRAPHIFY_BACKEND=none keeps it from calling an LLM).
graphify extract . --code-only --no-cluster
graphify cluster-only .
- name: Graph health
run: |
graphify diagnose multigraph --json > graph-health.json
python3 - <<'PY' >> "$GITHUB_STEP_SUMMARY"
import json
summary = json.load(open("graph-health.json")).get("summary", {})
print("### Graph health")
print(f"- nodes: {summary.get('node_count', 'n/a')}")
print(f"- edges: {summary.get('raw_edge_count', 'n/a')}")
print(f"- dangling endpoints: {summary.get('dangling_endpoint_edges', 'n/a')}")
print(f"- duplicate edges: {summary.get('exact_duplicate_edges', 'n/a')}")
PY
- name: Bundle outputs
run: |
gzip -9 -c graphify-out/graph.json > graph.json.gz
files=(graph.json.gz graphify-out/GRAPH_REPORT.md graph-health.json)
# graphify skips graph.html when it cannot aggregate a large graph.
if [ -f graphify-out/graph.html ]; then
files+=(graphify-out/graph.html)
else
echo "::warning::graphify-out/graph.html was not generated"
fi
tar -czf graph-bundle.tar.gz "${files[@]}"
- name: Upload graph artifact
uses: actions/upload-artifact@v7
with:
name: graph-${{ github.sha }}
path: graph-bundle.tar.gz
retention-days: 14
release:
name: Attach graph bundle
needs: graph
if: github.event_name == 'release' || inputs.tag != ''
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
steps:
- name: Download graph artifact
uses: actions/download-artifact@v8
with:
name: graph-${{ github.sha }}
- name: Upload release asset
env:
GH_TOKEN: ${{ github.token }}
run: |
asset="graph-${TAG//\//-}.tar.gz"
mv graph-bundle.tar.gz "${asset}"
gh release upload "${TAG}" "${asset}" --clobber --repo "${GITHUB_REPOSITORY}"
+77
View File
@@ -149,6 +149,83 @@ jobs:
grep -q "terminationGracePeriodSeconds: 85$" /tmp/aio-s3-prestop-own.yaml
echo "S3 preStopSeconds renders correctly"
echo "=== Testing shareProcessNamespace ==="
for workload in filer:templates/filer/filer-statefulset.yaml s3:templates/s3/s3-deployment.yaml; do
component=${workload%%:*}
template=${workload#*:}
helm template test $CHART_DIR --show-only "$template" \
--set "$component.enabled=true" > /tmp/spn-default.yaml
test "$(grep -c 'shareProcessNamespace' /tmp/spn-default.yaml)" -eq 0
helm template test $CHART_DIR --show-only "$template" \
--set "$component.enabled=true" --set "$component.shareProcessNamespace=true" > /tmp/spn.yaml
grep -q '^ shareProcessNamespace: true$' /tmp/spn.yaml
done
echo "shareProcessNamespace renders correctly"
echo "=== Testing volumeAttributesClassName ==="
pvc_args=(--set allInOne.enabled=true --set allInOne.data.type=persistentVolumeClaim
--set admin.enabled=true --set admin.allowInsecureBind=true --set volume.dataDirs[0].name=data1)
for claim in master.data master.logs filer.data filer.logs admin.data admin.logs \
volume.idx volume.logs volume.dataDirs[0]; do
pvc_args+=(--set "$claim.type=persistentVolumeClaim" --set "$claim.size=1Gi")
done
helm template test $CHART_DIR "${pvc_args[@]}" > /tmp/vac-default.yaml
test "$(grep -c 'volumeAttributesClassName' /tmp/vac-default.yaml)" -eq 0
for claim in master.data master.logs filer.data filer.logs admin.data admin.logs \
volume.idx volume.logs volume.dataDirs[0] allInOne.data; do
pvc_args+=(--set "$claim.volumeAttributesClassName=fast")
done
helm template test $CHART_DIR "${pvc_args[@]}" > /tmp/vac.yaml
test "$(grep -c '^ *volumeAttributesClassName: "fast"$' /tmp/vac.yaml)" -eq 10
helm template test $CHART_DIR --set master.data.type=persistentVolumeClaim \
--set-string master.data.volumeAttributesClassName=null > /tmp/vac-null.yaml
grep -q '^ *volumeAttributesClassName: "null"$' /tmp/vac-null.yaml
echo "volumeAttributesClassName renders correctly"
echo "=== Testing the S3 config reloader ==="
for workload in filer.s3:templates/filer/filer-statefulset.yaml s3:templates/s3/s3-deployment.yaml; do
prefix=${workload%%:*}
template=${workload#*:}
component=${prefix%%.*}
reloader_args=(--set "$prefix.enabled=true" --set "$prefix.enableAuth=true"
--set "$prefix.existingConfigSecret=s3-identities"
--set "$component.containerSecurityContext.enabled=true"
--set "$component.containerSecurityContext.runAsUser=1000")
helm template test $CHART_DIR --show-only "$template" "${reloader_args[@]}" > /tmp/reloader-off.yaml
test "$(grep -c 's3-config-reloader\|shareProcessNamespace' /tmp/reloader-off.yaml)" -eq 0
helm template test $CHART_DIR --show-only "$template" "${reloader_args[@]}" \
--set "$prefix.configReloader.enabled=true" \
--set "$prefix.configReloader.resources.limits.memory=32Mi" > /tmp/reloader-on.yaml
python3 - /tmp/reloader-off.yaml /tmp/reloader-on.yaml <<'PYEOF'
import sys, yaml
off, on = (yaml.safe_load(open(path)) for path in sys.argv[1:])
pod = on["spec"]["template"]["spec"]
main = pod["containers"][0]
reloader = next(c for c in pod["containers"] if c["name"] == "s3-config-reloader")
assert pod["shareProcessNamespace"] is True
assert reloader["image"] == main["image"]
# It must run as the same user as SeaweedFS to signal it.
assert reloader["securityContext"] == main["securityContext"], reloader.get("securityContext")
assert {"name": "config-users", "mountPath": "/etc/sw", "readOnly": True} in reloader["volumeMounts"]
assert reloader["resources"] == {"limits": {"memory": "32Mi"}}
# Without the reloader, the checksum hashes the existing Secret, so a change to it restarts the pod.
# With it, nothing may: not the Secret, and not the values of the Secret the chart generates.
annotations = lambda d: d["spec"]["template"]["metadata"].get("annotations") or {}
assert "checksum/s3config" in annotations(off)
assert "checksum/s3config" not in annotations(on), annotations(on)
PYEOF
# A release from a chart without configReloader, upgraded with --reuse-values, has no such map.
helm template test $CHART_DIR --show-only "$template" "${reloader_args[@]}" \
--set "$prefix.configReloader=null" > /tmp/reloader-old-values.yaml
test "$(grep -c 's3-config-reloader' /tmp/reloader-old-values.yaml)" -eq 0
if helm template test $CHART_DIR --show-only "$template" \
--set "$prefix.enabled=true" --set "$prefix.configReloader.enabled=true" > /tmp/reloader-noauth.yaml 2>&1; then
echo "FAIL: $prefix.configReloader rendered without $prefix.enableAuth"; exit 1
fi
grep -q "configReloader.enabled needs" /tmp/reloader-noauth.yaml
done
echo "S3 config reloader 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
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
- name: Run Client Unit Tests
working-directory: other/java/client
run: |
mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest
mvn test -Dtest=SeaweedReadTest,SeaweedCipherTest,FilerJwtTest
- name: Run HDFS3 Configuration Tests
working-directory: other/java/hdfs3
+1 -1
View File
@@ -42,7 +42,7 @@ jobs:
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: |
**/go.sum
+23 -23
View File
@@ -43,23 +43,23 @@ jobs:
matrix:
container-id: [unit-tests-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 1.0 --memory 1g --hostname kafka-unit-${{ matrix.container-id }}
env:
GOMAXPROCS: 1
CGO_ENABLED: 0
CONTAINER_ID: ${{ matrix.container-id }}
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code
uses: actions/checkout@v7
- name: Setup Container Environment
run: |
apk add --no-cache git
@@ -88,7 +88,7 @@ jobs:
matrix:
container-id: [integration-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 2.0 --memory 2g --ulimit nofile=1024:1024 --hostname kafka-integration-${{ matrix.container-id }}
env:
GOMAXPROCS: 2
@@ -96,16 +96,16 @@ jobs:
KAFKA_TEST_ISOLATION: "true"
CONTAINER_ID: ${{ matrix.container-id }}
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code
uses: actions/checkout@v7
- name: Setup Integration Container Environment
run: |
apk add --no-cache git procps
@@ -136,7 +136,7 @@ jobs:
matrix:
container-id: [e2e-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 2.0 --memory 2g --hostname kafka-e2e-${{ matrix.container-id }}
env:
GOMAXPROCS: 2
@@ -150,7 +150,7 @@ jobs:
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: |
**/go.sum
@@ -315,7 +315,7 @@ jobs:
matrix:
container-id: [consumer-group-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 1.0 --memory 2g --ulimit nofile=512:512 --hostname kafka-consumer-${{ matrix.container-id }}
env:
GOMAXPROCS: 1
@@ -329,7 +329,7 @@ jobs:
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: |
**/go.sum
@@ -477,7 +477,7 @@ jobs:
matrix:
container-id: [client-compat-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 1.0 --memory 1.5g --shm-size 256m --hostname kafka-client-${{ matrix.container-id }}
env:
GOMAXPROCS: 1
@@ -491,7 +491,7 @@ jobs:
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: |
**/go.sum
@@ -635,7 +635,7 @@ jobs:
matrix:
container-id: [smq-integration-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 1.0 --memory 2g --hostname kafka-smq-${{ matrix.container-id }}
env:
GOMAXPROCS: 1
@@ -649,7 +649,7 @@ jobs:
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: |
**/go.sum
@@ -796,7 +796,7 @@ jobs:
matrix:
container-id: [protocol-1]
container:
image: golang:1.26-alpine
image: golang:1.27-alpine
options: --cpus 1.0 --memory 1g --tmpfs /tmp:exec --hostname kafka-protocol-${{ matrix.container-id }}
env:
GOMAXPROCS: 1
@@ -804,16 +804,16 @@ jobs:
KAFKA_PROTOCOL_ISOLATION: "true"
CONTAINER_ID: ${{ matrix.container-id }}
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code
uses: actions/checkout@v7
- name: Setup Protocol Container Environment
run: |
apk add --no-cache git procps
+4 -4
View File
@@ -42,15 +42,15 @@ jobs:
path: test/plugin_workers/volume_balance
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Run plugin worker tests
run: go test -v ./${{ matrix.path }}
+8 -8
View File
@@ -39,7 +39,6 @@ permissions:
issues: write
env:
GO_VERSION: '1.26'
TIMEOUT: '45m'
jobs:
@@ -61,10 +60,11 @@ jobs:
- name: Clean up stale FUSE mounts
uses: ./.github/actions/cleanup-stale-fuse-mounts
- name: Set up Go ${{ env.GO_VERSION }}
- name: Set up Go
id: setup-go
uses: actions/setup-go@v7
with:
go-version: ${{ env.GO_VERSION }}
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
cache-dependency-path: |
go.sum
@@ -532,7 +532,7 @@ jobs:
const report = fs.readFileSync(reportPath, 'utf8');
const comment = `## POSIX Compliance Test Results
**Go Version:** ${{ env.GO_VERSION }}
**Go Version:** ${{ steps.setup-go.outputs.go-version }}
**FUSE Version:** ${{ matrix.fuse-version }}
**Test Type:** ${{ github.event.inputs.test_type || 'full' }}
@@ -570,7 +570,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version: ${{ env.GO_VERSION }}
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Install macFUSE
@@ -623,7 +623,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version: ${{ env.GO_VERSION }}
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Install security analysis tools
@@ -680,7 +680,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version: ${{ env.GO_VERSION }}
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Install dependencies
@@ -733,7 +733,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version: ${{ env.GO_VERSION }}
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Install dependencies
+138
View File
@@ -0,0 +1,138 @@
name: "postgres_flat Filer Store Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/**'
- 'test/postgres_flat/**'
- 'test/s3/versioning/**'
- 'test/testutil/**'
- 'test/volume_server/framework/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-flat-tests.yml'
- '.github/actions/fix-fusermount-setuid/**'
pull_request:
paths:
- 'weed/**'
- 'test/postgres_flat/**'
- 'test/s3/versioning/**'
- 'test/testutil/**'
- 'test/volume_server/framework/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/postgres-flat-tests.yml'
- '.github/actions/fix-fusermount-setuid/**'
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:
postgres-flat:
name: S3 and POSIX over postgres_flat
runs-on: ubuntu-24.04
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 20
steps:
- name: Checkout 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: Repair the fusermount3 setuid bit
uses: ./.github/actions/fix-fusermount-setuid
- name: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Run tests
env:
RUN_POSTGRES_TESTS: "1"
WEED_BINARY: ${{ github.workspace }}/weed/weed
run: go test -v -count=1 -timeout=20m ./test/postgres_flat/
versioning-suite:
name: S3 versioning suite over postgres_flat
runs-on: ubuntu-24.04
timeout-minutes: 30
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 20
steps:
- name: Checkout 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: Build SeaweedFS
run: go build -o weed/weed -buildvcs=false ./weed
- name: Start weed mini on postgres_flat
run: |
mkdir -p "$RUNNER_TEMP/config" "$RUNNER_TEMP/data"
: > "$RUNNER_TEMP/config/security.toml"
cat > "$RUNNER_TEMP/config/filer.toml" <<'EOF'
[postgres_flat]
enabled = true
hostname = "127.0.0.1"
port = 5432
username = "postgres"
password = "postgres"
database = "postgres"
sslmode = "disable"
EOF
weed/weed -config_dir="$RUNNER_TEMP/config" mini -ip=127.0.0.1 -ip.bind=127.0.0.1 \
-dir="$RUNNER_TEMP/data" -s3.config="$GITHUB_WORKSPACE/docker/compose/s3.json" \
-webdav=false -admin.ui=false > "$RUNNER_TEMP/weed.log" 2>&1 &
ready() {
curl -s -o /dev/null http://127.0.0.1:8333 &&
test "$(docker exec ${{ job.services.postgres.id }} psql -U postgres -Atc "SELECT count(*) FROM information_schema.columns WHERE table_name = 'filemeta' AND column_name = 'path'")" = 1
}
for i in $(seq 90); do ready && break; sleep 1; done
ready || { cat "$RUNNER_TEMP/weed.log"; exit 1; }
- name: Run the S3 versioning suite
env:
ENABLE_STRESS_TESTS: "true"
run: go test -v -count=1 -timeout=25m ./test/s3/versioning/
- name: Show the server log
if: failure()
run: tail -200 "$RUNNER_TEMP/weed.log"
+4 -4
View File
@@ -38,16 +38,16 @@ jobs:
run:
working-directory: test/postgres
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code
uses: actions/checkout@v7
- name: Configure Docker Hub mirror
run: |
echo '{"registry-mirrors": ["https://mirror.gcr.io"]}' | sudo tee /etc/docker/daemon.json
+113 -20
View File
@@ -7,32 +7,43 @@ on:
- 'seaweed-volume/**'
- 'seaweed-common/**'
- '.github/workflows/rust_binaries_dev.yml'
workflow_dispatch:
# Serialize dev builds of the shared "dev" release without cancelling a run.
concurrency:
group: rust-binaries-dev-${{ github.ref }}
cancel-in-progress: false
permissions:
contents: read
jobs:
cleanup:
permissions:
contents: write
prepare:
runs-on: ubuntu-latest
outputs:
build_time: ${{ steps.build_time.outputs.value }}
steps:
- name: Delete old Rust volume dev assets
uses: mknejp/delete-release-assets@v1
continue-on-error: true
with:
token: ${{ github.token }}
tag: dev
fail-if-no-assets: false
assets: |
weed-volume-*
- name: Ref guard
if: github.ref != 'refs/heads/master'
env:
GH_REF: ${{ github.ref }}
run: |
echo "dev builds only publish from master (got $GH_REF)" >&2
exit 1
- name: Set BUILD_TIME
id: build_time
run: |
echo "value=$(date -u +%Y%m%d-%H%M)" >> "$GITHUB_OUTPUT"
build-rust-volume-dev-linux:
permissions:
contents: write
needs: cleanup
needs: prepare
runs-on: ubuntu-24.04
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
include:
@@ -40,6 +51,11 @@ jobs:
asset_suffix: linux-amd64
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- uses: actions/checkout@v7
- name: Install Rust toolchain
@@ -57,9 +73,6 @@ jobs:
restore-keys: |
rust-dev-${{ matrix.target }}-
- name: Set BUILD_TIME
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> "$GITHUB_ENV"
- name: Build Rust volume server (large disk)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -96,8 +109,10 @@ jobs:
build-rust-volume-dev-darwin:
permissions:
contents: write
needs: build-rust-volume-dev-linux
needs: [prepare, build-rust-volume-dev-linux]
runs-on: macos-latest
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
strategy:
matrix:
include:
@@ -107,6 +122,11 @@ jobs:
asset_suffix: darwin-amd64
steps:
- name: Validate BUILD_TIME
run: |
: "${BUILD_TIME:?prepare output missing}"
- uses: actions/checkout@v7
- name: Install Rust toolchain
@@ -126,9 +146,6 @@ jobs:
restore-keys: |
rust-dev-${{ matrix.target }}-
- name: Set BUILD_TIME
run: echo BUILD_TIME=$(date -u +%Y%m%d-%H%M) >> "$GITHUB_ENV"
- name: Build Rust volume server (large disk)
env:
SEAWEEDFS_COMMIT: ${{ github.sha }}
@@ -161,3 +178,79 @@ jobs:
weed-volume-${{ env.BUILD_TIME }}-${{ matrix.asset_suffix }}.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
prune:
needs: [prepare, build-rust-volume-dev-linux, build-rust-volume-dev-darwin]
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write
env:
BUILD_TIME: ${{ needs.prepare.outputs.build_time }}
RELEASE_TAG: dev
steps:
- name: Delete Rust dev binaries from older builds
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
: "${BUILD_TIME:?BUILD_TIME is empty}"
case "$BUILD_TIME" in
[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]) ;;
*) echo "Invalid BUILD_TIME: $BUILD_TIME" >&2; exit 1 ;;
esac
release_tag="${RELEASE_TAG:-dev}"
if ! release_json=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$release_tag" 2>&1); then
case "$release_json" in
*"Not Found"*) echo "No $release_tag release; nothing to prune"; exit 0 ;;
esac
echo "Release lookup failed: $release_json" >&2
exit 1
fi
release_id=$(jq -r '.id // empty' <<<"$release_json")
if [ -z "$release_id" ]; then
echo "Release lookup returned no id" >&2
exit 1
fi
assets_file=$(mktemp)
trap 'rm -f "$assets_file"' EXIT
if ! gh api "repos/$GITHUB_REPOSITORY/releases/$release_id/assets" --paginate \
--jq '.[] | select(.name | startswith("weed-volume-")) | [.id, .name] | @tsv' \
> "$assets_file"; then
echo "Failed to list release assets" >&2
exit 1
fi
total=$(awk 'END{print NR+0}' "$assets_file")
matching=$(awk -v s="-$BUILD_TIME-" 'index($0,s){n++} END{print n+0}' "$assets_file")
if [ "$matching" -eq 0 ]; then
echo "No assets carry stamp $BUILD_TIME; refusing to prune" >&2
exit 1
fi
build_key=${BUILD_TIME/-/}
kept=0; newer=0; deleted=0; gone=0; failed=0
while IFS=$'\t' read -r id name || [ -n "${name:-}" ]; do
[ -n "${id:-}" ] || continue
case "$name" in
*"-$BUILD_TIME-"*) kept=$((kept+1)); continue ;;
esac
if [[ "$name" =~ -([0-9]{8})-([0-9]{4})- ]] && [ "${BASH_REMATCH[1]}${BASH_REMATCH[2]}" -gt "$build_key" ]; then
newer=$((newer+1)); continue
fi
if out=$(gh api -X DELETE "repos/$GITHUB_REPOSITORY/releases/assets/$id" </dev/null 2>&1); then
deleted=$((deleted+1))
else
case "$out" in
*"Not Found"*) gone=$((gone+1)) ;;
*) failed=$((failed+1)); echo "Failed to delete asset $name ($id): $out" >&2 ;;
esac
fi
done < "$assets_file"
[ "$((kept+newer+deleted+gone+failed))" -eq "$total" ] || { echo "Processed $((kept+newer+deleted+gone+failed)) of $total assets" >&2; exit 1; }
echo "Kept $kept assets from this build and $newer from newer builds; deleted $deleted older assets; $gone already gone; $failed failures"
[ "$failed" -eq 0 ] || { echo "::warning::prune: $failed deletions failed"; exit 1; }
+255
View File
@@ -0,0 +1,255 @@
name: "S3 digest and FIPS matrix"
# Runs the S3 suites in every digest mode with both volume servers and JWT
# signing on, so the sha256 digest and GODEBUG=fips140=only stay working:
# md5 GODEBUG=fips140=off, the default digest
# sha256 GODEBUG=fips140=on with the filer's -digest=sha256
# fips140only GODEBUG=fips140=only and WEED_FIPS_MODE=strict, built with
# GOFIPS140=v1.0.0
# test/s3/digest_matrix/start_cluster.sh starts each cell's cluster. The
# negative-config job checks what strict mode refuses at startup
# (test/s3/digest_matrix/negative_config.sh).
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/operation/**'
- 'weed/storage/**'
- 'weed/security/**'
- 'weed/util/**'
- 'weed/command/**'
- 'weed/pb/**'
- 'seaweed-volume/**'
- 'seaweed-common/**'
- 'test/s3/digest_matrix/**'
- 'test/s3/compatibility/**'
- 'test/s3/etag/**'
- 'test/s3/checksum/**'
- 'docker/compose/s3.json'
- 'docker/compose/s3tests.conf'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-digest-matrix.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/operation/**'
- 'weed/storage/**'
- 'weed/security/**'
- 'weed/util/**'
- 'weed/command/**'
- 'weed/pb/**'
- 'seaweed-volume/**'
- 'seaweed-common/**'
- 'test/s3/digest_matrix/**'
- 'test/s3/compatibility/**'
- 'test/s3/etag/**'
- 'test/s3/checksum/**'
- 'docker/compose/s3.json'
- 'docker/compose/s3tests.conf'
- 'go.mod'
- 'go.sum'
- '.github/workflows/s3-digest-matrix.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:
build:
name: Build weed (GOFIPS140) and weed-volume
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
- name: Fingerprint build toolchain
id: toolchain
run: echo "fingerprint=$(getconf GNU_LIBC_VERSION | tr ' ' '-')-rustc-$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- name: Cache cargo registry and target
if: runner.environment == 'github-hosted'
uses: actions/cache@v6
with:
path: |
~/.cargo/registry
~/.cargo/git
seaweed-volume/target
key: rust-${{ steps.toolchain.outputs.fingerprint }}-${{ hashFiles('seaweed-volume/Cargo.lock', 'seaweed-common/Cargo.lock') }}
restore-keys: |
rust-${{ steps.toolchain.outputs.fingerprint }}-
# GOFIPS140=v1.0.0 links the frozen Go Cryptographic Module, which the
# fips140only cells need; the other cells set GODEBUG to off or on.
- name: Build weed
run: |
cd weed
CGO_ENABLED=0 GOFIPS140=v1.0.0 go build -tags s3tests -buildvcs=false -o weed .
go version -m weed | grep GOFIPS140
- name: Build weed-volume
run: cd seaweed-volume && cargo build --release
- name: Package binaries
run: tar cf digest-matrix-binaries.tar weed/weed seaweed-volume/target/release/weed-volume
- uses: actions/upload-artifact@v7
with:
name: digest-matrix-binaries
if-no-files-found: error
retention-days: 1
path: digest-matrix-binaries.tar
negative-config:
name: Strict FIPS mode refusals
needs: build
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
- name: Restore binaries
run: |
tar xf digest-matrix-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
- name: Short keys refused
env:
WEED: ${{ github.workspace }}/weed/weed
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
WORK_DIR: /tmp/negative-config
run: bash test/s3/digest_matrix/negative_config.sh
- name: Upload logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: negative-config-logs
path: /tmp/negative-config/**/*.log
retention-days: 3
suites:
name: S3 suites (${{ matrix.digest }}, ${{ matrix.volume }} volume server)
needs: build
runs-on: ubuntu-24.04
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
digest: [ md5, sha256, fips140only ]
volume: [ go, rust ]
# s3_digest names the ETag digest for the Go suites. ceph_deselect
# drops ceph tests whose answer the mode changes on purpose:
# test_object_write_check_etag expects MD5("bar") as the ETag, and
# under fips140=only SSE-C is refused with 501 before its headers are
# compared, so the SSE-C conflict tests get 501 where they expect 400.
include:
- digest: md5
s3_digest: md5
- digest: sha256
s3_digest: sha256
ceph_deselect: --deselect s3tests/functional/test_s3.py::test_object_write_check_etag
- digest: fips140only
s3_digest: sha256
ceph_deselect: >-
--deselect s3tests/functional/test_s3.py::test_object_write_check_etag
--deselect s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_s3
--deselect s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_kms
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- uses: actions/setup-python@v7
with:
python-version: '3.10'
# The same s3-tests checkout and fixes as the "Ceph S3 tests" workflow.
- name: Clone s3-tests
run: |
git clone https://github.com/ceph/s3-tests.git
cd s3-tests
sudo apt-get update -qq
sudo apt-get install -y -qq libxml2-dev libxslt1-dev zlib1g-dev
python3 -m pip install -r requirements.txt
python3 -m pip install tox
python3 -m pip install -e .
cd ..
S3_TESTS_PATH=s3-tests python3 test/s3/compatibility/fix_s3_tests_bucket_conflicts.py
sed -i "s/assert prefixes == \['foo%2B1\/', 'foo\/', 'quux%20ab\/'\]/assert prefixes == \['foo\/', 'foo%2B1\/', 'quux%20ab\/'\]/" s3-tests/s3tests/functional/test_s3.py
sed -i "/# request PartNumber out of range/,+4{s/assert status == 400/assert status == 416/; s/assert error_code == 'InvalidPart'/assert error_code == 'InvalidPartNumber'/}" s3-tests/s3tests/functional/test_s3.py
- uses: actions/download-artifact@v8
with:
name: digest-matrix-binaries
- name: Restore binaries
run: |
tar xf digest-matrix-binaries.tar
chmod +x weed/weed seaweed-volume/target/release/weed-volume
- name: Start the cluster
env:
DIGEST_MODE: ${{ matrix.digest }}
VOLUME_SERVER: ${{ matrix.volume }}
WEED: ${{ github.workspace }}/weed/weed
WEED_VOLUME: ${{ github.workspace }}/seaweed-volume/target/release/weed-volume
WORK_DIR: /tmp/digest-matrix
S3_CONFIG: ${{ github.workspace }}/docker/compose/s3.json
run: bash test/s3/digest_matrix/start_cluster.sh
- name: Run the basic ceph s3-tests
working-directory: s3-tests
env:
S3TEST_CONF: ${{ github.workspace }}/docker/compose/s3tests.conf
run: |
mapfile -t tests < <(grep -v '^[[:space:]]*#' "$GITHUB_WORKSPACE/test/s3/compatibility/s3tests_basic.txt")
# shellcheck disable=SC2086 # the deselect list is separate arguments
tox -- "${tests[@]}" ${{ matrix.ceph_deselect }}
- name: Run the etag and checksum Go suites
env:
S3_ENDPOINT: http://127.0.0.1:8000
S3_DIGEST: ${{ matrix.s3_digest }}
S3_FIPS140_ONLY: ${{ matrix.digest == 'fips140only' && '1' || '0' }}
S3_ACCESS_KEY: some_access_key1
S3_SECRET_KEY: some_secret_key1
run: go test -count=1 -timeout 10m ./test/s3/etag/ ./test/s3/checksum/
- name: Stop the cluster
if: always()
run: xargs kill < /tmp/digest-matrix/pids 2>/dev/null || true
- name: Upload server logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: digest-matrix-logs-${{ matrix.digest }}-${{ matrix.volume }}
path: /tmp/digest-matrix/*.log
retention-days: 3
@@ -73,6 +73,20 @@ jobs:
echo "=== Running S3 Prefix Object Tests ==="
go test -v -timeout=180s -run TestS3PrefixObjectKeys ./...
- name: Run S3 GetPart Tests
timeout-minutes: 15
working-directory: test/s3/normal
run: |
set -x
go test -v -timeout=180s -run TestS3GetPart ./...
- name: Run S3 Bucket Default Storage Class Tests
timeout-minutes: 15
working-directory: test/s3/normal
run: |
set -x
go test -v -timeout=180s -run TestS3BucketDefaultStorageClass ./...
- name: Run IAM Integration Tests
timeout-minutes: 15
working-directory: test/s3/normal
+2 -2
View File
@@ -45,7 +45,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Set up Python ${{ matrix.python-version }}
@@ -153,7 +153,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Run Go unit tests
+69
View File
@@ -0,0 +1,69 @@
name: "S3 rclone fstests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/command/mini.go'
- 'go.mod'
- 'go.sum'
- 'test/s3/rclone_fstests/**'
- '.github/workflows/s3-rclone-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'weed/command/mini.go'
- 'go.mod'
- 'go.sum'
- 'test/s3/rclone_fstests/**'
- '.github/workflows/s3-rclone-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-rclone-fstests:
name: rclone fstests (S3 backend)
runs-on: ubuntu-24.04
timeout-minutes: 40
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: Test the result checker
working-directory: test/s3/rclone_fstests
run: python3 -m unittest -v test_check_results
- name: Run rclone fstests
working-directory: test/s3/rclone_fstests
run: make test
- name: Show server log on failure
if: failure()
working-directory: test/s3/rclone_fstests
run: tail -200 weed-test.log || true
- name: Upload results
if: always()
uses: actions/upload-artifact@v7
with:
name: s3-rclone-fstests-results
path: test/s3/rclone_fstests/results.jsonl
if-no-files-found: ignore
retention-days: 7
+3 -184
View File
@@ -197,190 +197,9 @@ jobs:
}
trap cleanup EXIT
tox -- \
s3tests/functional/test_s3.py::test_bucket_list_empty \
s3tests/functional/test_s3.py::test_bucket_list_distinct \
s3tests/functional/test_s3.py::test_bucket_list_many \
s3tests/functional/test_s3.py::test_bucket_listv2_many \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_basic \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_basic \
s3tests/functional/test_s3.py::test_bucket_listv2_encoding_basic \
s3tests/functional/test_s3.py::test_bucket_list_encoding_basic \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_prefix \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_prefix \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_prefix_ends_with_delimiter \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_prefix_ends_with_delimiter \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_alt \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_alt \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_prefix_underscore \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_prefix_underscore \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_percentage \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_percentage \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_whitespace \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_whitespace \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_dot \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_dot \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_unreadable \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_unreadable \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_empty \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_empty \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_none \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_none \
s3tests/functional/test_s3.py::test_bucket_listv2_delimiter_not_exist \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_not_exist \
s3tests/functional/test_s3.py::test_bucket_list_delimiter_not_skip_special \
s3tests/functional/test_s3.py::test_bucket_list_prefix_delimiter_basic \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_delimiter_basic \
s3tests/functional/test_s3.py::test_bucket_list_prefix_delimiter_alt \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_delimiter_alt \
s3tests/functional/test_s3.py::test_bucket_list_prefix_delimiter_prefix_not_exist \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_delimiter_prefix_not_exist \
s3tests/functional/test_s3.py::test_bucket_list_prefix_delimiter_delimiter_not_exist \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_delimiter_delimiter_not_exist \
s3tests/functional/test_s3.py::test_bucket_list_prefix_delimiter_prefix_delimiter_not_exist \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_delimiter_prefix_delimiter_not_exist \
s3tests/functional/test_s3.py::test_bucket_listv2_fetchowner_notempty \
s3tests/functional/test_s3.py::test_bucket_listv2_fetchowner_defaultempty \
s3tests/functional/test_s3.py::test_bucket_listv2_fetchowner_empty \
s3tests/functional/test_s3.py::test_bucket_list_prefix_basic \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_basic \
s3tests/functional/test_s3.py::test_bucket_list_prefix_alt \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_alt \
s3tests/functional/test_s3.py::test_bucket_list_prefix_empty \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_empty \
s3tests/functional/test_s3.py::test_bucket_list_prefix_none \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_none \
s3tests/functional/test_s3.py::test_bucket_list_prefix_not_exist \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_not_exist \
s3tests/functional/test_s3.py::test_bucket_list_prefix_unreadable \
s3tests/functional/test_s3.py::test_bucket_listv2_prefix_unreadable \
s3tests/functional/test_s3.py::test_bucket_list_maxkeys_one \
s3tests/functional/test_s3.py::test_bucket_listv2_maxkeys_one \
s3tests/functional/test_s3.py::test_bucket_list_maxkeys_zero \
s3tests/functional/test_s3.py::test_bucket_listv2_maxkeys_zero \
s3tests/functional/test_s3.py::test_bucket_list_maxkeys_none \
s3tests/functional/test_s3.py::test_bucket_listv2_maxkeys_none \
s3tests/functional/test_s3.py::test_bucket_list_unordered \
s3tests/functional/test_s3.py::test_bucket_listv2_unordered \
s3tests/functional/test_s3.py::test_bucket_list_maxkeys_invalid \
s3tests/functional/test_s3.py::test_bucket_list_marker_none \
s3tests/functional/test_s3.py::test_bucket_list_marker_empty \
s3tests/functional/test_s3.py::test_bucket_listv2_continuationtoken_empty \
s3tests/functional/test_s3.py::test_bucket_listv2_continuationtoken \
s3tests/functional/test_s3.py::test_bucket_listv2_both_continuationtoken_startafter \
s3tests/functional/test_s3.py::test_bucket_list_marker_unreadable \
s3tests/functional/test_s3.py::test_bucket_listv2_startafter_unreadable \
s3tests/functional/test_s3.py::test_bucket_list_marker_not_in_list \
s3tests/functional/test_s3.py::test_bucket_listv2_startafter_not_in_list \
s3tests/functional/test_s3.py::test_bucket_list_marker_after_list \
s3tests/functional/test_s3.py::test_bucket_listv2_startafter_after_list \
s3tests/functional/test_s3.py::test_bucket_list_return_data \
s3tests/functional/test_s3.py::test_bucket_list_objects_anonymous \
s3tests/functional/test_s3.py::test_bucket_listv2_objects_anonymous \
s3tests/functional/test_s3.py::test_bucket_list_objects_anonymous_fail \
s3tests/functional/test_s3.py::test_bucket_listv2_objects_anonymous_fail \
s3tests/functional/test_s3.py::test_bucket_list_long_name \
s3tests/functional/test_s3.py::test_bucket_list_special_prefix \
s3tests/functional/test_s3.py::test_bucket_delete_notexist \
s3tests/functional/test_s3.py::test_bucket_create_delete \
s3tests/functional/test_s3.py::test_object_read_not_exist \
s3tests/functional/test_s3.py::test_multi_object_delete \
s3tests/functional/test_s3.py::test_multi_objectv2_delete \
s3tests/functional/test_s3.py::test_object_head_zero_bytes \
s3tests/functional/test_s3.py::test_object_write_check_etag \
s3tests/functional/test_s3.py::test_object_write_cache_control \
s3tests/functional/test_s3.py::test_object_write_expires \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_s3 \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_c_kms \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_s3_kms \
s3tests/functional/test_s3.py::test_put_obj_enc_conflict_bad_enc_kms \
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
s3tests/functional/test_s3.py::test_object_write_file \
s3tests/functional/test_s3.py::test_post_object_invalid_date_format \
s3tests/functional/test_s3.py::test_post_object_no_key_specified \
s3tests/functional/test_s3.py::test_post_object_missing_signature \
s3tests/functional/test_s3.py::test_post_object_condition_is_case_sensitive \
s3tests/functional/test_s3.py::test_post_object_expires_is_case_sensitive \
s3tests/functional/test_s3.py::test_post_object_missing_expires_condition \
s3tests/functional/test_s3.py::test_post_object_missing_conditions_list \
s3tests/functional/test_s3.py::test_post_object_upload_size_limit_exceeded \
s3tests/functional/test_s3.py::test_post_object_missing_content_length_argument \
s3tests/functional/test_s3.py::test_post_object_invalid_content_length_argument \
s3tests/functional/test_s3.py::test_post_object_upload_size_below_minimum \
s3tests/functional/test_s3.py::test_post_object_empty_conditions \
s3tests/functional/test_s3.py::test_get_object_ifmatch_good \
s3tests/functional/test_s3.py::test_get_object_ifnonematch_good \
s3tests/functional/test_s3.py::test_get_object_ifmatch_failed \
s3tests/functional/test_s3.py::test_get_object_ifnonematch_failed \
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_good \
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_failed \
s3tests/functional/test_s3.py::test_get_object_ifunmodifiedsince_failed \
s3tests/functional/test_s3.py::test_get_checksum_object_attributes \
s3tests/functional/test_s3.py::test_bucket_head \
s3tests/functional/test_s3.py::test_bucket_head_notexist \
s3tests/functional/test_s3.py::test_object_raw_authenticated \
s3tests/functional/test_s3.py::test_object_raw_authenticated_bucket_acl \
s3tests/functional/test_s3.py::test_object_raw_authenticated_object_acl \
s3tests/functional/test_s3.py::test_object_raw_authenticated_object_gone \
s3tests/functional/test_s3.py::test_object_raw_get_x_amz_expires_out_range_zero \
s3tests/functional/test_s3.py::test_object_anon_put \
s3tests/functional/test_s3.py::test_object_put_authenticated \
s3tests/functional/test_s3.py::test_bucket_recreate_overwrite_acl \
s3tests/functional/test_s3.py::test_bucket_recreate_new_acl \
s3tests/functional/test_s3.py::test_buckets_create_then_list \
s3tests/functional/test_s3.py::test_buckets_list_ctime \
s3tests/functional/test_s3.py::test_list_buckets_invalid_auth \
s3tests/functional/test_s3.py::test_list_buckets_bad_auth \
s3tests/functional/test_s3.py::test_bucket_create_naming_good_contains_period \
s3tests/functional/test_s3.py::test_bucket_create_naming_good_contains_hyphen \
s3tests/functional/test_s3.py::test_bucket_list_special_prefix \
s3tests/functional/test_s3.py::test_object_copy_zero_size \
s3tests/functional/test_s3.py::test_object_copy_same_bucket \
s3tests/functional/test_s3.py::test_object_copy_to_itself \
s3tests/functional/test_s3.py::test_object_copy_diff_bucket \
s3tests/functional/test_s3.py::test_object_copy_canned_acl \
s3tests/functional/test_s3.py::test_object_copy_bucket_not_found \
s3tests/functional/test_s3.py::test_object_copy_key_not_found \
s3tests/functional/test_s3.py::test_multipart_copy_small \
s3tests/functional/test_s3.py::test_multipart_copy_without_range \
s3tests/functional/test_s3.py::test_multipart_copy_special_names \
s3tests/functional/test_s3.py::test_multipart_copy_multiple_sizes \
s3tests/functional/test_s3.py::test_multipart_get_part \
s3tests/functional/test_s3.py::test_multipart_upload \
s3tests/functional/test_s3.py::test_multipart_upload_empty \
s3tests/functional/test_s3.py::test_multipart_upload_multiple_sizes \
s3tests/functional/test_s3.py::test_multipart_upload_contents \
s3tests/functional/test_s3.py::test_multipart_upload_overwrite_existing_object \
s3tests/functional/test_s3.py::test_multipart_upload_size_too_small \
s3tests/functional/test_s3.py::test_multipart_resend_first_finishes_last \
s3tests/functional/test_s3.py::test_multipart_upload_resend_part \
s3tests/functional/test_s3.py::test_multipart_upload_missing_part \
s3tests/functional/test_s3.py::test_multipart_upload_incorrect_etag \
s3tests/functional/test_s3.py::test_abort_multipart_upload \
s3tests/functional/test_s3.py::test_list_multipart_upload \
s3tests/functional/test_s3.py::test_atomic_read_1mb \
s3tests/functional/test_s3.py::test_atomic_read_4mb \
s3tests/functional/test_s3.py::test_atomic_read_8mb \
s3tests/functional/test_s3.py::test_atomic_write_1mb \
s3tests/functional/test_s3.py::test_atomic_write_4mb \
s3tests/functional/test_s3.py::test_atomic_write_8mb \
s3tests/functional/test_s3.py::test_atomic_dual_write_1mb \
s3tests/functional/test_s3.py::test_atomic_dual_write_4mb \
s3tests/functional/test_s3.py::test_atomic_dual_write_8mb \
s3tests/functional/test_s3.py::test_atomic_multipart_upload_write \
s3tests/functional/test_s3.py::test_ranged_request_response_code \
s3tests/functional/test_s3.py::test_ranged_big_request_response_code \
s3tests/functional/test_s3.py::test_ranged_request_skip_leading_bytes_response_code \
s3tests/functional/test_s3.py::test_ranged_request_return_trailing_bytes_response_code \
s3tests/functional/test_s3.py::test_copy_object_ifmatch_good \
s3tests/functional/test_s3.py::test_copy_object_ifnonematch_failed \
s3tests/functional/test_s3.py::test_copy_object_ifmatch_failed \
s3tests/functional/test_s3.py::test_copy_object_ifnonematch_good \
s3tests/functional/test_s3.py::test_lifecycle_set \
s3tests/functional/test_s3.py::test_lifecycle_get \
s3tests/functional/test_s3.py::test_lifecycle_set_filter
# test/s3/compatibility/s3tests_basic.txt is shared with s3-digest-matrix.yml.
mapfile -t basic_tests < <(grep -v '^[[:space:]]*#' "$GITHUB_WORKSPACE/test/s3/compatibility/s3tests_basic.txt")
tox -- "${basic_tests[@]}"
# The expiration tests race the lifecycle worker's meta-log replay;
# under the suite's write flood a shard can trail an object's PUT
@@ -40,7 +40,7 @@ jobs:
- uses: actions/setup-go@v7
with:
go-version: ^1.26
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Build SeaweedFS
+4 -4
View File
@@ -31,16 +31,16 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Build weed binary
run: |
cd weed && go build -o weed .
@@ -31,16 +31,16 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Set up Go 1.x
uses: actions/setup-go@v7
with:
cache: ${{ runner.environment == 'github-hosted' }}
go-version: ^1.26
go-version-file: 'go.mod'
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- name: Build weed binary
run: |
cd weed && go build -o weed .
+3
View File
@@ -151,3 +151,6 @@ __pycache__/
/test/s3vectors/weed-worker
/test/s3vectors/weed-volume
.pytest_cache/
# Graphify code graph (generated by .github/workflows/graph.yml)
graphify-out/
+11 -1
View File
@@ -36,6 +36,7 @@ Table of Contents
* [Docker Compose](#docker-compose)
* [Kubernetes with Helm](#kubernetes-with-helm)
* [Build from source](#build-from-source)
* [Development builds](#development-builds)
* [Scale out](#scale-out)
* [Why SeaweedFS](#why-seaweedfs)
* [Fast](#fast)
@@ -87,7 +88,7 @@ AWS_ACCESS_KEY_ID=admin AWS_SECRET_ACCESS_KEY=secret \
The same process also runs the master, a volume server, the filer, WebDAV, the Iceberg REST catalog, and the Admin UI. Add `S3_TABLE_BUCKET=warehouse` to also create an Iceberg table bucket, or `warehouse:LANCE` for a Lance one. Drop the AWS keys to run without authentication for development.
Without Admin authentication or mTLS, `weed mini` binds the Admin UI/API and its worker gRPC control plane to loopback rather than `-ip.bind`. Set `WEED_ADMIN_PASSWORD` or configure `https.admin` mTLS to keep the network bind. Remote workers must opt in with `-admin.worker.ip=<address>` and should configure `grpc.admin` mTLS. `-admin.allowInsecureBind` restores the legacy unauthenticated network bind and should only be used on an isolated network.
`weed mini` binds the Admin UI/API and WebDAV to `-ip.bind` like its other components, even without authentication, so use it on a trusted network or set `WEED_ADMIN_PASSWORD` or `https.admin` mTLS. Pass `-admin.allowInsecureBind=false` or `-webdav.allowInsecureBind=false` to keep an unauthenticated Admin or WebDAV on loopback. The Admin worker gRPC control plane stays on loopback; remote workers must opt in with `-admin.worker.ip=<address>` and should configure `grpc.admin` mTLS.
> macOS: if the binary is quarantined, run `xattr -d com.apple.quarantine ./weed` first.
@@ -175,6 +176,15 @@ cd seaweedfs/weed && make install
`weed` lands in `$GOPATH/bin`. [Getting Started][GettingStarted] covers running master, volume, filer, and S3 as separate processes.
## Development builds ##
Each dev build workflow publishes its latest successful build of `master`:
- **Binaries**: the [`dev` release](https://github.com/seaweedfs/seaweedfs/releases/tag/dev) has Linux amd64, Windows amd64, and macOS amd64/arm64 archives named `weed-<yyyymmdd-HHMM>-<linux|windows|darwin>-<arch>.tar.gz` (`.zip` on Windows) and `weed-large-disk-<yyyymmdd-HHMM>-<linux|windows|darwin>-<arch>`, each with an `.md5` checksum. The Rust volume server is published there too as `weed-volume-*` for Linux amd64 (glibc) and macOS amd64/arm64. The Go archives contain `weed-normal-disk` or `weed-large-disk` (`.exe` on Windows) rather than `weed`, and the Rust archives contain `weed-volume-normal` or `weed-volume-large-disk` rather than `weed-volume`, so rename or symlink the one you want. The `.md5` files are published for the Go archives only.
- **Containers**: `docker pull chrislusf/seaweedfs:dev` or `ghcr.io/chrislusf/seaweedfs:dev`, built for `linux/amd64` and `linux/arm64`. The [dev compose file](docker/seaweedfs-dev-compose.yml) runs the Docker Hub image as master, volume, filer, S3, WebDAV, and admin.
The timestamp in a binary name is the UTC start time of the run that built it. The Go binaries, the Rust volume server, and the `:dev` image come from three separate path-filtered workflows, so they can carry different timestamps and lag `master` by hours, or much longer when their paths were not touched. The release can list more than one timestamp for a while, for example after a failed or retried run; use the newest one for your platform. The `dev` release is marked pre-release, so it does not appear under [releases/latest](https://github.com/seaweedfs/seaweedfs/releases/latest); these builds come from `master`, can break at any commit, and are not recommended for production.
## Scale out ##
Capacity is a volume server. Start one on any machine with disk and point it at the master:
+15 -2
View File
@@ -278,11 +278,24 @@ automatic vacuum or another request is running does nothing and gets
### Delete a collection
```bash
curl "http://localhost:9333/col/delete?collection=benchmark"
curl -X DELETE "http://localhost:9333/col/delete?collection=benchmark"
```
Deletes all volumes of the collection, including erasure-coded shards.
`204 No Content` on success.
`204 No Content` on success. Only the `DELETE` method is accepted; any other
method gets `405 Method Not Allowed`.
The `collection` parameter is required: a request without it, or with an
empty value, gets `400 Bad Request`. To delete the default (empty-named)
collection, name it explicitly with `collection=_default` or
`collection=_default_`, the keywords `weed shell collection.delete` accepts.
If a collection is literally named a keyword, that name deletes it, and when
it exists next to the default collection the request gets
`400 Bad Request`; use the other keyword for the default collection. If both
keyword names are literal collections next to the default collection, both
keywords get `400 Bad Request`; delete the default collection with
`weed shell` `collection.delete -collection _default -apply`, where the
keywords always mean the default collection.
### Health
+4 -1
View File
@@ -169,7 +169,10 @@ func Run(args []string) int {
}
func runWithOptions(opts *Options) bool {
util.LoadConfiguration("security", false)
if err := util.LoadSecurityConfigurationOrError(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return false
}
// Validate options.
if opts.MasterAddr == "" {
+6
View File
@@ -13,6 +13,7 @@ import (
"github.com/peterh/liner"
"github.com/seaweedfs/seaweedfs/weed/query/engine"
"github.com/seaweedfs/seaweedfs/weed/util"
flag "github.com/seaweedfs/seaweedfs/weed/util/fla9"
"github.com/seaweedfs/seaweedfs/weed/util/grace"
"github.com/seaweedfs/seaweedfs/weed/util/sqlutil"
@@ -106,6 +107,11 @@ func Run(args []string) int {
}
func runWithOptions(opts *Options) bool {
if err := util.LoadSecurityConfigurationOrError(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return false
}
// Initialize SQL engine with master address for service discovery.
sqlEngine := engine.NewSQLEngine(opts.Master)
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.26 AS builder
FROM golang:1.27 AS builder
RUN apt-get update && \
apt-get install -y build-essential wget ca-certificates && \
+3 -3
View File
@@ -1,6 +1,6 @@
# Pin the builder to the host arch and cross-compile the (CGO-free) Go binary,
# so arm64/arm/386 targets skip QEMU emulation of the whole compile.
FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS builder
FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS builder
RUN apk add git g++ fuse
RUN mkdir -p /go/src/github.com/seaweedfs/
ARG BRANCH=${BRANCH:-master}
@@ -93,8 +93,8 @@ RUN mkdir -p /etc/seaweedfs
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/filer.toml /etc/seaweedfs/filer.toml
COPY --from=builder /go/src/github.com/seaweedfs/seaweedfs/docker/entrypoint.sh /entrypoint.sh
# FIPS 140-3 mode is ON by default (Go 1.24+)
# To disable: docker run -e GODEBUG=fips140=off ...
# FIPS 140-3 mode is on by default for every process (entrypoint.sh)
# To disable: docker run -e WEED_FIPS_MODE=off ...
# Install dependencies and create non-root user
RUN apk upgrade --no-cache && \
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.26 AS builder
FROM golang:1.27 AS builder
RUN apt-get update
RUN apt-get install -y build-essential libsnappy-dev zlib1g-dev libbz2-dev libgflags-dev liblz4-dev libzstd-dev
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.26 AS builder
FROM golang:1.27 AS builder
RUN apt-get update
RUN apt-get install -y build-essential libsnappy-dev zlib1g-dev libbz2-dev libgflags-dev liblz4-dev libzstd-dev
+3 -1
View File
@@ -21,7 +21,9 @@ docker compose -f seaweedfs-compose.yml -p seaweedfs up
```
## Try latest tip
## Try the latest development image
The compose file below uses `chrislusf/seaweedfs:dev`, built from `master`. It is a development image, not a stable release, and can lag `master` by hours or more; the `org.opencontainers.image.revision` label records the commit it was built from, and pinning by digest keeps that exact build. See [Development builds](../README.md#development-builds) for the `dev` binaries and image details.
```bash
+44 -4
View File
@@ -1,9 +1,5 @@
#!/bin/sh
# Enable FIPS 140-3 mode by default (Go 1.24+)
# To disable: docker run -e GODEBUG=fips140=off ...
export GODEBUG="${GODEBUG:+$GODEBUG,}fips140=on"
# Fix permissions for mounted volumes
# If /data is mounted from host, it might have different ownership
# Fix this by ensuring seaweed user owns the directory
@@ -32,10 +28,54 @@ if [ "$(id -u)" = "0" ]; then
fi
fi
# A restrictive Docker daemon umask can leave these 0600, and the resolver
# then falls back to a nameserver on localhost once privileges are dropped.
for f in /etc/resolv.conf /etc/hosts; do
if [ -f "$f" ] && ! su-exec seaweed test -r "$f"; then
chmod a+r "$f" 2>/dev/null
fi
done
# Use su-exec to drop privileges and run as seaweed user
exec su-exec seaweed "$0" "$@"
fi
# FIPS 140-3 mode is on by default, for the Go processes and the Rust
# binaries alike. To pick another mode: docker run -e WEED_FIPS_MODE=off (or
# strict). A fips.mode in security.toml alone cannot change it, since Go
# processes would still get this mode's fips140 and refuse to start.
# WEED_FIPS_MODE_DEFAULT is the mode when nothing else sets one; set it empty
# to leave every process in its own default (fips140=off for Go, off for Rust).
# A fips140 the caller puts in GODEBUG still picks the mode, for the Rust
# binaries as well, unless WEED_FIPS_MODE is set, but is deprecated and warns;
# a Go process refuses to start when its fips140 differs from WEED_FIPS_MODE or
# fips.mode.
# Transparent huge pages are a host-wide setting this image cannot change; to
# turn them off for this process only, append GODEBUG=disablethp=1.
export WEED_FIPS_MODE_DEFAULT="${WEED_FIPS_MODE_DEFAULT-on}"
godebug_fips140="$(printf '%s\n' "$GODEBUG" | tr ',' '\n' | sed -n 's/^fips140=/=/p' | tail -n 1)"
case "$godebug_fips140" in
=off | =) WEED_FIPS_MODE_DEFAULT=off ;;
=on | =debug) WEED_FIPS_MODE_DEFAULT=on ;;
=only) WEED_FIPS_MODE_DEFAULT=strict ;;
esac
if [ -n "$godebug_fips140" ] && [ -z "$WEED_FIPS_MODE" ]; then
echo "Warning: choosing the FIPS mode with GODEBUG=fips140 is deprecated; set WEED_FIPS_MODE=off, on or strict, which also covers the Rust binaries when they start without this entrypoint." >&2
fi
case "${WEED_FIPS_MODE:-$WEED_FIPS_MODE_DEFAULT}" in
off) fips140=off ;;
on) fips140=on ;;
strict) fips140=only ;;
*) fips140= ;;
esac
export GODEBUG="${fips140:+fips140=$fips140}${fips140:+${GODEBUG:+,}}${GODEBUG}"
for f in /etc/resolv.conf /etc/hosts; do
if [ -f "$f" ] && [ ! -r "$f" ]; then
echo "Warning: $f is not readable by uid $(id -u), so host name lookups may fail. Make it world-readable (0644)." >&2
fi
done
isArgPassed() {
# Match both `-flag` and `--flag` (and their `=value` forms): the Go fla9
# library accepts both, and users may pick either form on the CLI.
+9 -7
View File
@@ -30,10 +30,12 @@ Override `SEAWEEDFS_IMAGE` to test a newer image. With metrics-enabled engines,
append `--metrics-port=9329 --metrics-ip=0.0.0.0` to the vector command and scrape
`vector:9329/metrics` inside the Compose network.
A native development setup can use `weed mini -vector -vectorBucket=embeddings`
with `weed-vector` beside `weed` or on PATH. `-vector.binary` selects an explicit
binary, and `-vector.metricsPort=9329` enables HTTP readiness and metrics on a
compatible engine. The child inherits the cluster's configuration directory and
stops with mini. Run `weed-worker` separately for ANN maintenance. `weed shell`
provides `s3vectors -operation <Operation> -file request.json` for the same API
operations using trusted cluster credentials.
A native development setup can use `weed mini -vectorBucket=embeddings`. Mini
starts `weed-vector` and the `weed-worker` maintenance worker when it finds them
beside `weed` or on PATH, and logs and continues without one it cannot find.
`-vector.binary` selects an explicit engine binary, and `weed-worker` is also
looked up beside it. `-vector=false` leaves both out, and
`-vector.metricsPort=9329` enables HTTP readiness and metrics on a compatible
engine. The children inherit the cluster's configuration directory and stop with
mini. `weed shell` provides `s3vectors -operation <Operation> -file
request.json` for the same API operations using trusted cluster credentials.
+1 -1
View File
@@ -1,7 +1,7 @@
services:
seaweedfs:
image: ${SEAWEEDFS_IMAGE:-chrislusf/seaweedfs:4.53}
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE
command: mini -dir=/data -ip=seaweedfs -ip.bind=0.0.0.0 -admin.password=vector-demo -admin.worker.ip=0.0.0.0 -tableBucket=embeddings:LANCE -vector=false
environment: &environment
WEED_JWT_FILER_SIGNING_KEY: vector-demo-cluster-key
AWS_ACCESS_KEY_ID: vector-demo
+157
View File
@@ -0,0 +1,157 @@
# Yandex Disk as a remote storage
SeaweedFS can mount a Yandex Disk and mirror buckets to it, the same way it uses
S3, Google Cloud Storage, or Azure Blob Storage. The storage type is `yandex`.
Yandex Disk has no buckets: a **top-level folder under `yandex.root` plays the
bucket**, and the folder holds the objects. A file's modification time and
content encoding, which the Disk API cannot store natively, travel as custom
resource properties (`seaweedfs_modified`, `seaweedfs_content_encoding`). The
client also reads `rclone_modified`, so objects uploaded by rclone keep their
mtime.
## Limitations to know first
- The public Disk API has **no multipart upload**: an object is one PUT. Very
large objects are limited by the plan's maximum file size (see `GET /` quota)
and need a long HTTP timeout.
- Writes are expensive: one upload is an upload-link request, the PUT, a
metadata PATCH, and a stat.
- Yandex applies rate limits; the client retries 423, 429, 5xx and 509 with a
backoff, the sync retries a failed upload from a fresh reader.
- The Disk API lists one folder per request, so `remote.cache` and
`remote.copy.local`, which walk a whole tree, cost one request per folder.
- S3 keys that contain characters Yandex rejects in a path fail; there is no
key-encoding layer. S3 keys are not folders: a prefix that only appears as
part of object names is created on demand.
- This is a consumer product: it fits backups and small mirrors, not millions
of objects or a high request rate.
## 1. Register an OAuth app
1. Open <https://oauth.yandex.ru/client/new> and create an app.
2. Pick the **Web services** platform.
3. Set the redirect URI to `https://oauth.yandex.ru/verification_code`. That
page shows the authorization code (or the token) for the operator to copy,
so no browser is needed on the server.
4. Grant the app the permissions you need:
- `cloud_api:disk.write` — write anywhere on the disk (needed for buckets
and for `-yandex.root` outside the app folder),
- `cloud_api:disk.read` — read the disk,
- `cloud_api:disk.info` — read the quota,
- `cloud_api:disk.app_folder` — app folder only; then the configuration
needs `-yandex.app_folder=true`.
5. Copy the **ClientID** (and the **Client secret** if you want a refreshable
token).
A Yandex Mail account is required for a working Disk subscription; a token
issued for an account without one fails with
`403 DiskUnsupportedUserAccountTypeError`.
## 2. Get a token
### Refreshable token (recommended)
```bash
# 1. print the authorization url and keep the app credentials
weed shell -master=... <<< "remote.configure -name=disk -type=yandex \
-yandex.client_id=<client id> -yandex.client_secret=<client secret> -yandex.oauth_url"
# 2. open the printed url, allow the app, copy the code from the page
# 3. store the token
weed shell -master=... <<< "remote.configure -name=disk -yandex.code=<code>"
```
The stored value is a token JSON document
(`{"access_token","refresh_token","token_type","expiry"}`, the same shape
rclone stores), so a token can also be copied from an existing rclone
configuration.
### Debug token (one year, no refresh)
Open
`https://oauth.yandex.ru/authorize?response_type=token&client_id=<client id>`
in a browser, allow the app, and copy the token. Then:
```bash
weed shell -master=... <<< "remote.configure -name=disk -type=yandex -yandex.token=<token>"
```
To try the backend without registering an app, the Disk API polygon
(<https://yandex.ru/dev/disk/poligon/>) issues a one-year token for its own
OAuth app: sign in, click "Получить OAuth-токен", allow the access, and copy
`access_token` from the address the page lands on. That token cannot be
refreshed; use the code flow above for anything long-lived.
## 3. Configure
```bash
remote.configure -name=disk -type=yandex -yandex.token=<token> [-yandex.root=/seaweedfs]
```
| flag | meaning |
| --- | --- |
| `-yandex.token` | token JSON or a bare access token |
| `-yandex.client_id`, `-yandex.client_secret` | OAuth app credentials, needed to refresh the token and for `-yandex.code` |
| `-yandex.root` | folder that holds the buckets, default `/` |
| `-yandex.app_folder` | the token only reaches the app folder: paths are addressed under `app:` |
| `-yandex.trash` | move deleted files to the trash instead of deleting them permanently (the trash keeps occupying quota) |
| `-yandex.endpoint` | override the API endpoint, e.g. for a proxy (default `https://cloud-api.yandex.net/v1/disk`); it must be `https`, plain `http` is accepted on a loopback host only, since every request carries the OAuth token |
A dedicated root (`-yandex.root=/seaweedfs`) is recommended: with the default
`/`, `remote.mount.buckets` treats every top-level folder of the disk,
personal folders included, as a bucket.
## 4. Mount or mirror
```bash
# mount one folder as a local directory
remote.mount -dir=/buckets/photos -remote=disk/photos
# mount every folder under the root as a bucket and pull its metadata
remote.mount.buckets -remote=disk -apply
# pull remote changes into the local metadata later
remote.meta.sync -dir=/buckets/photos
# mirror local buckets to the disk
weed filer.remote.gateway -filer=<filer host>:<filer port> -createBucketAt=disk
```
`weed filer.remote.sync -filer=... -dir=/buckets` uploads changes made under
the mounted directories.
Deleting a local bucket deletes its remote folder only when that folder is
empty, the same rule S3 and GCS apply to a bucket: a Disk API delete is
recursive, and the folder may hold files SeaweedFS never saw.
## Token lifetime and refresh
An access token and its refresh token both live about a year. The client
refreshes the access token when it expires or when the API answers 401, and
uses the new refresh token Yandex returns. The refreshed token is kept in
memory only: a client cannot write the configuration back to the filer, so
every restart, and every other process using the same configuration, starts
again from the stored refresh token. Yandex does not document whether that
token stays valid once a newer one has been issued, so after a refresh a
restart can fail with `invalid_grant`. Then, or when the stored token nears
the end of its year, issue a new one with `-yandex.oauth_url` and
`-yandex.code` above. Yandex recommends refreshing a long-lived token every
three months.
## Not covered
- `weed filer.backup` and the legacy `weed/replication/sink` sinks have no
Yandex backend; use `filer.remote.sync` / `filer.remote.gateway`.
- The Rust volume server (`seaweed-volume`) supports only S3-compatible remote
storage; a Yandex remote cannot back a tiered volume there.
## Troubleshooting
- `403 DiskUnsupportedUserAccountTypeError` — the account has no Yandex Mail /
Disk subscription.
- `401` on every request — the token is wrong or revoked; reissue it.
- `invalid_grant` while refreshing — the refresh token expired or was rotated
elsewhere; reissue it.
- `500` right after an upload — Yandex finalizes an upload asynchronously; the
client retries the stat, and a retry of the whole upload succeeds.
+255 -259
View File
@@ -1,93 +1,120 @@
module github.com/seaweedfs/seaweedfs
go 1.26.6
go 1.27.4
require (
cloud.google.com/go v0.123.0 // indirect
cloud.google.com/go/kms v1.36.1
cloud.google.com/go/pubsub v1.51.1
cloud.google.com/go/storage v1.69.0
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/keyvault/azkeys v0.10.0
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.3
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Jille/raft-grpc-transport v1.6.1
github.com/KimMachineGun/automemlimit v1.0.2
github.com/Shopify/sarama v1.38.1
github.com/ThreeDotsLabs/watermill v1.5.3
github.com/a-h/templ v0.3.1100
github.com/apache/arrow-go/v18 v18.9.0
github.com/apache/cassandra-gocql-driver/v2 v2.1.2
github.com/apache/iceberg-go v0.7.0
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/aws/aws-sdk-go v1.55.8
github.com/beorn7/perks v1.0.1 // indirect
github.com/aws/aws-sdk-go-v2 v1.49.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.117.1
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6
github.com/aws/smithy-go v1.28.11
github.com/bwmarrin/snowflake v0.3.0
github.com/cenkalti/backoff/v4 v4.3.0
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.7.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/cespare/xxhash/v2 v2.3.0
github.com/cognusion/imaging v1.0.4
github.com/dustin/go-humanize v1.1.0
github.com/eapache/go-resiliency v1.6.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
github.com/eapache/queue v1.1.0 // indirect
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a
github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c // indirect
github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect
github.com/facebookgo/stats v0.0.0-20151006221625-1b76add642e4
github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/fluent/fluent-logger-golang v1.10.1
github.com/getsentry/sentry-go v0.50.0
github.com/go-ldap/ldap/v3 v3.4.14
github.com/go-redsync/redsync/v4 v4.18.0
github.com/go-sql-driver/mysql v1.10.1
github.com/go-zookeeper/zk v1.0.4 // indirect
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/golang/protobuf v1.5.4
github.com/golang/snappy v1.0.0
github.com/google/btree v1.1.3
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
github.com/google/uuid v1.6.0
github.com/google/wire v0.7.0 // indirect
github.com/googleapis/gax-go/v2 v2.27.0 // indirect
github.com/gorilla/mux v1.8.1
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/jackc/pgx/v5 v5.10.0
github.com/jcmturner/gofork v1.7.6 // indirect
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
github.com/gorilla/sessions v1.4.0
github.com/hashicorp/go-metrics v0.7.0
github.com/hashicorp/golang-lru/v2 v2.0.7
github.com/hashicorp/raft v1.8.0
github.com/hashicorp/raft-boltdb/v2 v2.4.2
github.com/hashicorp/vault/api v1.23.0
github.com/jackc/pgx/v5 v5.13.0
github.com/jhump/protoreflect v1.19.0
github.com/jinzhu/copier v0.4.0
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/json-iterator/go v1.1.12
github.com/k0kubun/pp v3.0.1+incompatible
github.com/karlseguin/ccache/v2 v2.0.8
github.com/klauspost/compress v1.20.3
github.com/klauspost/compress v1.20.5
github.com/klauspost/reedsolomon v1.14.2
github.com/kurin/blazer v0.5.3
github.com/linkedin/goavro/v2 v2.15.0
github.com/linxGnu/grocksdb v1.11.1
github.com/mailru/easyjson v0.9.2 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/minio/crc64nvme v1.1.1
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
github.com/olivere/elastic/v7 v7.0.32
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.33.0
github.com/peterh/liner v1.2.3
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pierrec/lz4/v4 v4.1.33
github.com/pkg/sftp v1.13.12
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10
github.com/posener/complete v1.2.3
github.com/pquerna/cachecontrol v0.2.0
github.com/prometheus/client_golang v1.24.1
github.com/prometheus/client_model v0.6.3
github.com/prometheus/common v0.71.0 // indirect
github.com/prometheus/procfs v0.23.0
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rabbitmq/amqp091-go v1.17.0
github.com/rclone/rclone v1.75.1
github.com/rdleal/intervalst v1.5.0
github.com/redis/go-redis/v9 v9.23.0
github.com/schollz/progressbar/v3 v3.19.1
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564
github.com/seaweedfs/go-fuse/v2 v2.9.5
github.com/seaweedfs/goexif v1.0.3
github.com/seaweedfs/raft v1.2.4
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/shirou/gopsutil/v4 v4.26.10
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.12.1
github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203
github.com/syndtr/goleveldb v1.0.1-0.20190318030020-c3a204f8e965
github.com/tarantool/go-option v1.1.0
github.com/tarantool/go-tarantool/v3 v3.0.2
github.com/testcontainers/testcontainers-go v0.45.0
github.com/tidwall/gjson v1.20.0
github.com/tidwall/match v1.2.0
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tikv/client-go/v2 v2.0.7
github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365
github.com/twmb/avro v1.9.0
github.com/twpayne/go-geom v1.6.1
github.com/tylertreat/BoomFilters v0.0.0-20210315201527-1a82519a3e43
github.com/valyala/bytebufferpool v1.0.0
github.com/viant/ptrie v1.0.1
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/winfsp/cgofuse v1.6.1-0.20260126094232-f2c4fccdb286
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
github.com/xeipuuv/gojsonschema v1.2.0
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3
github.com/ydb-platform/ydb-go-sdk/v3 v3.157.1
go.etcd.io/etcd/api/v3 v3.7.3
go.etcd.io/etcd/client/pkg/v3 v3.7.4
go.etcd.io/etcd/client/v3 v3.7.3
go.mongodb.org/mongo-driver v1.17.9
go.opencensus.io v0.24.0 // indirect
go.mongodb.org/mongo-driver v1.17.10
go.uber.org/atomic v1.12.0
go.yaml.in/yaml/v3 v3.0.6
gocloud.dev v0.49.0
gocloud.dev/pubsub/natspubsub v0.49.0
gocloud.dev/pubsub/rabbitpubsub v0.47.0
@@ -95,214 +122,40 @@ require (
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.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-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
modernc.org/b v1.0.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
modernc.org/sqlite v1.60.1
)
require (
cloud.google.com/go/kms v1.36.1
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/Jille/raft-grpc-transport v1.6.1
github.com/ThreeDotsLabs/watermill v1.5.3
github.com/a-h/templ v0.3.1100
github.com/apache/arrow-go/v18 v18.8.0
github.com/apache/cassandra-gocql-driver/v2 v2.1.2
github.com/apache/iceberg-go v0.7.0
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
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
github.com/getsentry/sentry-go v0.50.0
github.com/go-ldap/ldap/v3 v3.4.14
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/flatbuffers/go v0.0.0-20230108230133-3b8644d32c50
github.com/hashicorp/go-metrics v0.7.0
github.com/hashicorp/golang-lru/v2 v2.0.7
github.com/hashicorp/raft v1.8.0
github.com/hashicorp/raft-boltdb/v2 v2.4.2
github.com/hashicorp/vault/api v1.23.0
github.com/jhump/protoreflect v1.18.1
github.com/linkedin/goavro/v2 v2.15.0
github.com/minio/crc64nvme v1.1.1
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/parquet-go/parquet-go v0.32.0
github.com/pkg/sftp v1.13.12
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
github.com/schollz/progressbar/v3 v3.19.1
github.com/seaweedfs/go-fuse/v2 v2.9.4
github.com/shirou/gopsutil/v4 v4.26.10
github.com/tarantool/go-option v1.1.0
github.com/tarantool/go-tarantool/v3 v3.0.2
github.com/testcontainers/testcontainers-go v0.45.0
github.com/tikv/client-go/v2 v2.0.7
github.com/twmb/avro v1.9.0
github.com/xeipuuv/gojsonschema v1.2.0
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3
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/oauth2 v0.38.0
golang.org/x/sync v0.25.0
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0
golang.org/x/time v0.16.0
golang.org/x/tools/godoc v0.1.0-deprecated
google.golang.org/api v0.310.0
google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b
google.golang.org/grpc v1.86.0-dev.0.20261027044109-d619b5d02089
google.golang.org/grpc/security/advancedtls v1.0.0
)
require github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
require (
cloud.google.com/go/longrunning v1.3.0 // indirect
cloud.google.com/go/pubsub/v2 v2.7.0 // indirect
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect
github.com/FilenCloudDienste/filen-sdk-go v0.0.39 // indirect
github.com/ProtonMail/gopenpgp/v3 v3.4.1 // indirect
github.com/RoaringBitmap/roaring/v2 v2.26.0 // indirect
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 // indirect
github.com/adrg/xdg v0.5.3 // indirect
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.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
github.com/bits-and-blooms/bitset v1.24.4 // indirect
github.com/blevesearch/snowballstem v0.9.0 // indirect
github.com/boombuler/barcode v1.1.0 // indirect
github.com/buger/jsonparser v1.2.0 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/cockroachdb/apd/v3 v3.2.1 // indirect
github.com/cockroachdb/errors v1.14.0 // indirect
github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 // indirect
github.com/cockroachdb/redact v1.1.5 // indirect
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v1.0.0-rc.4 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/dave/dst v0.27.2 // indirect
github.com/diskfs/go-diskfs v1.9.4 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.8.2 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dromara/dongle v1.0.1 // indirect
github.com/geoarrow/geoarrow-go v0.0.0-20260403143023-f54751c3e3a1 // indirect
github.com/gin-gonic/gin v1.11.0 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
github.com/go-git/go-billy/v5 v5.9.0 // indirect
github.com/goccy/go-yaml v1.18.0 // indirect
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/gopherjs/gopherjs v1.17.2 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
github.com/internxt/rclone-adapter v0.0.0-20260708165336-dd6561bacfa2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jaegertracing/jaeger v1.47.0 // indirect
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lib/pq v1.12.3 // indirect
github.com/lithammer/shortuuid/v3 v3.0.7 // indirect
github.com/lpar/calendar v0.2.0 // indirect
github.com/magiconair/properties v1.18.12 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.3.3 // indirect
github.com/moby/moby/api v1.56.1 // indirect
github.com/moby/moby/client v0.6.2 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.1 // indirect
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.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
github.com/parquet-go/bitpack v1.0.0 // indirect
github.com/parquet-go/jsonlite v1.0.0 // indirect
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
github.com/pierrre/geohash v1.0.0 // indirect
github.com/pquerna/otp v1.5.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/rclone/Proton-API-Bridge v1.0.5 // indirect
github.com/rclone/go-proton-api v1.0.4 // indirect
github.com/rogpeppe/go-internal v1.15.0 // indirect
github.com/ryanuber/go-glob v1.0.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/smarty/assertions v1.15.0 // indirect
github.com/sony/gobreaker/v2 v2.4.0 // indirect
github.com/stretchr/objx v0.5.3 // indirect
github.com/substrait-io/substrait v0.87.0 // indirect
github.com/substrait-io/substrait-go/v8 v8.1.1 // indirect
github.com/substrait-io/substrait-protobuf/go v0.85.0 // indirect
github.com/twpayne/go-geom v1.6.1 // indirect
github.com/twpayne/go-kml/v3 v3.2.1 // indirect
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
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.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.1 // indirect
go.uber.org/mock v0.5.2 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
golang.org/x/mod v0.42.0 // indirect
gonum.org/v1/gonum v0.17.0 // indirect
google.golang.org/protobuf v1.36.12
modernc.org/sqlite v1.61.1
)
require (
cel.dev/expr v0.25.3 // indirect
cloud.google.com/go v0.123.0 // 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/longrunning v1.3.0 // indirect
cloud.google.com/go/monitoring v1.31.0 // indirect
cloud.google.com/go/pubsub/v2 v2.7.0 // indirect
dario.cat/mergo v1.0.2 // 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.3
github.com/Azure/azure-sdk-for-go/sdk/keyvault/internal v0.7.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0 // indirect
github.com/Azure/go-ansiterm v0.0.0-20261006220739-8c912ac31dd4 // indirect
github.com/Azure/go-ntlmssp v0.1.1 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 // indirect
github.com/FilenCloudDienste/filen-sdk-go v0.0.39 // indirect
github.com/Files-com/files-sdk-go/v3 v3.3.194 // 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
@@ -313,58 +166,104 @@ require (
github.com/ProtonMail/gluon v0.17.1-0.20230724134000-308be39be96e // indirect
github.com/ProtonMail/go-crypto v1.4.1 // indirect
github.com/ProtonMail/go-srp v0.0.7 // indirect
github.com/ProtonMail/gopenpgp/v3 v3.4.1 // indirect
github.com/PuerkitoBio/goquery v1.12.0 // indirect
github.com/RoaringBitmap/roaring/v2 v2.26.0 // indirect
github.com/a1ex3/zstd-seekable-format-go/pkg v0.10.0 // indirect
github.com/abbot/go-http-auth v0.4.0 // indirect
github.com/andybalholm/brotli v1.2.7 // indirect
github.com/adrg/xdg v0.5.3 // indirect
github.com/anchore/go-lzo v0.1.1 // indirect
github.com/andybalholm/brotli v1.3.0 // indirect
github.com/andybalholm/cascadia v1.3.4 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/thrift v0.25.0 // 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.27 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 // 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.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/internal/configsources v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // 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.9
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/bazelbuild/rules_go v0.46.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
github.com/bits-and-blooms/bitset v1.24.4 // indirect
github.com/blevesearch/snowballstem v0.9.0 // indirect
github.com/boltdb/bolt v1.3.1 // indirect
github.com/boombuler/barcode v1.1.0 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
github.com/buengese/sgzip v0.1.1 // indirect
github.com/buger/jsonparser v1.2.0 // indirect
github.com/calebcase/tmpfile v1.0.3 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/chilts/sid v0.0.0-20190607042430-660e94789ec9 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/cloudflare/circl v1.6.4 // indirect
github.com/cloudinary/cloudinary-go/v2 v2.16.0 // indirect
github.com/cloudsoda/go-smb2 v0.0.0-20260701064823-d8c5600d73b8 // indirect
github.com/cloudsoda/sddl v0.0.0-20250224235906-926454e91efc // indirect
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect
github.com/cockroachdb/apd/v3 v3.2.1 // indirect
github.com/cockroachdb/errors v1.14.0 // indirect
github.com/cockroachdb/logtags v0.0.0-20241215232642-bb51bb14a506 // indirect
github.com/cockroachdb/redact v1.1.5 // indirect
github.com/cockroachdb/version v0.0.0-20250314144055-3860cd14adf2 // indirect
github.com/colinmarc/hdfs/v2 v2.4.0 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v1.0.0-rc.4 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.7.0 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/creasty/defaults v1.8.0 // indirect
github.com/cronokirby/saferith v0.33.1-0.20250226174546-1f11f94ce488 // indirect
github.com/cznic/mathutil v0.0.0-20181122101859-297441e03548 // indirect
github.com/d4l3k/messagediff v1.2.1 // indirect
github.com/dave/dst v0.27.2 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/diskfs/go-diskfs v1.9.4 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.8.2 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/dromara/dongle v1.0.1 // indirect
github.com/dropbox/dropbox-sdk-go-unofficial/v6 v6.4.0 // indirect
github.com/eapache/go-resiliency v1.6.0 // indirect
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
github.com/eapache/queue v1.1.0 // indirect
github.com/ebitengine/purego v0.11.2 // indirect
github.com/elastic/gosigar v0.14.3 // indirect
github.com/emersion/go-message v0.18.2 // indirect
github.com/emersion/go-vcard v0.0.0-20260618161152-d854b7e0e2d3 // indirect
github.com/envoyproxy/go-control-plane/envoy v1.40.1-0.20261014170222-9c4befd3c419 // indirect
github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect
github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c // indirect
github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect
github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/flynn/noise v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/geoarrow/geoarrow-go v0.0.0-20260403143023-f54751c3e3a1 // indirect
github.com/geoffgarside/ber v1.2.0 // indirect
github.com/gin-gonic/gin v1.11.0 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
github.com/go-chi/chi/v5 v5.4.0 // indirect
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
github.com/go-git/go-billy/v5 v5.9.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.6 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
@@ -376,129 +275,226 @@ require (
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.11.2 // indirect
github.com/go-zookeeper/zk v1.0.4 // indirect
github.com/goccy/go-json v0.12.0 // indirect
github.com/goccy/go-yaml v1.18.0 // 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
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/s2a-go v0.1.11 // indirect
github.com/google/wire v0.7.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.24 // indirect
github.com/googleapis/gax-go/v2 v2.27.0 // indirect
github.com/gopherjs/gopherjs v1.17.2 // indirect
github.com/gorilla/schema v1.4.1 // indirect
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 v1.16.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 // indirect
github.com/hashicorp/errwrap v1.1.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
github.com/hashicorp/go-msgpack/v2 v2.1.5 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/go-secure-stdlib/parseutil v0.2.0 // indirect
github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
github.com/hashicorp/go-uuid v1.0.3 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/hcl v1.0.1-vault-7 // indirect
github.com/internxt/rclone-adapter v0.0.0-20260708165336-dd6561bacfa2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/jaegertracing/jaeger v1.47.0 // indirect
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
github.com/jcmturner/gofork v1.7.6 // indirect
github.com/jcmturner/goidentity/v6 v6.0.1 // indirect
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
github.com/jcmturner/rpc/v2 v2.0.3 // indirect
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 // indirect
github.com/jlaffaye/ftp v0.2.1-0.20251026020404-6602e981a1bb // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/jtolio/noiseconn v0.0.0-20231127013910-f6d9ecbf1de7 // indirect
github.com/jzelinskie/whirlpool v0.0.0-20201016144138-0675e54bb004 // indirect
github.com/k0kubun/pp v3.0.1+incompatible
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
github.com/klauspost/cpuid/v2 v2.4.2 // indirect
github.com/koofr/go-httpclient v0.0.0-20240520111329-e20f8f203988 // indirect
github.com/koofr/go-koofrclient v0.0.0-20221207135200-cbd7fc9ad6a6 // indirect
github.com/kr/fs v0.1.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/lanrat/extsort v1.4.2 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lib/pq v1.12.3 // indirect
github.com/lithammer/shortuuid/v3 v3.0.7 // indirect
github.com/lpar/calendar v0.2.0 // indirect
github.com/lufia/plan9stats v0.0.0-20260627054121-477a66015f15 // indirect
github.com/magiconair/properties v1.18.12 // indirect
github.com/mailru/easyjson v0.9.2 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-runewidth v0.0.31 // indirect
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.1-0.20220423185008-bf980b35cac4
github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.3.3 // indirect
github.com/moby/moby/api v1.56.1 // indirect
github.com/moby/moby/client v0.6.2 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.4.1 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/mschoch/smat v0.2.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // 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/ncruces/go-strftime v1.1.0 // indirect
github.com/ncw/swift/v2 v2.0.5 // indirect
github.com/nxadm/tail v1.4.11 // indirect
github.com/oklog/ulid v1.3.1 // indirect
github.com/oklog/ulid/v2 v2.1.2 // indirect
github.com/onsi/ginkgo/v2 v2.23.3 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/openzipkin/zipkin-go v0.4.3 // indirect
github.com/oracle/oci-go-sdk/v65 v65.121.0 // indirect
github.com/panjf2000/ants/v2 v2.12.1 // indirect
github.com/parquet-go/bitpack v1.1.1 // indirect
github.com/parquet-go/jsonlite v1.5.7 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
github.com/petermattis/goid v0.0.0-20260113132338-7c7de50cc741 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pierrec/lz4/v4 v4.1.33
github.com/pierrre/geohash v1.0.0 // indirect
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
github.com/pingcap/goleveldb v0.0.0-20191226122134-f82aafb29989 // indirect
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
github.com/pingcap/log v1.1.1-0.20221110025148-ca232912c9f3 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pkg/xattr v0.4.12 // indirect
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 // indirect
github.com/pquerna/otp v1.5.0 // indirect
github.com/prometheus/common v0.71.0 // indirect
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/rclone/Proton-API-Bridge v1.0.5 // indirect
github.com/rclone/go-proton-api v1.0.4 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/relvacode/iso8601 v1.7.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rfjakob/eme v1.2.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.15.0 // indirect
github.com/ryanuber/go-glob v1.0.0 // indirect
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/samber/lo v1.53.0 // indirect
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
github.com/smarty/assertions v1.15.0 // indirect
github.com/sony/gobreaker v1.0.0 // indirect
github.com/sony/gobreaker/v2 v2.4.0 // indirect
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/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/spiffe/go-spiffe/v2 v2.9.0 // indirect
github.com/stretchr/objx v0.5.3 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/substrait-io/substrait v0.87.0 // indirect
github.com/substrait-io/substrait-go/v8 v8.1.1 // indirect
github.com/substrait-io/substrait-protobuf/go v0.85.0 // indirect
github.com/t3rm1n4l/go-mega v0.0.0-20260717075258-c6acd6a5bd04 // indirect
github.com/tarantool/go-iproto v1.1.0 // indirect
github.com/tiancaiamao/gp v0.0.0-20221230034425-4025bc8a4d4a // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tikv/pd/client v0.0.0-20230329114254-1948c247c2b1 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/twmb/murmur3 v1.1.8 // indirect
github.com/twpayne/go-kml/v3 v3.2.1 // indirect
github.com/tyler-smith/go-bip39 v1.1.0 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/unknwon/goconfig v1.0.0 // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/winfsp/cgofuse v1.6.1-0.20260126094232-f2c4fccdb286
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/yandex-cloud/go-genproto v0.0.0-20240819112322-98a264d392f6 // indirect
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810122915-65bfd5c4b705 // indirect
github.com/ydb-platform/ydb-go-yc v0.12.5 // indirect
github.com/ydb-platform/ydb-go-yc-metadata v0.6.2 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
github.com/yunify/qingstor-sdk-go/v3 v3.2.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/zeebo/blake3 v0.2.4 // indirect
github.com/zeebo/errs v1.4.0 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.etcd.io/bbolt v1.5.0 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // 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/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/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.47.0 // indirect
go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/mock v0.5.2 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/term v0.47.0
golang.org/x/time v0.16.0
go.yaml.in/yaml/v2 v2.4.4 // indirect
golang.org/x/mod v0.42.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.52.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
gonum.org/v1/gonum v0.17.0 // indirect
google.golang.org/genproto v0.0.0-20261019180522-ce908d29299b // 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/inf.v0 v0.9.1 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/validator.v2 v2.0.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.77.1 // indirect
modernc.org/b v1.0.0 // indirect
modernc.org/libc v1.79.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
moul.io/http2curl/v2 v2.3.0 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
storj.io/common v0.0.0-20260629224719-ba1bff0a7846 // indirect
+82 -78
View File
@@ -85,6 +85,8 @@ github.com/IBM/go-sdk-core/v5 v5.23.1 h1:fxLusCG+GlGY1SM7BYAAiiSFhzKUs5zqs0P8knD
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=
github.com/Jille/raft-grpc-transport v1.6.1/go.mod h1:HbOjEdu/yzCJ/mjTF6wEOJNbAUpHfU2UOA2hVD4CNFg=
github.com/KimMachineGun/automemlimit v1.0.2 h1:DkORkhuzrwT2/b35xz8zLd7cJ6Hu2ESRGBY8HKUFIYk=
github.com/KimMachineGun/automemlimit v1.0.2/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0=
github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7YgDP83g=
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd h1:nzE1YQBdx1bq9IlZinHa+HVffy+NmVRoKr+wHN8fpLE=
@@ -142,8 +144,8 @@ github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktp
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/anchore/go-lzo v0.1.1 h1:IwL/fvkdtlIrYIXck6WxZ3nb8WjjHziYYmGxlooyOnM=
github.com/anchore/go-lzo v0.1.1/go.mod h1:3kLx0bve2oN1iDwgM1U5zGku1Tfbdb0No5qp1eL1fIk=
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
@@ -151,14 +153,14 @@ github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op h1:kpBdlEPbRvff0m
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/apache/arrow-go/v18 v18.8.0 h1:BLOzbPv7bxMPgXPacAg6HQjnxupYsZzC4tf+FkqPU/M=
github.com/apache/arrow-go/v18 v18.8.0/go.mod h1:uJCFfCwq0KsxCmsCfQg4ft+LsW+iHYzAXiSDh5ug/8U=
github.com/apache/arrow-go/v18 v18.9.0 h1:o+CdPvv7G7tXRc3UCq7sAkMOEEzvPFhunnWPMtIDZeQ=
github.com/apache/arrow-go/v18 v18.9.0/go.mod h1:QbEIuSG88lfEwkBfq1OKoZ5/aFXLObsS2awz9F5OKak=
github.com/apache/cassandra-gocql-driver/v2 v2.1.2 h1:lu/p0Db2av18enHJvWJQoChLssI0P+AR06STq4VdvCc=
github.com/apache/cassandra-gocql-driver/v2 v2.1.2/go.mod h1:QH/asJjB3mHvY6Dot6ZKMMpTcOrWJ8i9GhsvG1g0PK4=
github.com/apache/iceberg-go v0.7.0 h1:bTD6Pb4uM4sWcMfIx0/cV1haHMc84r+CvPieUqYzD4I=
github.com/apache/iceberg-go v0.7.0/go.mod h1:oGz5MX3/m3GDc6acsrwbdHChj28jZH8MVDWqUrW6WQQ=
github.com/apache/thrift v0.24.0 h1:zy31L1a49QTNB2bG1BBfMXol3yJrTH975G3pPubQVLQ=
github.com/apache/thrift v0.24.0/go.mod h1:zPt6WxgvTOM6hF92y8C+MkEM5LMxZuk4JcQOiU4Esvs=
github.com/apache/thrift v0.25.0 h1:6LLlvoPjy8Cc/0b5TYRcTR3RZa2W0at3WQRcOkDwVGs=
github.com/apache/thrift v0.25.0/go.mod h1:4lwyToijD9T70w7GlevFk7FnpY60Wv8I8krMkF6FkAo=
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3 h1:WZaTKNHCfcw7fWSR6/RKnCldVzvYZC+Y20Su4lffEIg=
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3/go.mod h1:OMVSB21p9+xQUIqlGizHPZfjK+SHws1ht+ZytVDoz9U=
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er+LKDHDUfU5tRvFwxH0LjPpZN8OoG8Ll+liGU=
@@ -171,10 +173,10 @@ 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.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 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 h1:LfdRwpJ0Dfh+vpqHevmmnFnMoc3/lfB4pdHOfWpLfH4=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29/go.mod h1:r6fijnrGRQ4OnSGyHYuFcC7G6wdwB4Ld8WhiIaGZHx0=
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=
@@ -185,22 +187,22 @@ github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.34 h1:Pn7OsMwBLbkZ6OnCxWHA
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.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/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15 h1:XKIkHY7yRHnTJrixMmcA1qIm3qenDe/vmOtf/xiuWYE=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.15/go.mod h1:HqYW3gHCQl0tF6dO7kXgc0wFe1Yng0hgCEI7Xa3rK54=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27/go.mod h1:LpMjYa8iT3kMkAxsVCGfyXkBDOOKsziY6S2wSpEvY70=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16 h1:D2smhPZgqVLuc8rmuvb6wrG4sgut9iv1BN8W2twFtfo=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.16/go.mod h1:HheOgBYcgoZgeKSLVEmk9whxHERlVXAKTVWK3xizKeo=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15 h1:ds6Pm/S5xYXPmiqyebd0AeK0zHAAO7qHP1+JZauFnpA=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.15/go.mod h1:WqaHpxUhwzsE+NYp2TQitKclpwhi1XYp6wMsdg+yd/k=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15 h1:5w2E7ndu7XOt62yvu2vGm/Rv7WDn1oQjrJ7Dt1NTVTM=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.15/go.mod h1:1WgfBCsJYL6E7T2QkkE8kQvo7uG+5+z2LpaQ9L6pjZs=
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1 h1:fOeEIKMlgwKbMFSNMM+pLo2NPRJ1dSKbaAuZYGXUVR0=
github.com/aws/aws-sdk-go-v2/service/s3 v1.117.1/go.mod h1:xHaAZkbYuIc9UtLZxdoeyhzmx06g1paDjPkHgljJU/I=
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=
@@ -213,8 +215,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEB
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.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI=
github.com/aws/smithy-go v1.28.11/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=
@@ -544,8 +546,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.11.2 h1:jdZv93Tt4ioR8yW1CoNsvSxrcZlCXAUU1aZXN7gpXUA=
github.com/goccy/go-json v0.11.2/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
github.com/goccy/go-json v0.12.0/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=
@@ -615,8 +617,8 @@ github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc=
github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/s2a-go v0.1.11 h1:7v1V1TraNGP63WptsAkNqr2w8jgm4vM6A6qx6Lsw9iM=
github.com/google/s2a-go v0.1.11/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
@@ -722,10 +724,10 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
github.com/jaegertracing/jaeger v1.47.0/go.mod h1:mHU/OHFML51CijQql4+rLfgPOcIb9MhxOMn+RKQwrJc=
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
@@ -740,8 +742,8 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/jhump/protoreflect v1.18.1 h1:h4odAaLg9wyn7yHxMF7sSkJ7JfLwK1oy37/1Pi212GE=
github.com/jhump/protoreflect v1.18.1/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
github.com/jhump/protoreflect v1.19.0 h1:YhKbE78JrjfngcCZfZTIV7rQQGndyqll6fXfaqiOEg4=
github.com/jhump/protoreflect v1.19.0/go.mod h1:I2yar2oJEMf0k4EMryPzfV0tvGwN/SejJziYBOpETQo=
github.com/jhump/protoreflect/v2 v2.0.0-beta.1 h1:Dw1rslK/VotaUGYsv53XVWITr+5RCPXfvvlGrM/+B6w=
github.com/jhump/protoreflect/v2 v2.0.0-beta.1/go.mod h1:D9LBEowZyv8/iSu97FU2zmXG3JxVTmNw21mu63niFzU=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
@@ -782,10 +784,10 @@ github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXw
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4=
github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/reedsolomon v1.14.2 h1:SafJYwpBBQBI6amHUygcjxZjXeN2HpiENHQDwuPWCCQ=
github.com/klauspost/reedsolomon v1.14.2/go.mod h1:yjqqjgMTQkBUHSG97/rm4zipffCNbCiZcB3kTqr++sQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
@@ -919,8 +921,8 @@ 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=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/ncw/swift/v2 v2.0.5 h1:9o5Gsd7bInAFEqsGPcaUdsboMbqf8lnNtxqWKFT9iz8=
github.com/ncw/swift/v2 v2.0.5/go.mod h1:cbAO76/ZwcFrFlHdXPjaqWZ9R7Hdar7HpjRXBfbjigk=
github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY=
@@ -955,15 +957,17 @@ github.com/orcaman/concurrent-map/v2 v2.0.1 h1:jOJ5Pg2w1oeB6PeDurIYf6k9PQ+aTITr/
github.com/orcaman/concurrent-map/v2 v2.0.1/go.mod h1:9Eq3TG2oBe5FirmYWQfYO5iH1q0Jv47PLaNK++uCdOM=
github.com/panjf2000/ants/v2 v2.12.1 h1:BWvU2wHpyXWxhhNXsGB6JXLCNbshyLd1QxvoAmZnu10=
github.com/panjf2000/ants/v2 v2.12.1/go.mod h1:tSQuaNQ6r6NRhPt+IZVUevvDyFMTs+eS4ztZc52uJTY=
github.com/parquet-go/bitpack v1.0.0 h1:AUqzlKzPPXf2bCdjfj4sTeacrUwsT7NlcYDMUQxPcQA=
github.com/parquet-go/bitpack v1.0.0/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.0.0 h1:87QNdi56wOfsE5bdgas0vRzHPxfJgzrXGml1zZdd7VU=
github.com/parquet-go/jsonlite v1.0.0/go.mod h1:nDjpkpL4EOtqs6NQugUsi0Rleq9sW/OtC1NnZEnxzF0=
github.com/parquet-go/parquet-go v0.32.0 h1:NWDqTUHfrCS4cJP/Fj2HlxvqsrVedWG3sayMkf+znzM=
github.com/parquet-go/parquet-go v0.32.0/go.mod h1:navtkAYr2LGoJVp141oXPlO/sxLvaOe3la2JEoD8+rg=
github.com/parquet-go/bitpack v1.1.1 h1:mygqlCBk/rnvtqqP5Oy7IkIPAxZ3bDM7V4yce/ms6pE=
github.com/parquet-go/bitpack v1.1.1/go.mod h1:XnVk9TH+O40eOOmvpAVZ7K2ocQFrQwysLMnc6M/8lgs=
github.com/parquet-go/jsonlite v1.5.7 h1:FxIrc2MBZ9QLpljM1+3F3JuCuug+BWOt8Yx+S4o3bl8=
github.com/parquet-go/jsonlite v1.5.7/go.mod h1:ZIyft0+sSdvgTu2m6RpqxWx/F3UBNtF3ammevxDJcoE=
github.com/parquet-go/parquet-go v0.33.0 h1:iDe13lcW6t0mnZWPqKqWccNa5GdP/L9GNNyzlr8JqNY=
github.com/parquet-go/parquet-go v0.33.0/go.mod h1:zl2XMxzSXZ5UYGfTLK0kvW0ifgVMPJ6I+/zmNnsOSh4=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
@@ -1049,8 +1053,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.16.0 h1:1O8oQqnj9hLACoo6CVMgn57z2pLWXvgemhh4GsquV+Y=
github.com/rabbitmq/amqp091-go v1.16.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
github.com/rabbitmq/amqp091-go v1.17.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=
@@ -1100,8 +1104,8 @@ github.com/schollz/progressbar/v3 v3.19.1 h1:iv8BgwOvdML/S3p84uBpy/IMigv4U9594vP
github.com/schollz/progressbar/v3 v3.19.1/go.mod h1:LFL7jqimKxfhero4K1eCkUr/6R39AgQeiPCJtlTWIW8=
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564 h1:TgxPraf1NmF6XTcUG53ULpLQrKvhtUJxQ3hyekxSDNQ=
github.com/seaweedfs/cockroachdb-parser v0.0.0-20260225204133-2f342c5ea564/go.mod h1:JSKCh6uCHBz91lQYFYHCyTrSVIPge4SUFVn28iwMNB0=
github.com/seaweedfs/go-fuse/v2 v2.9.4 h1:ACyloiuopdhRSjdLLeSWbsVaemMPskORaRF01TY6GyM=
github.com/seaweedfs/go-fuse/v2 v2.9.4/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
github.com/seaweedfs/go-fuse/v2 v2.9.5 h1:qz3tuAGbUJOPJtaxyP35xW3JT23utywXKer0hoTiJPU=
github.com/seaweedfs/go-fuse/v2 v2.9.5/go.mod h1:zABdmWEa6A0bwaBeEOBUeUkGIZlxUhcdv+V1Dcc/U/I=
github.com/seaweedfs/goexif v1.0.3 h1:ve/OjI7dxPW8X9YQsv3JuVMaxEyF9Rvfd04ouL+Bz30=
github.com/seaweedfs/goexif v1.0.3/go.mod h1:Oni780Z236sXpIQzk1XoJlTwqrJ02smEin9zQeff7Fk=
github.com/seaweedfs/raft v1.2.4 h1:lEBQ9seDSGrJNs2WitMgfYpaDxLgh9qukm1IJTEV1hk=
@@ -1317,8 +1321,8 @@ github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810122915-65bfd5c4b705 h1:7V
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260810122915-65bfd5c4b705/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3 h1:A48PcmIETWwbEMIGwndv52uME6J1eJ28MBgF7HVR74o=
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.3/go.mod h1:oRGF+67GWLbtNzqGygsPIUsjXmsRXD1KS5m3o5ppm2k=
github.com/ydb-platform/ydb-go-sdk/v3 v3.155.1 h1:ZMByYe53zZ9R1o23fxJsbNhjzKFQkzpXm6uGj8gWHXQ=
github.com/ydb-platform/ydb-go-sdk/v3 v3.155.1/go.mod h1:dJXJ1u00IqO8Vsph8fWmYj8b1E7jyphnvJPqA69emBY=
github.com/ydb-platform/ydb-go-sdk/v3 v3.157.1 h1:eaf2VLTwta3VO0+K9+rUd1yWtXU6C5WxZx7v/sdbz/Y=
github.com/ydb-platform/ydb-go-sdk/v3 v3.157.1/go.mod h1:dJXJ1u00IqO8Vsph8fWmYj8b1E7jyphnvJPqA69emBY=
github.com/ydb-platform/ydb-go-yc v0.12.5 h1:qYIeU1N6a92FaDA0+/vR55l5IzRF50MeLZwUWwvy2xQ=
github.com/ydb-platform/ydb-go-yc v0.12.5/go.mod h1:DlSltVQKEdXJotaAYwoHzMGDF9EJw5S3hg3LXe/5yYw=
github.com/ydb-platform/ydb-go-yc-metadata v0.6.2 h1:CZFawwHjLcjsxcl/g0dGIXbI2r41okPGLCydF4qTHcc=
@@ -1351,12 +1355,12 @@ 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.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/pkg/v3 v3.7.4 h1:633yLMDAQHWqLTRMxUNuZfOy6a4REJPcA3juoMRx5qU=
go.etcd.io/etcd/client/pkg/v3 v3.7.4/go.mod h1:I1lMmoiq2SF4Wg0Gru7uXMovS1eEo6wwAxcFPFPk/v0=
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.mongodb.org/mongo-driver v1.17.10 h1:kdAgQvu8TROXZpSkJQd5wzfaNCCrMbpZyKFtQ6qkPCE=
go.mongodb.org/mongo-driver v1.17.10/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=
@@ -1501,8 +1505,8 @@ golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -1514,8 +1518,8 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1557,8 +1561,8 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
@@ -1567,8 +1571,8 @@ golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk=
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
@@ -1705,20 +1709,20 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
modernc.org/b v1.0.0 h1:vpvqeyp17ddcQWF29Czawql4lDdABCDRbXRAS4+aF2o=
modernc.org/b v1.0.0/go.mod h1:uZWcZfRj1BpYzfN9JTerzlNUnnPsV9O2ZA8JsRcubNg=
modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys=
modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4=
modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o=
modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8=
modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M=
modernc.org/mathutil v1.1.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
@@ -1728,8 +1732,8 @@ modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
modernc.org/sqlite v1.61.1 h1:TBEE49wz7VlxS+qXRXMQiPUZYOXHJ4ku83daYv1fe04=
modernc.org/sqlite v1.61.1/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0=
modernc.org/strutil v1.1.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.55"
appVersion: "4.56"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.55.0
version: 4.56.0
+77 -1
View File
@@ -122,6 +122,18 @@ https://github.com/rancher/local-path-provisioner
you can use ANY storage class you like, just update the correct storage-class
for your deployment.
Every claim the chart creates also takes an optional `volumeAttributesClassName`
next to its `storageClass` (for example `master.data.volumeAttributesClassName`
or `volume.dataDirs[].volumeAttributesClassName`), to set provisioned
performance such as IOPS and throughput through a
[VolumeAttributesClass](https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/).
It needs Kubernetes 1.34+, or 1.31+ with the `VolumeAttributesClass` feature gate.
`volumeClaimTemplates` cannot be changed on an existing StatefulSet, and a new
template only reaches claims created after it. To set it on a release that
already exists, patch `spec.volumeAttributesClassName` on each existing claim,
and delete the StatefulSet with `--cascade=orphan` before the upgrade so the
upgrade can apply the new template.
### Master data: hostPath vs a claim
The master's `-mdir` holds its Raft log and snapshots, and with them the
@@ -255,6 +267,18 @@ filer:
enabled: true
```
### Message queue broker
An S3 gateway can run a message queue broker beside it, on gRPC port 17777 by default. `s3.mqBroker`, `filer.s3.mqBroker` and `allInOne.s3.mqBroker` choose it:
- `auto` (the default) runs it only with `global.seaweedfs.enableSecurity`, where the chart gives it mutual TLS through `[grpc.msg_broker]` in security.toml.
- `true` runs it either way. Without `enableSecurity` it then accepts any client that can reach the port.
- `false` never runs it.
`s3.mqBrokerPort`, `filer.s3.mqBrokerPort` and `allInOne.s3.mqBrokerPort` set the port, and 0 also turns the broker off. The `allInOne.s3` values inherit the `s3` ones when null. The container port and NetworkPolicy entry appear only when the broker runs.
Brokers register with the master under the pod IP, and clients and other brokers find them there and dial that address, so the port is deliberately left off the Services; a LoadBalancer or NodePort Service would only publish it outside the cluster. With `networkPolicy.enabled` the chart admits the port from the release's own pods; publishers and subscribers elsewhere need an `extraIngress` rule for it.
### Enabling Authentication to S3
To enable authentication for S3, you have two options:
@@ -330,6 +354,54 @@ applies. Rotating a key in the Secret takes effect on the next pod restart, as
with any other environment variable. The COSI driver parses the config itself
and does not resolve these references.
#### Reload identities without a restart
The chart hashes `existingConfigSecret` into the filer and S3 pod templates when it renders,
so the first Helm upgrade after the Secret's content changes restarts those pods, and every
identity change briefly takes S3 down, completely so with a single filer. SeaweedFS also
reloads the identities file on SIGHUP, which `configReloader` uses instead:
```yaml
filer:
s3:
enabled: true
enableAuth: true
existingConfigSecret: my-s3-identities
configReloader:
enabled: true
```
`s3.configReloader` does the same for the standalone S3 gateway. With it:
- An `s3-config-reloader` sidecar checks the mounted identities file every second, and
sends SIGHUP to SeaweedFS when it changes and once when it starts. Kubelet updates the
file at its next sync of the pod. Secret volumes are eventually consistent, so there is no
fixed bound: with the kubelet's default settings (a one-minute sync period and the `Watch`
Secret change detection strategy) it typically takes up to about 90 seconds, and changing
an annotation on the pod usually brings it down to seconds. Other kubelet settings can make
it slower. Until the file is updated, a revoked identity keeps working.
- Changes to the content of `existingConfigSecret` no longer restart the pod: the chart
leaves `checksum/s3config` off it. Adding, changing, disabling and deleting identities
apply without a restart. Other files in the Secret, such as an audit log config, still
need one, and so do changes to the values the chart generates its own Secret from, such
as `s3.credentials`.
- Every reload also re-creates the KMS providers configured in the identities file, and
drops the ones it no longer lists. A file whose identities don't parse changes neither.
A provider that fails to load keeps its previous instance, unless it's the one S3 uses,
which fails the KMS reload. S3 uses `default_provider`, or the first provider by name
when it isn't set, so set it when you list more than one, as adding a provider whose
name sorts first would switch S3 to it. The `local` provider reads its `keys` list
again, so objects encrypted under those keys stay readable. The keys it generates in
memory are lost on a reload, as on a restart, so list every key that protects objects
you need to keep, and give the alias `aws/s3` to the one that should serve requests
naming no key.
- The pod shares its process namespace (see [Sharing the process namespace](#sharing-the-process-namespace)),
so the sidecar can see SeaweedFS. It uses the component's image and container security
context, because it must run as the same user as SeaweedFS to signal it. If it can't
signal SeaweedFS, it logs a warning.
The all-in-one deployment does not have this option.
## Admin Component
The admin component provides a modern web-based administration interface for managing SeaweedFS clusters. It includes:
@@ -629,6 +701,10 @@ The volume servers do not require client certificates, because kubelet probes ca
`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.
## Sharing the process namespace
`filer.shareProcessNamespace` and `s3.shareProcessNamespace` let the containers in the filer and S3 pods see each other's processes, so a sidecar can signal SeaweedFS, for example with SIGHUP to reload the S3 identities file. SeaweedFS is then no longer PID 1 in its container, and every container in the pod can read the other containers' processes and files through `/proc`. Both are off by default.
## Pod and container security contexts
Pod and container security contexts are configurable independently for every built-in workload and remain empty by default for backwards compatibility. The examples in `values.yaml` show how to enable a `RuntimeDefault` seccomp profile, disable privilege escalation and privileged mode, drop all Linux capabilities, and use a read-only root filesystem.
@@ -729,7 +805,7 @@ 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.
@@ -189,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 }}
@@ -355,6 +359,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ .Values.admin.data.storageClass }}
{{- with .Values.admin.data.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.admin.data.size }}
@@ -369,6 +376,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ .Values.admin.logs.storageClass }}
{{- with .Values.admin.logs.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.admin.logs.size }}
@@ -274,6 +274,9 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
-sftp \
@@ -406,6 +409,10 @@ spec:
- containerPort: {{ $httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "allInOne") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
- containerPort: {{ .Values.allInOne.sftp.port | default .Values.sftp.port }}
@@ -22,6 +22,9 @@ spec:
{{- if .Values.allInOne.data.storageClass }}
storageClassName: {{ .Values.allInOne.data.storageClass }}
{{- end }}
{{- with .Values.allInOne.data.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.allInOne.data.size | default "10Gi" }}
@@ -4,6 +4,10 @@
{{- if .Values.filer.s3.enabled }}
{{- $s3PreStopSeconds = .Values.filer.s3.preStopSeconds | int }}
{{- end }}
{{- $s3ConfigReloader := (.Values.filer.s3.configReloader | default dict).enabled }}
{{- if and $s3ConfigReloader (not (and .Values.filer.s3.enabled .Values.filer.s3.enableAuth)) }}
{{- fail "filer.s3.configReloader.enabled needs filer.s3.enabled and filer.s3.enableAuth: it reloads the identities file they mount" }}
{{- end }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
@@ -50,8 +54,11 @@ spec:
{{- end }}
{{- $podAnnotations := mergeOverwrite (deepCopy (.Values.podAnnotations | default dict)) (.Values.filer.podAnnotations | default dict) }}
{{- if .Values.filer.s3.existingConfigSecret }}
{{- /* With the config reloader, a change to the existing Secret is applied by SIGHUP, so nothing in it may restart the pod. */}}
{{- if not $s3ConfigReloader }}
{{- $configSecret := (lookup "v1" "Secret" (include "seaweedfs.namespace" .) .Values.filer.s3.existingConfigSecret) | default dict }}
{{- $_ := set $podAnnotations "checksum/s3config" ($configSecret | toYaml | sha256sum) }}
{{- end }}
{{- else }}
{{- $_ := set $podAnnotations "checksum/s3config" (include "seaweedfs.s3.configChecksum" .) }}
{{- end }}
@@ -82,6 +89,9 @@ spec:
schedulerName: {{ .Values.filer.schedulerName | quote }}
{{- end }}
enableServiceLinks: false
{{- if or .Values.filer.shareProcessNamespace $s3ConfigReloader }}
shareProcessNamespace: true
{{- end }}
{{- if .Values.filer.initContainers }}
initContainers:
{{ tpl .Values.filer.initContainers . | nindent 8 | trim }}
@@ -286,6 +296,9 @@ spec:
{{- if gt $s3PreStopSeconds 0 }}
-s3.preStopSeconds={{ $s3PreStopSeconds }} \
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).args }}
{{ . }} \
{{- end }}
{{- end }}
-master={{ include "seaweedfs.masterServerArg" . }} \
{{- range .Values.filer.extraArgs }}
@@ -353,6 +366,10 @@ spec:
- containerPort: {{ .Values.filer.s3.httpsPort }}
name: swfs-s3-tls
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "filer") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- end }}
{{- $jwt := (.Values.global.seaweedfs.securityConfig).jwtSigning | default dict }}
{{- $isJwtEnabled := or $jwt.filerWrite $jwt.filerRead }}
@@ -397,6 +414,9 @@ spec:
{{- if .Values.filer.containerSecurityContext.enabled }}
securityContext: {{- omit .Values.filer.containerSecurityContext "enabled" | toYaml | nindent 12 }}
{{- end }}
{{- if $s3ConfigReloader }}
{{- include "seaweedfs.s3.configReloaderContainer" (dict "root" $ "image" (include "seaweedfs.filer.image" .) "port" .Values.filer.s3.port "resources" .Values.filer.s3.configReloader.resources "securityContext" .Values.filer.containerSecurityContext) | nindent 8 }}
{{- end }}
{{- if .Values.filer.sidecars }}
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.filer.sidecars "context" $) | nindent 8 }}
{{- end }}
@@ -497,6 +517,9 @@ spec:
{{- if .Values.filer.storageClass }}
storageClassName: {{ .Values.filer.storageClass }}
{{- end }}
{{- with .Values.filer.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
{{- end }}
{{- $pvc_exists := include "seaweedfs.filer.pvc_exists" . -}}
{{- if $pvc_exists }}
@@ -513,6 +536,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ .Values.filer.data.storageClass }}
{{- with .Values.filer.data.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.filer.data.size }}
@@ -529,6 +555,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ .Values.filer.logs.storageClass }}
{{- with .Values.filer.logs.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.filer.logs.size }}
@@ -340,6 +340,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ .Values.master.data.storageClass }}
{{- with .Values.master.data.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.master.data.size }}
@@ -356,6 +359,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ .Values.master.logs.storageClass }}
{{- with .Values.master.logs.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.master.logs.size }}
@@ -1,6 +1,10 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.s3.enabled }}
{{- $preStopSeconds := .Values.s3.preStopSeconds | int }}
{{- $s3ConfigReloader := (.Values.s3.configReloader | default dict).enabled }}
{{- if and $s3ConfigReloader (not .Values.s3.enableAuth) }}
{{- fail "s3.configReloader.enabled needs s3.enableAuth: it reloads the identities file that mounts" }}
{{- end }}
{{- $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) -}}
@@ -47,8 +51,11 @@ spec:
{{- end }}
{{- $podAnnotations := mergeOverwrite (deepCopy (.Values.podAnnotations | default dict)) (.Values.s3.podAnnotations | default dict) }}
{{- if .Values.s3.existingConfigSecret }}
{{- /* With the config reloader, a change to the existing Secret is applied by SIGHUP, so nothing in it may restart the pod. */}}
{{- if not $s3ConfigReloader }}
{{- $configSecret := (lookup "v1" "Secret" (include "seaweedfs.namespace" .) .Values.s3.existingConfigSecret) | default dict }}
{{- $_ := set $podAnnotations "checksum/s3config" ($configSecret | toYaml | sha256sum) }}
{{- end }}
{{- else }}
{{- $_ := set $podAnnotations "checksum/s3config" (include "seaweedfs.s3.configChecksum" .) }}
{{- end }}
@@ -78,6 +85,9 @@ spec:
schedulerName: {{ .Values.s3.schedulerName | quote }}
{{- end }}
enableServiceLinks: false
{{- if or .Values.s3.shareProcessNamespace $s3ConfigReloader }}
shareProcessNamespace: true
{{- end }}
{{- if .Values.s3.serviceAccountName }}
serviceAccountName: {{ .Values.s3.serviceAccountName | quote }}
{{- end }}
@@ -169,6 +179,9 @@ spec:
{{- end }}
{{- /* rendered even when 0: an if would drop the flag and weed would serve its default */}}
-port.lance={{ .Values.s3.lancePort | default 0 }} \
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).args }}
{{ . }} \
{{- end }}
{{- range .Values.s3.extraArgs }}
{{ . }} \
{{- end }}
@@ -223,6 +236,10 @@ spec:
- containerPort: {{ .Values.s3.lancePort }}
name: swfs-lance
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list . "s3") | fromJson).port }}
- containerPort: {{ int . }}
name: swfs-mq-broker
{{- end }}
{{- if .Values.s3.metricsPort }}
- containerPort: {{ .Values.s3.metricsPort }}
name: metrics
@@ -262,6 +279,9 @@ spec:
{{- if .Values.s3.containerSecurityContext.enabled }}
securityContext: {{- omit .Values.s3.containerSecurityContext "enabled" | toYaml | nindent 12 }}
{{- end }}
{{- if $s3ConfigReloader }}
{{- include "seaweedfs.s3.configReloaderContainer" (dict "root" $ "image" (include "seaweedfs.s3.image" .) "port" .Values.s3.port "resources" .Values.s3.configReloader.resources "securityContext" .Values.s3.containerSecurityContext) | nindent 8 }}
{{- end }}
{{- if .Values.s3.sidecars }}
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.s3.sidecars "context" $) | nindent 8 }}
{{- end }}
@@ -269,15 +269,69 @@ 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 -}}
{{/*
The message queue broker beside an S3 gateway, for (list $ "s3"|"filer"|"allInOne"),
as JSON: "args" are its flags and "port" the port it serves, 0 when it cannot run.
Unflagged, weed starts it only with grpc.msg_broker TLS, which enableSecurity
writes, and on 17777; defaults are left out so images without these flags start.
allInOne.s3 inherits s3's mqBroker and mqBrokerPort when null.
*/}}
{{- define "seaweedfs.mqBroker" -}}
{{- $root := index . 0 -}}
{{- $component := index . 1 -}}
{{- $prefix := "" -}}
{{- $name := "s3.mqBroker" -}}
{{- $mode := $root.Values.s3.mqBroker -}}
{{- $port := $root.Values.s3.mqBrokerPort -}}
{{- if eq $component "filer" -}}
{{- $prefix = "s3." -}}
{{- $name = "filer.s3.mqBroker" -}}
{{- $mode = $root.Values.filer.s3.mqBroker -}}
{{- $port = $root.Values.filer.s3.mqBrokerPort -}}
{{- else if eq $component "allInOne" -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBroker) -}}
{{- $name = "allInOne.s3.mqBroker" -}}
{{- $mode = $root.Values.allInOne.s3.mqBroker -}}
{{- end -}}
{{- if not (kindIs "invalid" $root.Values.allInOne.s3.mqBrokerPort) -}}
{{- $port = $root.Values.allInOne.s3.mqBrokerPort -}}
{{- end -}}
{{- end -}}
{{- $mode = ternary "auto" (toString $mode | lower) (kindIs "invalid" $mode) -}}
{{- if not (has $mode (list "auto" "true" "false")) -}}
{{- fail (printf "%s must be auto, true or false, not %q" $name $mode) -}}
{{- end -}}
{{- $port = int ($port | default 0) -}}
{{- $runs := false -}}
{{- if and (gt $port 0) (or (eq $mode "true") (and (eq $mode "auto") $root.Values.global.seaweedfs.enableSecurity)) -}}
{{- $runs = true -}}
{{- end -}}
{{- $args := list -}}
{{- if or (eq $mode "false") (eq $port 0) -}}
{{- $args = append $args (printf "-%smq.broker=false" $prefix) -}}
{{- else if eq $mode "true" -}}
{{- $args = append $args (printf "-%smq.broker=true" $prefix) -}}
{{- end -}}
{{- if and $runs (ne $port 17777) -}}
{{- $args = append $args (printf "-%smq.broker.port=%d" $prefix $port) -}}
{{- end -}}
{{- dict "args" (join " " $args) "port" (ternary $port 0 $runs) | toJson -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -784,6 +838,65 @@ on install.
| toJson | sha256sum -}}
{{- end -}}
{{/*
The s3-config-reloader sidecar of the filer and S3 pods. It checks the mounted identities file every
second and sends SIGHUP to SeaweedFS when it changes, so SeaweedFS loads it again without a restart.
It only signals once SeaweedFS listens on its S3 port, because SeaweedFS registers the reload when it
starts serving S3, and it sends one SIGHUP when it starts, which catches changes made while it was not
running. It needs the pod's process namespace to see SeaweedFS, and the same user to signal it, so it
uses the component's image and container security context.
Usage: include "seaweedfs.s3.configReloaderContainer" (dict "root" $ "image" <image> "port" <S3 port>
"resources" <resources> "securityContext" <the component's containerSecurityContext>)
*/}}
{{- define "seaweedfs.s3.configReloaderContainer" -}}
- name: s3-config-reloader
image: {{ .image }}
imagePullPolicy: {{ default "IfNotPresent" .root.Values.global.seaweedfs.imagePullPolicy }}
command:
- /bin/sh
- -c
- |
config_file=/etc/sw/seaweedfs_s3_config
# /proc/net/tcp lists ports in hex, and 0A is the state LISTEN.
s3_port=$(printf '%04X' {{ .port }})
last_hash=""
warned=""
while sleep 1; do
current_hash=$(sha256sum "$config_file" 2>/dev/null | cut -d' ' -f1)
if [ -z "$current_hash" ] || [ "$current_hash" = "$last_hash" ]; then
continue
fi
if ! grep -qE ":$s3_port [0-9A-F]+:[0-9A-F]+ 0A " /proc/net/tcp /proc/net/tcp6 2>/dev/null; then
continue
fi
signalled=""
for process_dir in /proc/[0-9]*; do
if [ "$(cat "$process_dir/comm" 2>/dev/null)" = "weed" ] && kill -HUP "${process_dir#/proc/}" 2>/dev/null; then
echo "S3 config changed (sha256 $current_hash), sent SIGHUP to weed (PID ${process_dir#/proc/})"
signalled=1
fi
done
if [ -n "$signalled" ]; then
last_hash=$current_hash
warned=""
elif [ -z "$warned" ]; then
echo "S3 config changed, but no weed process is visible: the pod must share its process namespace, and the sidecar must run as the same user as SeaweedFS" >&2
warned=1
fi
done
volumeMounts:
- name: config-users
mountPath: /etc/sw
readOnly: true
{{- with .resources }}
resources:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- if .securityContext.enabled }}
securityContext: {{- omit .securityContext "enabled" | toYaml | nindent 4 }}
{{- end }}
{{- end -}}
{{/* Master ConfigMap checksum, ignoring commonLabels so labels do not roll the pods */}}
{{- define "seaweedfs.master.configChecksum" -}}
{{- $context := merge (dict "Values" (omit .Values "commonLabels")) (omit . "Values") -}}
@@ -26,6 +26,9 @@
{{- if and $https (gt (int $https) 0) }}
{{- $ports = append $ports $https }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "allInOne") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- if .Values.allInOne.sftp.enabled }}
{{- $ports = append $ports (.Values.allInOne.sftp.port | default .Values.sftp.port) }}
@@ -62,6 +65,9 @@
{{- if and .Values.filer.s3.httpsPort (gt (int .Values.filer.s3.httpsPort) 0) }}
{{- $ports = append $ports .Values.filer.s3.httpsPort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "filer") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- end }}
{{- $targets = append $targets (dict "component" "filer" "ports" $ports) }}
{{- end }}
@@ -76,6 +82,9 @@
{{- if .Values.s3.lancePort }}
{{- $ports = append $ports .Values.s3.lancePort }}
{{- end }}
{{- with (include "seaweedfs.mqBroker" (list $ "s3") | fromJson).port }}
{{- $ports = append $ports (int .) }}
{{- end }}
{{- if .Values.s3.metricsPort }}
{{- $ports = append $ports .Values.s3.metricsPort }}
{{- end }}
@@ -104,7 +113,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) }}
@@ -120,6 +120,14 @@ stringData:
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
{{- /* The broker beside each S3 gateway serves with this identity and
dials other brokers with it; weed starts that broker only when this
section has a cert and key. Same internal client cert as grpc.s3, which
every pod running a gateway already mounts. */}}
[grpc.msg_broker]
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
# use this for any place needs a grpc client
# i.e., "weed backup|benchmark|filer.copy|filer.replicate|mount|s3|upload"
[grpc.client]
@@ -56,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 }}
@@ -412,6 +412,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ $dir.storageClass }}
{{- with $dir.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ $dir.size }}
@@ -430,6 +433,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ $volume.idx.storageClass }}
{{- with $volume.idx.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ $volume.idx.size }}
@@ -446,6 +452,9 @@ spec:
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: {{ $volume.logs.storageClass }}
{{- with $volume.logs.volumeAttributesClassName }}
volumeAttributesClassName: {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ $volume.logs.size }}
@@ -228,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 }}
@@ -237,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 }}
@@ -272,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 \
@@ -299,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/
@@ -342,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:
@@ -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
@@ -0,0 +1,199 @@
package tests
import (
"fmt"
"os/exec"
"strings"
"testing"
)
const security = "global.seaweedfs.enableSecurity=true"
type brokerGateway struct {
name string
settings []string
kind string
object string
prefix string
broker string
port string
}
var brokerGateways = []brokerGateway{
{"s3", []string{"s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-s3", "", "s3.mqBroker", "s3.mqBrokerPort"},
{"filer.s3", []string{"filer.s3.enabled=true"}, "StatefulSet", "vector-test-seaweedfs-filer", "s3.", "filer.s3.mqBroker", "filer.s3.mqBrokerPort"},
{"allInOne", []string{"allInOne.enabled=true", "allInOne.s3.enabled=true"}, "Deployment", "vector-test-seaweedfs-all-in-one", "", "allInOne.s3.mqBroker", "allInOne.s3.mqBrokerPort"},
}
func firstContainer(workload map[string]interface{}) map[string]interface{} {
return workload["spec"].(map[string]interface{})["template"].(map[string]interface{})["spec"].(map[string]interface{})["containers"].([]interface{})[0].(map[string]interface{})
}
// brokerFlags returns the broker flags of the workload's first container.
func brokerFlags(workload map[string]interface{}) []string {
container := firstContainer(workload)
var words []string
for _, key := range []string{"command", "args"} {
if list, ok := container[key].([]interface{}); ok {
for _, word := range list {
words = append(words, strings.Fields(word.(string))...)
}
}
}
var flags []string
for _, word := range words {
if strings.Contains(word, "mq.broker") {
flags = append(flags, word)
}
}
return flags
}
func namedPort(ports []interface{}, name, field string) int {
for _, port := range ports {
if p := port.(map[string]interface{}); p["name"] == name {
return p[field].(int)
}
}
return 0
}
func policyAllows(policy map[string]interface{}, want int) bool {
rules, _ := policy["spec"].(map[string]interface{})["ingress"].([]interface{})
for _, rule := range rules {
ports, _ := rule.(map[string]interface{})["ports"].([]interface{})
for _, port := range ports {
if port.(map[string]interface{})["port"] == want {
return true
}
}
}
return false
}
// checkBroker asserts the flags, that the broker port is declared and
// admitted exactly when the broker runs, so a broker that runs with its port
// blocked fails, and that no Service ever carries it.
func checkBroker(t *testing.T, gateway brokerGateway, label string, settings []string, wantFlags []string, wantPort int) {
t.Helper()
_, documents := render(t, append(append([]string{"networkPolicy.enabled=true"}, gateway.settings...), settings...)...)
label = fmt.Sprintf("%s %s", gateway.name, label)
workload := findDocument(documents, gateway.kind, gateway.object)
if workload == nil {
t.Fatalf("%s: no %s %s", label, gateway.kind, gateway.object)
}
if got := brokerFlags(workload); strings.Join(got, " ") != strings.Join(wantFlags, " ") {
t.Errorf("%s: broker flags %q, want %q", label, got, wantFlags)
}
containerPorts, _ := firstContainer(workload)["ports"].([]interface{})
if got := namedPort(containerPorts, "swfs-mq-broker", "containerPort"); got != wantPort {
t.Errorf("%s: containerPort %d, want %d", label, got, wantPort)
}
// Clients find brokers through the master and dial the pod, so a Service
// port would only publish the broker through a LoadBalancer or NodePort.
for _, document := range documents {
if document["kind"] != "Service" {
continue
}
for _, port := range document["spec"].(map[string]interface{})["ports"].([]interface{}) {
p := port.(map[string]interface{})
if p["name"] == "swfs-mq-broker" || p["port"] == 17777 || p["targetPort"] == 17777 || (wantPort != 0 && (p["port"] == wantPort || p["targetPort"] == wantPort)) {
t.Errorf("%s: Service %v carries the broker port: %v", label, document["metadata"].(map[string]interface{})["name"], p)
}
}
}
policy := findDocument(documents, "NetworkPolicy", gateway.object)
if policy == nil {
t.Fatalf("%s: no NetworkPolicy %s", label, gateway.object)
}
if wantPort != 0 && !policyAllows(policy, wantPort) {
t.Errorf("%s: NetworkPolicy does not admit broker port %d", label, wantPort)
}
for _, port := range []int{17777, 18887} {
if port != wantPort && policyAllows(policy, port) {
t.Errorf("%s: NetworkPolicy admits %d with no broker on it", label, port)
}
}
}
func TestMqBrokerModes(t *testing.T) {
for _, gateway := range brokerGateways {
on := "-" + gateway.prefix + "mq.broker=true"
off := "-" + gateway.prefix + "mq.broker=false"
port := "-" + gateway.prefix + "mq.broker.port=18887"
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"auto without security", nil, nil, 0},
{"auto with security", []string{security}, nil, 17777},
{"auto with security, custom port", []string{security, gateway.port + "=18887"}, []string{port}, 18887},
{"auto without security, custom port", []string{gateway.port + "=18887"}, nil, 0},
{"true", []string{gateway.broker + "=true"}, []string{on}, 17777},
{"true, custom port", []string{gateway.broker + "=true", gateway.port + "=18887"}, []string{on, port}, 18887},
{"false with security", []string{security, gateway.broker + "=false"}, []string{off}, 0},
{"true, port 0", []string{gateway.broker + "=true", gateway.port + "=0"}, []string{off}, 0},
}
for _, c := range cases {
checkBroker(t, gateway, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
}
func TestMqBrokerAllInOneInherits(t *testing.T) {
allInOne := brokerGateways[2]
cases := []struct {
label string
settings []string
wantFlags []string
wantPort int
}{
{"null inherits s3.mqBroker=true", []string{"s3.mqBroker=true"}, []string{"-mq.broker=true"}, 17777},
{"null inherits s3.mqBroker=false", []string{security, "s3.mqBroker=false"}, []string{"-mq.broker=false"}, 0},
{"explicit auto overrides s3.mqBroker=false", []string{security, "s3.mqBroker=false", "allInOne.s3.mqBroker=auto"}, nil, 17777},
{"null inherits s3.mqBrokerPort", []string{security, "s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
{"explicit port overrides s3.mqBrokerPort=0", []string{security, "s3.mqBrokerPort=0", "allInOne.s3.mqBrokerPort=18887"}, []string{"-mq.broker.port=18887"}, 18887},
}
for _, c := range cases {
checkBroker(t, allInOne, c.label, c.settings, c.wantFlags, c.wantPort)
}
}
func TestMqBrokerTLSOnlyWithSecurity(t *testing.T) {
for _, secured := range []bool{false, true} {
// filer JWT signing writes security.toml without enableSecurity
settings := []string{"s3.enabled=true", "global.seaweedfs.securityConfig.jwtSigning.filerWrite=true"}
if secured {
settings = append(settings, security)
}
_, documents := render(t, settings...)
secret := findDocument(documents, "Secret", "vector-test-seaweedfs-security-config")
if secret == nil {
t.Fatalf("security %v: no security config Secret", secured)
}
toml := secret["stringData"].(map[string]interface{})["security.toml"].(string)
section := "[grpc.msg_broker]\ncert = \"/usr/local/share/ca-certificates/client/tls.crt\"\nkey = \"/usr/local/share/ca-certificates/client/tls.key\""
if got := strings.Contains(toml, section); got != secured {
t.Errorf("security %v: [grpc.msg_broker] with the client cert present = %v\n%s", secured, got, toml)
}
if !secured && strings.Contains(toml, "[grpc.msg_broker]") {
t.Errorf("[grpc.msg_broker] written without enableSecurity")
}
}
}
func TestMqBrokerRejectsUnknownValue(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
output, err := exec.Command("helm", "template", "test", "..", "--set", "s3.enabled=true", "--set", "s3.mqBroker=yes").CombinedOutput()
if err == nil || !strings.Contains(string(output), `s3.mqBroker must be auto, true or false, not "yes"`) {
t.Fatalf("s3.mqBroker=yes accepted: %v %s", err, output)
}
}
+54 -8
View File
@@ -151,12 +151,14 @@ master:
# Enter any extra configuration for master.toml here.
# It may be a multi-line string.
# volumeAttributesClassName (optional) needs Kubernetes 1.34+, or 1.31+ with the VolumeAttributesClass feature gate.
# You may use ANY storage-class, example with local-path-provisioner
# Annotations are optional.
# data:
# type: "persistentVolumeClaim"
# size: "24Ti"
# storageClass: "local-path-provisioner"
# volumeAttributesClassName: "my-attributes-class"
# annotations:
# "key": "value"
#
@@ -184,6 +186,7 @@ master:
# type: "persistentVolumeClaim"
# size: "24Ti"
# storageClass: "local-path-provisioner"
# volumeAttributesClassName: "my-attributes-class"
# annotations:
# "key": "value"
@@ -416,6 +419,7 @@ volume:
# extraArgs: ["-customFlag", "value", "-anotherFlag"]
extraArgs: []
# volumeAttributesClassName (optional) needs Kubernetes 1.34+, or 1.31+ with the VolumeAttributesClass feature gate.
# For each data disk you may use ANY storage-class, example with local-path-provisioner
# Annotations are optional.
# dataDirs:
@@ -423,6 +427,7 @@ volume:
# type: "persistentVolumeClaim"
# size: "24Ti"
# storageClass: "local-path-provisioner"
# volumeAttributesClassName: "my-attributes-class"
# annotations:
# "key": "value"
# maxVolumes: 0 # If set to zero on non-windows OS, the limit will be auto configured. (default "7")
@@ -477,6 +482,7 @@ volume:
# type: "persistentVolumeClaim"
# size: "20Gi"
# storageClass: "local-path-provisioner"
# volumeAttributesClassName: "my-attributes-class"
#
# or
#
@@ -799,12 +805,16 @@ filer:
storage: 25Gi
# storageClass is the class of storage which defaults to null (the Kube cluster will pick the default).
storageClass: null
# volumeAttributesClassName is the VolumeAttributesClass of the enablePVC claim; null leaves it unset.
volumeAttributesClassName: null
# volumeAttributesClassName (optional) needs Kubernetes 1.34+, or 1.31+ with the VolumeAttributesClass feature gate.
# You may use ANY storage-class, example with local-path-provisioner
# Annotations are optional.
# data:
# type: "persistentVolumeClaim"
# size: "24Ti"
# storageClass: "local-path-provisioner"
# volumeAttributesClassName: "my-attributes-class"
# annotations:
# "key": "value"
#
@@ -828,6 +838,7 @@ filer:
# type: "persistentVolumeClaim"
# size: "24Ti"
# storageClass: "local-path-provisioner"
# volumeAttributesClassName: "my-attributes-class"
# annotations:
# "key": "value"
@@ -856,6 +867,11 @@ filer:
extraVolumes: ""
extraVolumeMounts: ""
# Share one process namespace between the containers of the filer pod, so a
# sidecar can see and signal the filer process, for example to reload its
# configuration with SIGHUP. The filer is then no longer PID 1.
shareProcessNamespace: false
# Labels to be added to the filer pods
podLabels: {}
@@ -1080,6 +1096,9 @@ filer:
port: 8333
# add additional https port
httpsPort: 0
# Message queue broker beside the gateway, see s3.mqBroker
mqBroker: auto
mqBrokerPort: 17777
# Suffix of the host name, {bucket}.{domainName}
domainName: ""
# Seconds the gateway keeps serving after SIGTERM while its health checks
@@ -1091,6 +1110,13 @@ filer:
# set to the name of an existing kubernetes Secret with the s3 json config file
# should have a secret key called seaweedfs_s3_config with an inline json configure
existingConfigSecret: null
# Reload the identities file without restarting the filer: a sidecar sends
# SIGHUP to SeaweedFS when kubelet updates the mounted config Secret, and the
# pod no longer restarts when the content of existingConfigSecret changes.
# Needs enableAuth, and turns on shareProcessNamespace. See the README.
configReloader:
enabled: false
resources: {}
# To provide explicit credentials for the S3 gateway, set them under
# the top-level s3.credentials key (not filer.s3.credentials).
# The s3-secret.yaml template only reads from .Values.s3.credentials.
@@ -1161,14 +1187,28 @@ 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
# Message queue broker beside the gateway: auto runs it only with
# global.seaweedfs.enableSecurity, which gives it mTLS; true runs it either
# way, without TLS when security is off; false never does.
mqBroker: auto
# Its gRPC port, 0 turns it off. Clients and other brokers find the broker
# through the master and dial the pod IP, so no Service carries this port.
mqBrokerPort: 17777
loggingOverrideLevel: null
# 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
# should have a secret key called seaweedfs_s3_config with an inline json config
existingConfigSecret: null
# Reload the identities file without restarting the gateway: a sidecar sends
# SIGHUP to SeaweedFS when kubelet updates the mounted config Secret, and the
# pod no longer restarts when the content of existingConfigSecret changes.
# Needs enableAuth, and turns on shareProcessNamespace. See the README.
configReloader:
enabled: false
resources: {}
# Optionally provide explicit credentials for the S3 gateway.
# When set, these are used in the generated s3 secret instead of
# auto-generating random credentials.
@@ -1228,6 +1268,11 @@ s3:
extraVolumes: ""
extraVolumeMounts: ""
# Share one process namespace between the containers of the s3 pod, so a
# sidecar can see and signal the gateway process, for example to reload its
# configuration with SIGHUP. The gateway is then no longer PID 1.
shareProcessNamespace: false
# Labels to be added to the s3 pods
podLabels: {}
@@ -1609,10 +1654,12 @@ admin:
extraArgs: []
# Storage configuration
# volumeAttributesClassName (optional) needs Kubernetes 1.34+, or 1.31+ with the VolumeAttributesClass feature gate.
data:
type: "emptyDir" # Options: "hostPath", "persistentVolumeClaim", "emptyDir", "existingClaim"
size: "10Gi"
storageClass: ""
volumeAttributesClassName: ""
hostPathPrefix: /storage
claimName: ""
annotations: {}
@@ -1621,6 +1668,7 @@ admin:
type: "emptyDir" # Options: "hostPath", "persistentVolumeClaim", "emptyDir", "existingClaim"
size: "5Gi"
storageClass: ""
volumeAttributesClassName: ""
hostPathPrefix: /storage
claimName: ""
annotations: {}
@@ -1774,8 +1822,6 @@ vector:
port: 8090
metricsPort: 0
masters: ""
readCacheMB: 512
nprobes: null
extraArgs: []
extraEnvironmentVars: {}
podLabels: {}
@@ -1832,7 +1878,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
@@ -1841,9 +1887,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
@@ -1853,7 +1896,7 @@ worker:
# Worker job types - categories or comma-separated list of names/aliases
# Categories: all, default, heavy
# default: vacuum, volume_balance, ec_balance, admin_script
# heavy: erasure_coding, iceberg_maintenance
# heavy: erasure_coding, iceberg_maintenance, mq_topic_table
# all: every registered job type
# Examples: "all", "default", "heavy", "default,iceberg" (default+iceberg), "vacuum,volume_balance"
# Refer: https://github.com/seaweedfs/seaweedfs/wiki/Worker
@@ -2027,6 +2070,8 @@ allInOne:
enabled: false # Whether to enable S3 gateway
port: null # S3 gateway port (null inherits from s3.port)
httpsPort: null # S3 gateway HTTPS port (null inherits from s3.httpsPort)
mqBroker: null # Message queue broker: auto, true or false (null inherits from s3.mqBroker)
mqBrokerPort: null # Message queue broker gRPC port (null inherits from s3.mqBrokerPort, 0 turns the broker off)
domainName: null # Suffix of the host name (null inherits from s3.domainName)
enableAuth: false # Enable user & permission to S3
# Set to the name of an existing kubernetes Secret with the s3 json config file
@@ -2121,6 +2166,7 @@ allInOne:
claimName: seaweedfs-data-pvc # Name of the PVC to use (for existingClaim type)
size: null # Size of the PVC (null defaults to 10Gi for persistentVolumeClaim type)
storageClass: null # Storage class for the PVC (null uses cluster default)
volumeAttributesClassName: null # VolumeAttributesClass for the PVC; needs Kubernetes 1.34+, or 1.31+ with the feature gate
# accessModes for the PVC. Default is ["ReadWriteOnce"].
# For multi-replica deployments, use ["ReadWriteMany"] with a compatible storage class.
accessModes: []
+1025 -1019
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

@@ -42,12 +42,26 @@ public class FileChunkManifest {
// avoid deprecated chunk.getFileId()
resolvedChunks.add(t.toBuilder().setFileId(FilerClient.toFileId(t.getFid())).build());
}
dataChunks.addAll(resolveChunkManifest(filerClient, resolvedChunks));
dataChunks.addAll(resolveChunkManifest(filerClient, cutToManifestSpan(chunk, resolvedChunks)));
}
return dataChunks;
}
// A truncate may have shortened a manifest and left the chunks it holds whole.
static List<FilerProto.FileChunk> cutToManifestSpan(FilerProto.FileChunk manifest, List<FilerProto.FileChunk> held) {
long end = manifest.getOffset() + manifest.getSize();
List<FilerProto.FileChunk> cut = new ArrayList<>(held.size());
for (FilerProto.FileChunk chunk : held) {
if (chunk.getOffset() + chunk.getSize() <= end) {
cut.add(chunk);
} else if (chunk.getOffset() < end) {
cut.add(chunk.toBuilder().setSize(end - chunk.getOffset()).build());
}
}
return cut;
}
private static byte[] fetchChunk(final FilerClient filerClient, FilerProto.FileChunk chunk) throws IOException {
String vid = "" + chunk.getFid().getVolumeId();
@@ -0,0 +1,102 @@
package seaweedfs.client;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;
// Credentials for a filer's own HTTP port: [filer.basic_auth], [jwt.filer_signing] and
// [jwt.filer_signing.read]. Each FilerClient starts from its own copy of the security.toml values.
public final class FilerCredentials {
private static final long DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS = 10;
private static final long DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS = 60;
private volatile String basicAuthUser = "";
private volatile String basicAuthPassword = "";
private volatile String basicAuthHeaderValue;
private volatile String signingKey = "";
private volatile long signingExpiresAfterSeconds = DEFAULT_SIGNING_EXPIRES_AFTER_SECONDS;
private volatile String readSigningKey = "";
private volatile long readSigningExpiresAfterSeconds = DEFAULT_READ_SIGNING_EXPIRES_AFTER_SECONDS;
public FilerCredentials() {
}
public FilerCredentials(FilerCredentials other) {
synchronized (other) {
basicAuthUser = other.basicAuthUser;
basicAuthPassword = other.basicAuthPassword;
basicAuthHeaderValue = other.basicAuthHeaderValue;
signingKey = other.signingKey;
signingExpiresAfterSeconds = other.signingExpiresAfterSeconds;
readSigningKey = other.readSigningKey;
readSigningExpiresAfterSeconds = other.readSigningExpiresAfterSeconds;
}
}
// A null argument keeps the current value. Like the filer, an empty password turns
// Basic Auth off and an empty user is allowed.
public synchronized void setBasicAuth(String user, String password) {
if (user != null) {
basicAuthUser = user;
}
if (password != null) {
basicAuthPassword = password;
}
basicAuthHeaderValue = basicAuthPassword.isEmpty() ? null
: FilerSecurityContext.encodeBasicAuth(basicAuthUser, basicAuthPassword);
}
// A null key or expiresAfterSeconds <= 0 keeps the current value; an empty key turns signing off.
public synchronized void setJwtSigningKey(String key, long expiresAfterSeconds) {
if (key != null) {
signingKey = key;
}
if (expiresAfterSeconds > 0) {
signingExpiresAfterSeconds = expiresAfterSeconds;
}
}
// Same as setJwtSigningKey, for the read key.
public synchronized void setJwtReadSigningKey(String key, long expiresAfterSeconds) {
if (key != null) {
readSigningKey = key;
}
if (expiresAfterSeconds > 0) {
readSigningExpiresAfterSeconds = expiresAfterSeconds;
}
}
// Returns the Authorization header value for an HTTP request addressed to the filer:
// a filer JWT for the access level when its key is set, else [filer.basic_auth], else
// [basic_auth]; null when none is configured. The filer reads GET and HEAD with the read key.
public String getAuthorizationHeaderValue(boolean isWrite) {
String key = isWrite ? signingKey : readSigningKey;
if (!key.isEmpty()) {
return "BEARER " + genJwtForFilerServer(key.getBytes(StandardCharsets.UTF_8),
isWrite ? signingExpiresAfterSeconds : readSigningExpiresAfterSeconds);
}
String basicAuth = basicAuthHeaderValue;
if (basicAuth != null) {
return basicAuth;
}
return FilerSecurityContext.getBasicAuthHeaderValue();
}
// Mints an HS256 token with only an "exp" claim, like security.GenJwtForFilerServer.
static String genJwtForFilerServer(byte[] signingKey, long expiresAfterSeconds) {
Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
long exp = System.currentTimeMillis() / 1000 + expiresAfterSeconds;
String signingInput = encoder.encodeToString("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8))
+ "." + encoder.encodeToString(("{\"exp\":" + exp + "}").getBytes(StandardCharsets.UTF_8));
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
return signingInput + "." + encoder.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("cannot sign filer jwt", e);
}
}
}
@@ -50,6 +50,7 @@ public class FilerGrpcClient {
private String replication = "";
private int volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT;
private String filerAddress;
private final FilerCredentials filerCredentials = new FilerCredentials(FilerSecurityContext.getFilerCredentials());
public FilerGrpcClient(String host, int port, int grpcPort, String cn) {
this(host, port, grpcPort, cn, sslContext);
@@ -154,6 +155,11 @@ public class FilerGrpcClient {
return SeaweedFilerGrpc.newFutureStub(getChannel());
}
// Credentials for this client's requests to the filer's HTTP port; changes affect only this client.
public FilerCredentials getFilerCredentials() {
return filerCredentials;
}
public void setAccessVolumeServerDirectly() {
this.volumeServerAccess = VOLUME_SERVER_ACCESS_DIRECT;
}
@@ -183,9 +189,18 @@ public class FilerGrpcClient {
case VOLUME_SERVER_ACCESS_PUBLIC_URL:
return String.format("%s://%s/%s", protocol, publicUrl, chunkId);
case VOLUME_SERVER_ACCESS_FILER_PROXY:
return String.format("%s://%s/?proxyChunkId=%s", protocol, this.filerAddress, chunkId);
return proxyChunkUrlPrefix() + chunkId;
default:
return String.format("%s://%s/%s", protocol, url, chunkId);
}
}
// Reports whether a chunk URL addresses this client's filer chunk proxy rather than a volume server.
public boolean isProxyChunkUrl(String url) {
return isAccessVolumeServerByFilerProxy() && url != null && url.startsWith(proxyChunkUrlPrefix());
}
private String proxyChunkUrlPrefix() {
return String.format("%s://%s/?proxyChunkId=", protocol, this.filerAddress);
}
}
@@ -43,6 +43,8 @@ public abstract class FilerSecurityContext extends SslContext {
// volume/proxy HTTP requests. Precomputed so per-chunk requests don't re-encode.
private static volatile String basicAuthHeaderValue;
private static final FilerCredentials filerCredentials = new FilerCredentials();
static {
String securityFileName = "security.toml";
@@ -64,6 +66,11 @@ public abstract class FilerSecurityContext extends SslContext {
basicAuthHeaderValue = computeBasicAuthHeaderValue(
toml.getString("basic_auth.username"), toml.getString("basic_auth.password"));
filerCredentials.setBasicAuth(toml.getString("filer.basic_auth.user"), toml.getString("filer.basic_auth.password"));
filerCredentials.setJwtSigningKey(toml.getString("jwt.filer_signing.key"),
toml.getLong("jwt.filer_signing.expires_after_seconds", 0L));
filerCredentials.setJwtReadSigningKey(toml.getString("jwt.filer_signing.read.key"),
toml.getLong("jwt.filer_signing.read.expires_after_seconds", 0L));
grpcTrustCertCollectionFilePath = toml.getString("grpc.ca");
logger.debug("loading gRPC ca from {}", grpcTrustCertCollectionFilePath);
@@ -86,7 +93,7 @@ public abstract class FilerSecurityContext extends SslContext {
}
}
if (toml.getBoolean("https.client.enabled")) {
if (toml.getBoolean("https.client.enabled", false)) {
httpTrustCertCollectionFilePath = toml.getString("https.client.ca");
logger.debug("loading HTTP ca from {}", httpTrustCertCollectionFilePath);
httpClientCertChainFilePath = toml.getString("https.client.cert");
@@ -146,11 +153,20 @@ public abstract class FilerSecurityContext extends SslContext {
return basicAuthHeaderValue;
}
// The filer credentials read from security.toml; each FilerClient copies them.
static FilerCredentials getFilerCredentials() {
return filerCredentials;
}
private static String computeBasicAuthHeaderValue(String username, String password) {
if (Strings.isNullOrEmpty(username)) {
return null;
}
String credentials = username + ":" + (password == null ? "" : password);
return encodeBasicAuth(username, password == null ? "" : password);
}
static String encodeBasicAuth(String username, String password) {
String credentials = username + ":" + password;
return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
}
@@ -136,7 +136,7 @@ public class SeaweedRead {
for (FilerProto.Location location : locations.getLocationsList()) {
String url = filerClient.getChunkUrl(chunkView.fileId, location.getUrl(), location.getPublicUrl());
try {
byte[] fetched = doFetchOneFullChunkData(chunkView, url);
byte[] fetched = doFetchOneFullChunkData(filerClient, chunkView, url);
// An empty (or null) body for a chunk we are reading from is never
// valid; treat it as a transient failure so the retry loop tries
// another location and backs off, rather than caching an empty chunk.
@@ -171,15 +171,19 @@ public class SeaweedRead {
}
private static byte[] doFetchOneFullChunkData(ChunkView chunkView, String url) throws IOException {
private static byte[] doFetchOneFullChunkData(FilerClient filerClient, ChunkView chunkView, String url) throws IOException {
HttpGet request = new HttpGet(url);
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");
String basicAuthHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (basicAuthHeader != null) {
request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader);
String authHeader = FilerSecurityContext.getBasicAuthHeaderValue();
if (filerClient.isProxyChunkUrl(url)) {
authHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(false);
request.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG);
}
if (authHeader != null) {
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
byte[] data = null;
@@ -187,6 +191,11 @@ public class SeaweedRead {
CloseableHttpResponse response = SeaweedUtil.getClosableHttpClient().execute(request);
try {
int status = response.getStatusLine().getStatusCode();
if (status / 100 != 2) {
throw new IOException("fetch " + url + ": " + response.getStatusLine());
}
HttpEntity entity = response.getEntity();
Header contentEncodingHeader = entity.getContentEncoding();
@@ -1,5 +1,6 @@
package seaweedfs.client;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
@@ -90,4 +91,7 @@ public class SeaweedUtil {
}
return host + ":" + port;
}
// Redirects would carry the filer credential to the redirect target.
static final RequestConfig PROXY_CHUNK_REQUEST_CONFIG = RequestConfig.custom().setRedirectsEnabled(false).build();
}
@@ -135,7 +135,7 @@ public class SeaweedWrite {
cipherKeyString = ByteString.copyFrom(cipherKey);
}
String etag = multipartUpload(targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey);
String etag = multipartUpload(filerClient, targetUrl, auth, bytes, bytesOffset, bytesLength, cipherKey);
return FilerProto.FileChunk.newBuilder()
.setFileId(fileId)
@@ -167,7 +167,8 @@ public class SeaweedWrite {
}
}
private static String multipartUpload(String targetUrl,
private static String multipartUpload(FilerClient filerClient,
String targetUrl,
String auth,
final byte[] bytes,
final long bytesOffset, final long bytesLength,
@@ -193,7 +194,14 @@ public class SeaweedWrite {
}
HttpPost post = new HttpPost(targetUrl);
if (auth != null && auth.length() != 0) {
String filerAuthHeader = null;
if (filerClient.isProxyChunkUrl(targetUrl)) {
filerAuthHeader = filerClient.getFilerCredentials().getAuthorizationHeaderValue(true);
post.setConfig(SeaweedUtil.PROXY_CHUNK_REQUEST_CONFIG);
}
if (filerAuthHeader != null) {
post.addHeader("Authorization", filerAuthHeader);
} else if (auth != null && auth.length() != 0) {
// Volume JWT and Basic Auth both use the Authorization header; the JWT wins
// when present. Front the volume with a JWT-free path to use Basic Auth here.
post.addHeader("Authorization", "BEARER " + auth);
@@ -556,9 +556,15 @@ message AtomicRenameEntryRequest {
// already exists. Lets a caller that authorized the rename without delete
// access on an absent target stay safe if one is created concurrently.
bool fail_if_target_exists = 6;
// Set on a rename forwarded to the source's write owner, so it is not
// forwarded again.
bool is_moved = 7;
}
message AtomicRenameEntryResponse {
// Set for a forwarded rename: the owner's metadata log position of
// the rename's last event.
int64 ts_ns = 1;
}
message StreamRenameEntryRequest {
@@ -567,6 +573,9 @@ message StreamRenameEntryRequest {
string new_directory = 3;
string new_name = 4;
repeated int32 signatures = 5;
// Set on a rename forwarded to the source's write owner, so it is not
// forwarded again.
bool is_moved = 6;
}
message StreamRenameEntryResponse {
string directory = 1;
@@ -681,6 +690,7 @@ message GetFilerConfigurationResponse {
string filer_group = 13;
int32 major_version = 14;
int32 minor_version = 15;
string digest = 16; // "md5" or "sha256": the hash behind ETags and chunk digests
}
message SubscribeMetadataRequest {
@@ -0,0 +1,43 @@
package seaweedfs.client;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FileChunkManifestTest {
private static FilerProto.FileChunk chunk(int volumeId, long key, long offset, long size) {
return FilerProto.FileChunk.newBuilder()
.setFid(FilerProto.FileId.newBuilder().setVolumeId(volumeId).setFileKey(key).setCookie(1))
.setOffset(offset)
.setSize(size)
.setModifiedTsNs(1)
.build();
}
@Test
public void testCutToManifestSpanCutsAShortenedManifest() throws IOException {
List<FilerProto.FileChunk> held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100), chunk(9, 3, 200, 100));
FilerProto.FileChunk manifest = chunk(9, 4, 0, 150).toBuilder().setIsChunkManifest(true).build();
List<FilerProto.FileChunk> cut = FileChunkManifest.cutToManifestSpan(manifest, held);
Assert.assertEquals(2, cut.size());
Assert.assertEquals(held.get(0), cut.get(0));
Assert.assertEquals(100, cut.get(1).getOffset());
Assert.assertEquals(50, cut.get(1).getSize());
Assert.assertEquals(100, held.get(1).getSize());
List<SeaweedRead.VisibleInterval> visibles = ReadChunks.readResolvedChunks(cut);
Assert.assertEquals(150, visibles.get(visibles.size() - 1).stop);
}
@Test
public void testCutToManifestSpanLeavesAWholeManifestAlone() {
List<FilerProto.FileChunk> held = Arrays.asList(chunk(9, 1, 0, 100), chunk(9, 2, 100, 100));
FilerProto.FileChunk manifest = chunk(9, 4, 0, 200).toBuilder().setIsChunkManifest(true).build();
Assert.assertEquals(held, FileChunkManifest.cutToManifestSpan(manifest, held));
}
}
@@ -0,0 +1,244 @@
package seaweedfs.client;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class FilerJwtTest {
private FilerCredentials credentials;
@Before
public void clearCredentials() {
FilerSecurityContext.setBasicAuth(null, null);
credentials = new FilerCredentials();
}
@After
public void clearProxyBasicAuth() {
FilerSecurityContext.setBasicAuth(null, null);
}
@Test
public void filerJwtIsSignedHs256WithExp() throws Exception {
long before = System.currentTimeMillis() / 1000;
String token = FilerCredentials.genJwtForFilerServer("write-key".getBytes(StandardCharsets.UTF_8), 10);
long after = System.currentTimeMillis() / 1000;
String[] parts = token.split("\\.");
assertEquals(3, parts.length);
assertEquals("{\"alg\":\"HS256\",\"typ\":\"JWT\"}", decode(parts[0]));
long exp = exp(decode(parts[1]));
assertTrue(exp >= before + 10 && exp <= after + 10);
assertEquals(sign("write-key", parts[0] + "." + parts[1]), parts[2]);
assertFalse(token.contains("="));
}
@Test
public void noCredentialsMeansNoFilerHeader() {
assertNull(credentials.getAuthorizationHeaderValue(true));
assertNull(credentials.getAuthorizationHeaderValue(false));
}
@Test
public void accessLevelPicksItsSigningKey() throws Exception {
credentials.setJwtSigningKey("write-key", 0);
credentials.setJwtReadSigningKey("read-key", 0);
long now = System.currentTimeMillis() / 1000;
String[] write = bearer(credentials.getAuthorizationHeaderValue(true));
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
assertTrue(exp(decode(write[1])) - now <= 11);
String[] read = bearer(credentials.getAuthorizationHeaderValue(false));
assertEquals(sign("read-key", read[0] + "." + read[1]), read[2]);
assertTrue(exp(decode(read[1])) - now >= 60);
}
@Test
public void basicAuthCoversAccessLevelsWithoutKey() {
FilerSecurityContext.setBasicAuth("proxy", "proxy-pass");
assertEquals(FilerSecurityContext.getBasicAuthHeaderValue(),
credentials.getAuthorizationHeaderValue(false));
credentials.setBasicAuth("filer", "filer-pass");
String filerBasic = "Basic " + Base64.getEncoder()
.encodeToString("filer:filer-pass".getBytes(StandardCharsets.UTF_8));
assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false));
credentials.setJwtSigningKey("write-key", 5);
assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("BEARER "));
assertEquals(filerBasic, credentials.getAuthorizationHeaderValue(false));
}
@Test
public void filerBasicAuthFollowsThePassword() {
credentials.setBasicAuth("filer", "");
assertNull(credentials.getAuthorizationHeaderValue(false));
credentials.setBasicAuth("", "only-pass");
assertEquals("Basic " + Base64.getEncoder().encodeToString(":only-pass".getBytes(StandardCharsets.UTF_8)),
credentials.getAuthorizationHeaderValue(false));
}
@Test
public void nullKeepsTheCurrentValue() throws Exception {
credentials.setBasicAuth("filer", "old-pass");
credentials.setBasicAuth(null, "new-pass");
assertEquals("Basic " + Base64.getEncoder().encodeToString("filer:new-pass".getBytes(StandardCharsets.UTF_8)),
credentials.getAuthorizationHeaderValue(false));
credentials.setJwtSigningKey("write-key", 0);
credentials.setJwtSigningKey(null, 300);
long now = System.currentTimeMillis() / 1000;
String[] write = bearer(credentials.getAuthorizationHeaderValue(true));
assertEquals(sign("write-key", write[0] + "." + write[1]), write[2]);
assertTrue(exp(decode(write[1])) - now >= 300);
credentials.setJwtSigningKey("", 0);
assertTrue(credentials.getAuthorizationHeaderValue(true).startsWith("Basic "));
}
@Test
public void copiesSignIndependently() throws Exception {
credentials.setJwtSigningKey("shared-key", 0);
FilerCredentials a = new FilerCredentials(credentials);
FilerCredentials b = new FilerCredentials(credentials);
b.setJwtSigningKey("b-key", 0);
String[] fromA = bearer(a.getAuthorizationHeaderValue(true));
String[] fromB = bearer(b.getAuthorizationHeaderValue(true));
assertEquals(sign("shared-key", fromA[0] + "." + fromA[1]), fromA[2]);
assertEquals(sign("b-key", fromB[0] + "." + fromB[1]), fromB[2]);
String[] fromDefaults = bearer(credentials.getAuthorizationHeaderValue(true));
assertEquals(sign("shared-key", fromDefaults[0] + "." + fromDefaults[1]), fromDefaults[2]);
}
@Test
public void onlyFilerProxyUrlsAreFilerRequests() throws Exception {
Server filerGrpc = startFilerGrpc();
FilerClient filerClient = new FilerClient("127.0.0.1", 8888, filerGrpc.getPort(), "");
try {
String proxyUrl = "http://127.0.0.1:8888/?proxyChunkId=3,01637037d6";
assertFalse(filerClient.isProxyChunkUrl(proxyUrl));
filerClient.setAccessVolumeServerByFilerProxy();
assertEquals(proxyUrl, filerClient.getChunkUrl("3,01637037d6", "volume:8080", "volume:8080"));
assertTrue(filerClient.isProxyChunkUrl(proxyUrl));
assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/3,01637037d6"));
assertFalse(filerClient.isProxyChunkUrl("http://volume:8080/?proxyChunkId=/3,01637037d6"));
assertFalse(filerClient.isProxyChunkUrl("http://127.0.0.1:8888.example/?proxyChunkId=3,01637037d6"));
assertFalse(filerClient.isProxyChunkUrl(null));
} finally {
filerClient.shutdown();
filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}
@Test
public void proxyChunkReadDoesNotFollowRedirects() throws Exception {
AtomicInteger targetHits = new AtomicInteger();
HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
target.createContext("/", exchange -> {
targetHits.incrementAndGet();
respond(exchange, 200, "leaked");
});
List<String> filerAuth = new CopyOnWriteArrayList<>();
HttpServer filer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
filer.createContext("/", exchange -> {
filerAuth.add(exchange.getRequestHeaders().getFirst("Authorization"));
if (filerAuth.size() == 1) {
exchange.getResponseHeaders().set("Location", "http://127.0.0.1:" + target.getAddress().getPort() + "/");
respond(exchange, 302, "");
} else {
respond(exchange, 200, "chunk");
}
});
Server filerGrpc = startFilerGrpc();
target.start();
filer.start();
FilerClient filerClient = new FilerClient("127.0.0.1", filer.getAddress().getPort(), filerGrpc.getPort(), "");
try {
filerClient.setAccessVolumeServerByFilerProxy();
filerClient.getFilerCredentials().setJwtReadSigningKey("read-key", 0);
FilerProto.Locations locations = FilerProto.Locations.newBuilder()
.addLocations(FilerProto.Location.newBuilder().setUrl("volume:8080")).build();
byte[] data = SeaweedRead.doFetchFullChunkData(filerClient,
new SeaweedRead.ChunkView("3,01637037d6", 0, 5, 0, true, null, false), locations);
assertEquals("chunk", new String(data, StandardCharsets.UTF_8));
assertEquals(0, targetHits.get());
assertEquals(2, filerAuth.size());
assertTrue(filerAuth.get(0).startsWith("BEARER "));
} finally {
filerClient.shutdown();
filerGrpc.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
filer.stop(0);
target.stop(0);
}
}
private static Server startFilerGrpc() throws IOException {
return ServerBuilder.forPort(0).addService(new SeaweedFilerGrpc.SeaweedFilerImplBase() {
@Override
public void getFilerConfiguration(FilerProto.GetFilerConfigurationRequest request,
StreamObserver<FilerProto.GetFilerConfigurationResponse> observer) {
observer.onNext(FilerProto.GetFilerConfigurationResponse.getDefaultInstance());
observer.onCompleted();
}
}).build().start();
}
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
}
private static String[] bearer(String header) {
assertTrue(header.startsWith("BEARER "));
return header.substring("BEARER ".length()).split("\\.");
}
private static String decode(String part) {
return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8);
}
private static long exp(String payload) {
Matcher m = Pattern.compile("^\\{\"exp\":(\\d+)\\}$").matcher(payload);
assertTrue(payload, m.matches());
return Long.parseLong(m.group(1));
}
private static String sign(String key, String signingInput) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8)));
}
}
+69
View File
@@ -149,6 +149,75 @@ The test suite covers:
hadoop fs -put local.txt seaweedfs://localhost:8888/test/
```
### Secured filer
With `fs.seaweed.volume.server.access` set to `filerProxy`, chunk reads and writes go to the
filer's HTTP port, so they need the filer's HTTP credentials. The client signs a filer JWT
when it has the filer's `jwt.filer_signing` key (writes) or
`jwt.filer_signing.read` key (reads), and otherwise sends the `[filer.basic_auth]`
credentials. These credentials are sent only to the filer, never to volume servers. In `direct`
and `publicUrl` modes chunk requests go straight to volume servers, so the filer's HTTP
credentials are not used; writes carry the volume token from the volume assignment as before.
gRPC mTLS comes from the `[grpc]` section as before, but it does not cover these HTTP chunk requests:
to keep the credentials off plain HTTP, serve the filer HTTP port over HTTPS (`[https.filer]`
on the filer) and enable `[https.client]` here. The client checks the certificate chain but
not the host name, so set `https.client.ca` to a CA that issues certificates only for your
SeaweedFS servers.
`security.toml` (read from `./`, `~/.seaweedfs/` or `/etc/seaweedfs/`), using the filer's
own values:
```toml
[jwt.filer_signing]
key = "<filer write key>"
[jwt.filer_signing.read]
key = "<filer read key>"
# or, for a filer with Basic Auth
[filer.basic_auth]
user = "<user>"
password = "<password>"
[grpc]
ca = "/etc/seaweedfs/ca.crt"
[grpc.client]
cert = "/etc/seaweedfs/client.crt"
key = "/etc/seaweedfs/client.key"
[https.client]
enabled = true
ca = "/etc/seaweedfs/ca.crt"
cert = "/etc/seaweedfs/client.crt"
key = "/etc/seaweedfs/client.key"
```
The same values can be set in `core-site.xml`. Each option overrides only its own
`security.toml` value (for example, a password alone keeps the `security.toml` user), and
applies only to that filesystem. The secrets can also come from a Hadoop credential provider:
```xml
<property>
<name>fs.seaweed.volume.server.access</name>
<value>filerProxy</value>
</property>
<property>
<name>fs.seaweed.filer.jwt.signing.key</name>
<value>filer write key</value>
</property>
<property>
<name>fs.seaweed.filer.jwt.signing.read.key</name>
<value>filer read key</value>
</property>
<!-- token lifetimes, defaults 10 and 60 seconds:
fs.seaweed.filer.jwt.signing.expires.after.seconds
fs.seaweed.filer.jwt.signing.read.expires.after.seconds -->
<!-- or Basic Auth:
fs.seaweed.filer.basic.auth.user
fs.seaweed.filer.basic.auth.password -->
```
## Continuous Integration
For CI environments, tests can be run in two modes:
@@ -10,6 +10,7 @@ import org.apache.hadoop.util.Progressable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import seaweedfs.client.FilerProto;
import seaweedfs.client.FilerCredentials;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -30,6 +31,12 @@ public class SeaweedFileSystem extends FileSystem {
public static final String FS_SEAWEED_VOLUME_SERVER_ACCESS = "fs.seaweed.volume.server.access";
public static final int FS_SEAWEED_DEFAULT_BUFFER_SIZE = 4 * 1024 * 1024;
public static final String FS_SEAWEED_FILER_CN = "fs.seaweed.filer.cn";
public static final String FS_SEAWEED_FILER_BASIC_AUTH_USER = "fs.seaweed.filer.basic.auth.user";
public static final String FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD = "fs.seaweed.filer.basic.auth.password";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_KEY = "fs.seaweed.filer.jwt.signing.key";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES = "fs.seaweed.filer.jwt.signing.expires.after.seconds";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY = "fs.seaweed.filer.jwt.signing.read.key";
public static final String FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES = "fs.seaweed.filer.jwt.signing.read.expires.after.seconds";
private static final Logger LOG = LoggerFactory.getLogger(SeaweedFileSystem.class);
@@ -69,6 +76,21 @@ public class SeaweedFileSystem extends FileSystem {
seaweedFileSystemStore = new SeaweedFileSystemStore(host, port, grpcPort, cn, conf);
}
// Each option set here overrides only its own [filer.basic_auth] or [jwt.filer_signing] value of security.toml.
static void applyFilerCredentials(Configuration conf, FilerCredentials credentials) throws IOException {
credentials.setBasicAuth(conf.get(FS_SEAWEED_FILER_BASIC_AUTH_USER),
secret(conf, FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD));
credentials.setJwtSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_KEY),
conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 0));
credentials.setJwtReadSigningKey(secret(conf, FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY),
conf.getLong(FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 0));
}
private static String secret(Configuration conf, String name) throws IOException {
char[] value = conf.getPassword(name);
return value == null ? null : new String(value);
}
@Override
public void close() throws IOException {
super.close();
@@ -27,9 +27,15 @@ public class SeaweedFileSystemStore {
private FilerClient filerClient;
private Configuration conf;
public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) {
public SeaweedFileSystemStore(String host, int port, int grpcPort, String cn, Configuration conf) throws IOException {
filerClient = new FilerClient(host, port, grpcPort, cn);
this.conf = conf;
try {
SeaweedFileSystem.applyFilerCredentials(conf, filerClient.getFilerCredentials());
} catch (IOException | RuntimeException e) {
close();
throw e;
}
String volumeServerAccessMode = this.conf.get(FS_SEAWEED_VOLUME_SERVER_ACCESS, "direct");
if (volumeServerAccessMode.equals("publicUrl")) {
filerClient.setAccessVolumeServerByPublicUrl();
@@ -4,6 +4,12 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.junit.Before;
import org.junit.Test;
import seaweedfs.client.FilerCredentials;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import static org.junit.Assert.*;
@@ -87,4 +93,57 @@ public class SeaweedFileSystemConfigTest {
// Test default port constant
assertEquals(8888, SeaweedFileSystem.FS_SEAWEED_DEFAULT_PORT);
}
@Test
public void testFilerCredentialsFromConfiguration() throws Exception {
FilerCredentials credentials = new FilerCredentials();
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_USER, "alice");
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "s3cret");
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
String basic = "Basic " + Base64.getEncoder().encodeToString("alice:s3cret".getBytes(StandardCharsets.UTF_8));
assertEquals(basic, credentials.getAuthorizationHeaderValue(true));
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_KEY, "write-key");
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_EXPIRES, 120);
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
long now = System.currentTimeMillis() / 1000;
assertTrue(signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now >= 119);
assertEquals(basic, credentials.getAuthorizationHeaderValue(false));
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_KEY, "read-key");
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 240);
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
long readExp = signedExp(credentials.getAuthorizationHeaderValue(false), "read-key") - now;
assertTrue(readExp >= 239 && readExp <= 245);
long writeExp = signedExp(credentials.getAuthorizationHeaderValue(true), "write-key") - now;
assertTrue(writeExp >= 119 && writeExp <= 125);
}
@Test
public void testFilerCredentialOptionsOverrideOneValueEach() throws Exception {
FilerCredentials credentials = new FilerCredentials();
credentials.setBasicAuth("toml-user", "toml-pass");
credentials.setJwtReadSigningKey("toml-read-key", 0);
conf.set(SeaweedFileSystem.FS_SEAWEED_FILER_BASIC_AUTH_PASSWORD, "new-pass");
conf.setLong(SeaweedFileSystem.FS_SEAWEED_FILER_JWT_SIGNING_READ_EXPIRES, 300);
SeaweedFileSystem.applyFilerCredentials(conf, credentials);
assertEquals("Basic " + Base64.getEncoder().encodeToString("toml-user:new-pass".getBytes(StandardCharsets.UTF_8)),
credentials.getAuthorizationHeaderValue(true));
long exp = signedExp(credentials.getAuthorizationHeaderValue(false), "toml-read-key");
assertTrue(exp - System.currentTimeMillis() / 1000 >= 299);
}
// Asserts the header is a filer JWT signed with key and returns its exp claim.
private static long signedExp(String header, String key) throws Exception {
assertTrue(header, header.startsWith("BEARER "));
String[] parts = header.substring("BEARER ".length()).split("\\.");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString(
mac.doFinal((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8))), parts[2]);
String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
return Long.parseLong(payload.replaceAll("[^0-9]", ""));
}
}
File diff suppressed because it is too large. Load diff
+322
View File
@@ -0,0 +1,322 @@
//! The FIPS 140-3 mode a SeaweedFS process runs in.
//!
//! One setting states it for a whole deployment: `[fips] mode` in
//! security.toml, or `WEED_FIPS_MODE`, which wins over the file as viper's
//! `AutomaticEnv` does for the Go processes. Go processes take their mode from
//! `GODEBUG=fips140` and refuse to start when it differs from the setting; the
//! Rust binaries take it from the setting alone, and under [`FipsMode::On`]
//! and [`FipsMode::Strict`] restrict TLS to what Go's `crypto/tls` allows in
//! FIPS mode (see [`crate::tls`]). This restricts behaviour only: the
//! cryptography underneath is still the non-validated aws-lc-rs build.
//!
//! Each binary reads `fips.mode` with the parser it uses for the rest of
//! security.toml and hands the value to [`resolve`], so the mode and the JWT
//! keys are either both read from a file or both missed.
use std::ffi::OsString;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
/// The security.toml setting, as `section.key`.
pub const SETTING: &str = "fips.mode";
/// The environment variable that overrides [`SETTING`].
pub const ENV: &str = "WEED_FIPS_MODE";
/// The environment variable holding the mode that applies when neither
/// [`ENV`] nor [`SETTING`] sets one; the Docker image's entrypoint sets it to
/// the mode it runs every process in.
pub const DEFAULT_ENV: &str = "WEED_FIPS_MODE_DEFAULT";
/// The modes `fips.mode` names. Unset reads as [`FipsMode::Off`], which is
/// how every Rust binary behaved before the setting existed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FipsMode {
/// No FIPS restrictions; Go processes need `fips140=off`.
#[default]
Off,
/// FIPS-mode TLS; Go processes need `GODEBUG=fips140=on`.
On,
/// FIPS-mode TLS; Go processes need `GODEBUG=fips140=only`, which also
/// refuses non-approved algorithms outside TLS.
Strict,
}
impl FipsMode {
/// Parses a value of `fips.mode`: `off`, `on` or `strict`, or `None` for
/// an empty value, which leaves the setting unset.
pub fn parse(value: &str) -> Result<Option<Self>, FipsModeError> {
match value {
"" => Ok(None),
"off" => Ok(Some(Self::Off)),
"on" => Ok(Some(Self::On)),
"strict" => Ok(Some(Self::Strict)),
other => Err(FipsModeError::Unknown {
source: SETTING.to_string(),
value: other.to_string(),
}),
}
}
/// Whether TLS is restricted to the FIPS 140-3 lists.
pub fn is_fips(self) -> bool {
self != Self::Off
}
pub fn as_str(self) -> &'static str {
match self {
Self::Off => "off",
Self::On => "on",
Self::Strict => "strict",
}
}
}
impl fmt::Display for FipsMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// Why the mode could not be resolved or recorded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FipsModeError {
/// `source` holds a value that is not `off`, `on` or `strict`.
Unknown { source: String, value: String },
/// The process mode was already set to a different mode.
AlreadySet { set: FipsMode, wanted: FipsMode },
/// The security.toml at `path` exists but could not be read or parsed, so
/// whether it sets `fips.mode` is unknown.
File { path: PathBuf, reason: String },
}
impl fmt::Display for FipsModeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unknown { source, value } => {
write!(f, "{source} is {value:?}; want off, on or strict")
}
Self::AlreadySet { set, wanted } => {
write!(f, "FIPS mode is already {set}, cannot switch to {wanted}")
}
Self::File { path, reason } => write!(
f,
"{}: {reason}; cannot tell whether it sets {SETTING}",
path.display()
),
}
}
}
impl std::error::Error for FipsModeError {}
/// A resolved `fips.mode`: the mode, and where it was set (`None` when
/// nothing set it and the mode is [`FipsMode::Off`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Setting {
pub mode: FipsMode,
pub source: Option<String>,
}
impl fmt::Display for Setting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.source {
Some(source) => write!(f, "FIPS mode {} ({source})", self.mode),
None => write!(f, "FIPS mode {} ({SETTING} unset)", self.mode),
}
}
}
/// Resolves the mode of a process whose own security.toml loader read
/// `file_value` for `fips.mode` from `file` (`None` when there is no file or
/// it does not set the key): `WEED_FIPS_MODE` when set and non-empty, else
/// `file_value` when non-empty, else `WEED_FIPS_MODE_DEFAULT`, the mode the
/// Docker image's entrypoint states, else [`FipsMode::Off`]. An unknown value
/// is an error naming where it came from.
pub fn resolve(
file: Option<&Path>,
file_value: Option<&str>,
env: &dyn Fn(&str) -> Option<OsString>,
) -> Result<Setting, FipsModeError> {
let from = |name: &'static str| {
env(name)
.map(|v| v.to_string_lossy().into_owned())
.filter(|v| !v.is_empty())
.map(|v| (name.to_string(), v))
};
let from_file = || {
let source = match file {
Some(path) => format!("{}: {SETTING}", path.display()),
None => SETTING.to_string(),
};
file_value
.filter(|value| !value.is_empty())
.map(|value| (source, value.to_string()))
};
let Some((source, value)) = from(ENV).or_else(from_file).or_else(|| from(DEFAULT_ENV)) else {
return Ok(Setting {
mode: FipsMode::Off,
source: None,
});
};
match FipsMode::parse(&value) {
Ok(Some(mode)) => Ok(Setting {
mode,
source: Some(source),
}),
Ok(None) => Ok(Setting {
mode: FipsMode::Off,
source: None,
}),
Err(_) => Err(FipsModeError::Unknown { source, value }),
}
}
static PROCESS_MODE: OnceLock<FipsMode> = OnceLock::new();
/// Records the mode this process runs in. A second call with the same mode is
/// a no-op; one with another mode is an error, since providers and
/// configurations built under the first would not change.
pub fn set_process_mode(mode: FipsMode) -> Result<(), FipsModeError> {
let set = *PROCESS_MODE.get_or_init(|| mode);
if set != mode {
return Err(FipsModeError::AlreadySet { set, wanted: mode });
}
Ok(())
}
/// The mode recorded by [`set_process_mode`], [`FipsMode::Off`] before.
pub fn process_mode() -> FipsMode {
PROCESS_MODE.get().copied().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn env_of(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<OsString> {
move |key| {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| OsString::from(v))
}
}
const FILE_PATH: &str = "/etc/seaweedfs/security.toml";
#[test]
fn parse_knows_three_modes_and_empty() {
assert_eq!(FipsMode::parse(""), Ok(None));
assert_eq!(FipsMode::parse("off"), Ok(Some(FipsMode::Off)));
assert_eq!(FipsMode::parse("on"), Ok(Some(FipsMode::On)));
assert_eq!(FipsMode::parse("strict"), Ok(Some(FipsMode::Strict)));
assert!(FipsMode::parse("only").is_err());
assert!(FipsMode::parse("On").is_err());
}
#[test]
fn unset_everywhere_is_off() {
let off = Setting {
mode: FipsMode::Off,
source: None,
};
assert_eq!(resolve(None, None, &env_of(&[])), Ok(off.clone()));
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), None, &env_of(&[])),
Ok(off.clone())
);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some(""), &env_of(&[])),
Ok(off.clone())
);
assert_eq!(off.to_string(), "FIPS mode off (fips.mode unset)");
}
#[test]
fn the_file_sets_the_mode() {
let setting = resolve(Some(Path::new(FILE_PATH)), Some("strict"), &env_of(&[])).unwrap();
assert_eq!(setting.mode, FipsMode::Strict);
assert_eq!(
setting.to_string(),
"FIPS mode strict (/etc/seaweedfs/security.toml: fips.mode)"
);
}
#[test]
fn the_environment_wins_over_the_file() {
let env = env_of(&[("WEED_FIPS_MODE", "on")]);
let setting = resolve(Some(Path::new(FILE_PATH)), Some("off"), &env).unwrap();
assert_eq!(setting.mode, FipsMode::On);
assert_eq!(setting.to_string(), "FIPS mode on (WEED_FIPS_MODE)");
assert_eq!(resolve(None, None, &env).unwrap().mode, FipsMode::On);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some("[\"strict\"]"), &env)
.unwrap()
.mode,
FipsMode::On
);
}
#[test]
fn the_image_default_applies_only_when_nothing_else_sets_the_mode() {
let env = env_of(&[("WEED_FIPS_MODE_DEFAULT", "on")]);
let setting = resolve(Some(Path::new(FILE_PATH)), Some(""), &env).unwrap();
assert_eq!(setting.mode, FipsMode::On);
assert_eq!(setting.to_string(), "FIPS mode on (WEED_FIPS_MODE_DEFAULT)");
assert_eq!(resolve(None, None, &env).unwrap().mode, FipsMode::On);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some("strict"), &env)
.unwrap()
.mode,
FipsMode::Strict
);
let both = env_of(&[("WEED_FIPS_MODE_DEFAULT", "on"), ("WEED_FIPS_MODE", "off")]);
assert_eq!(resolve(None, None, &both).unwrap().mode, FipsMode::Off);
let unknown = env_of(&[("WEED_FIPS_MODE_DEFAULT", "yes")]);
assert_eq!(
resolve(None, None, &unknown).unwrap_err().to_string(),
"WEED_FIPS_MODE_DEFAULT is \"yes\"; want off, on or strict"
);
}
#[test]
fn an_empty_environment_variable_counts_as_unset() {
let env = env_of(&[("WEED_FIPS_MODE", "")]);
assert_eq!(
resolve(Some(Path::new(FILE_PATH)), Some("on"), &env)
.unwrap()
.mode,
FipsMode::On
);
}
#[test]
fn an_unknown_value_is_refused_naming_its_source() {
let err = resolve(None, None, &env_of(&[("WEED_FIPS_MODE", "yes")])).unwrap_err();
assert_eq!(
err.to_string(),
"WEED_FIPS_MODE is \"yes\"; want off, on or strict"
);
let err = resolve(
Some(Path::new(FILE_PATH)),
Some("[\"strict\"]"),
&env_of(&[]),
)
.unwrap_err();
assert_eq!(
err.to_string(),
"/etc/seaweedfs/security.toml: fips.mode is \"[\\\"strict\\\"]\"; want off, on or strict"
);
}
#[test]
fn the_process_mode_is_set_once() {
assert_eq!(set_process_mode(process_mode()), Ok(()));
let other = if process_mode() == FipsMode::On {
FipsMode::Off
} else {
FipsMode::On
};
assert!(set_process_mode(other).is_err());
}
}
+169
View File
@@ -0,0 +1,169 @@
//! JWT signing keys under [`FipsMode::Strict`].
//!
//! FIPS 140 needs HMAC keys of at least 112 bits, and Go's `crypto/hmac`
//! panics on a shorter one under `GODEBUG=fips140=only`, so every Go process
//! refuses to start when a JWT key in security.toml is shorter
//! (`weed/util/fips140_keys.go`). The Rust binaries take `fips.mode = strict`
//! to mean the same and apply the same rule with the same wording, so one
//! security.toml gets the same answer from a Go and a Rust server.
use crate::fips::FipsMode;
/// The shortest HMAC key FIPS 140 allows: 112 bits.
pub const MIN_HMAC_KEY_BYTES: usize = 14;
/// The wiki section on switching JWT signing keys without downtime.
pub const JWT_SIGNING_KEYS_WIKI: &str =
"https://github.com/seaweedfs/seaweedfs/wiki/Cryptography-and-FIPS-Compliance#jwt-signing-keys";
/// Every security.toml setting that keys an HS256 JWT, in the order Go checks
/// them. Go refuses a short one at startup in any process that reads the file.
pub const JWT_KEY_SETTINGS: [&str; 11] = [
"jwt.signing.key",
"jwt.signing.previous_key",
"jwt.signing.read.key",
"jwt.signing.read.previous_key",
"jwt.filer_signing.key",
"jwt.filer_signing.previous_key",
"jwt.filer_signing.read.key",
"jwt.filer_signing.read.previous_key",
"jwt.filer_signing.grpc_key",
"jwt.filer_signing.grpc_previous_key",
"jwt.filer_signing.subscribe.key",
];
/// Whether `key` is shorter than the FIPS mode allows (14 characters when
/// strict).
pub fn is_short(mode: FipsMode, key: &[u8]) -> bool {
mode == FipsMode::Strict && !key.is_empty() && key.len() < MIN_HMAC_KEY_BYTES
}
/// Go's `CheckFips140HmacKeys`: under strict mode, one message naming each
/// setting in `keys` whose key is too short, with its length; otherwise `None`.
pub fn short_keys(mode: FipsMode, keys: &[(&str, &[u8])]) -> Option<String> {
let short: Vec<String> = keys
.iter()
.filter(|(_, key)| is_short(mode, key))
.map(|(setting, key)| format!("{} ({} characters)", setting, key.len()))
.collect();
match short.as_slice() {
[] => None,
[one] => Some(format!(
"{} is shorter than the {} characters FIPS 140 needs for HMAC keys",
one, MIN_HMAC_KEY_BYTES
)),
[rest @ .., last] => Some(format!(
"{} and {} are shorter than the {} characters FIPS 140 needs for HMAC keys",
rest.join(", "),
last,
MIN_HMAC_KEY_BYTES
)),
}
}
/// The error a server logs before it exits at startup over the short keys in
/// `file`; `short` is the message from [`short_keys`].
pub fn startup_refusal(file: &str, short: &str) -> String {
format!(
"{}: this process runs with fips.mode strict, and stops because {}; replace them on every server that uses them, with or without downtime, see {}",
file, short, JWT_SIGNING_KEYS_WIKI
)
}
/// Go's `shortJwtKeyWarning`: a warning that the key (other than a previous
/// key) of `setting` in `file` is too short for strict mode, asking for a
/// longer one while the short one still works.
pub fn short_key_warning(mode: FipsMode, file: &str, setting: &str, key: &[u8]) -> Option<String> {
if mode == FipsMode::Strict
|| key.is_empty()
|| key.len() >= MIN_HMAC_KEY_BYTES
|| setting.ends_with("previous_key")
{
return None;
}
Some(format!(
"{}: this process does not run with fips.mode strict, so {} works, but under fips.mode strict this server would not start: the key is shorter than the {} characters FIPS 140 needs for HMAC keys (it has {}); to replace it on every server that uses it without downtime, see {}",
file,
setting,
MIN_HMAC_KEY_BYTES,
key.len(),
JWT_SIGNING_KEYS_WIKI
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_keys_only_under_strict() {
let keys: [(&str, &[u8]); 1] = [("jwt.signing.key", b"0123456789")];
assert_eq!(short_keys(FipsMode::On, &keys), None);
assert_eq!(short_keys(FipsMode::Off, &keys), None);
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) is shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn short_keys_names_every_short_key_and_skips_unset_and_long_ones() {
let keys: [(&str, &[u8]); 4] = [
("jwt.signing.key", b"0123456789"),
("jwt.signing.read.key", b""),
("jwt.filer_signing.key", b"01234567890123"),
("jwt.filer_signing.subscribe.key", b"01234567"),
];
assert_eq!(
short_keys(FipsMode::Strict, &keys).as_deref(),
Some(
"jwt.signing.key (10 characters) and jwt.filer_signing.subscribe.key (8 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
let three: [(&str, &[u8]); 3] = [("a", b"1"), ("b", b"12"), ("c", b"123")];
assert_eq!(
short_keys(FipsMode::Strict, &three).as_deref(),
Some(
"a (1 characters), b (2 characters) and c (3 characters) are shorter than the 14 characters FIPS 140 needs for HMAC keys"
)
);
}
#[test]
fn warning_outside_strict_except_for_previous_keys() {
assert!(short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b"0123456789")
.unwrap()
.starts_with("s.toml: this process does not run with fips.mode strict, so jwt.signing.key works"));
assert!(
short_key_warning(FipsMode::On, "s.toml", "jwt.signing.key", b"0123456789").is_some()
);
assert_eq!(
short_key_warning(FipsMode::Strict, "s.toml", "jwt.signing.key", b"0123456789"),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.previous_key",
b"0123456789"
),
None
);
assert_eq!(
short_key_warning(
FipsMode::Off,
"s.toml",
"jwt.signing.key",
b"01234567890123"
),
None
);
assert_eq!(
short_key_warning(FipsMode::Off, "s.toml", "jwt.signing.key", b""),
None
);
}
}
+4
View File
@@ -8,7 +8,11 @@
//! rustls provider, which only works if every binary installs the same one.
//! The security.toml search path joined them for the same reason: an operator
//! mounts the file once and every binary has to look where `weed` looks.
//! The FIPS mode joined them because it decides that provider, and the JWT key
//! rule for strict mode because every binary that reads the keys applies it.
pub mod address;
pub mod fips;
pub mod jwt_keys;
pub mod security_config;
pub mod tls;
+3
View File
@@ -0,0 +1,3 @@
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIKcJM4ur78AjGRa92XbPxkXK+Dx4z7eObSdEzyhV/iiI
-----END PRIVATE KEY-----
+4
View File
@@ -0,0 +1,4 @@
-----BEGIN PRIVATE KEY-----
MEcCAQAwBQYDK2VxBDsEOSsBSiCeTY1tto3PFVZFeK55DoEaqWlcSREnSTQ4nfkr
Lvw0O5dru34QfckKqoFuEoyMvMh1RIz95g==
-----END PRIVATE KEY-----
+57
View File
@@ -0,0 +1,57 @@
-----BEGIN PRIVATE KEY-----
MIIKPgIBADALBglghkgBZQMEAxEEggoqMIIKJgQgQQrP8unrSpS7t1GeYGJIpRto
SmG4mJa33bu2HdaeZFsEggoA/gIsLnCAYuY4UDW5CpPcovPbtEmtHbOEZPWYYbiY
sGpD93b/wCjXPD+7jcDHohVQJ75aO4Adsj5sq/5zMixfzIPslMUdkX310RVIpi43
D6bfBrAxkO0U1Nkn6iDOqw+UWc9YvRM5WkujREA8qng79JZ1gbDEHUw4JahfIs79
F4fjQkGAuCxauC0bBCQihk1YpEkLQYUkGDCIBmJMQAUAhUUBIS0LIUyJpGnURilb
iBAMRQLEuEEJBHGJJlEhSTHRSA0QESYhRQgjGIEkiCjMkEDJIFBTwnCcomBUBlBb
uBFMSGHJxmjZgpAhsyhglkxiBo7BRoDUJEARgojRAiVYEg4AxklcFmCBQGUZiQRR
ok2bgI1CpA2USIwjgYnYNIpcICXKMi3RomijokghCSaaokyTwlFaFnEiBCqilkwR
iSwLGQEUIFHBsm1kBGVYRmniRnICsRCTJirDoogKSBHcSHHiqBGRGCkDMlJCCDFD
tGQAR0rYMATkRnGYAikixkjMhGUSyHAKSWgMkkAZGBLbJGBkIAQDhjCgEkEDR4zA
Jg0CQDJSlBEkQCUUGCEjyU1iIClRMBETgSQbR2WRqEWcRoBDIiLjoo1SpCVIuA1j
CDAJRYwYEGwEmDBRODFLFnAjwowjAkzbtm3QFE0ZsmVEGGwDRQwKyTBTIgkSxoAc
g03SoGRBRm0RSIQihQ0cqSDYSCYMOAqYIgoiFHLghixcRiQhhHEKBwHKOAACKWkR
I4pCFI2JyCUSOCkZNwmBxCAcQ3IhJVKEpkUgJgySGHLcJkRRlmHRlk0TgDCauCDg
JGURtmgbFWpBOHKKmCUag03BgnAhsohgFAGQuGHDRlEkBTGRFAkhEI7ThoBbyJDC
IGSkJkwgs0VjpgWIsE0Ctk0CyQFSBk4SowlDoCRZEmYKGSqiRIACpJGDQgUYRGDI
CIyJBCUaKA7EIijcJACEqC0DEgABOE2TyCwTSGAJlyhbgADZkGkDpgVaMFASGGlR
RgIBJ4bQQmEjQAlkkFEAGW0JQYIDFm0DNpDIgIQYQ4WTwiwgBAKJMi0ZliCUMEWa
GIkaJ5IKwJFjCI0iiGDjEExBtpCcKGVcMm4CsXAIImWEwhDYOI4hgUgCQYoUBZCC
soTbtBALEEIcJpAQF1EZlnDEqCgbNyCLBIISMVCLQgwJkmDJGCGCRiIYMYrKkiCa
xGTbZXtrCGKSFu3craDAVG1GAKYgmimIF4ktgY7/C4ammULwJmqnjNfOSlCt598v
9ofuxnVZlDEtlTjgKQPPfXOp3lEzl9Die1QeZNqcg3IuTVRnUolGKTI62HNqKXfm
PrSQ9sPnOdGa4XyXYncraf1UuZ//hknLrM88D+kNoGqP65ni+OQ5MU0nsy52Y6ns
G88lSAFypwo+welJJAWxek5PsLbhnYyZfTpKvPC52ZfRCQBCG4n4RK0qtiaFBgly
JrBUVnzLvMtxZPr7rK47UipXcQAAnd6m1Ul8wE7/FCBQ6xWQQQUH8lmW8a6ZSuod
lW2Evbut2p8B9HadMBRP6+2oPrYfrpTSkDawNPiNIWZvk4F6klljAWmrDJB0v/ou
kIzuYiMWkZhbhJO6bVVpW8/h2HQarETnCERtqBjXRDiJgg0gzHQZiNACMV3LiEaS
muZIxqzzsOhn/i6RA9qnBqvl3mk/2GFXudiLFVk0cYMBLqn3tIt2k/+S0DsbKvSE
0dPSqzXx62oLgqxK8DJmrJ5YHTHSTsJfHO64VX3f1MnFLhV/6TPOteJmE/8CEmZK
gtrDpN9wYvmFe3vWUCAsYOzfnzDolq+SsqXAbZhkYNoomAwBK36pU0aE/e8SiCdP
I7EM17AyPW5f9mLs0S3g9zVX3NK9zgaW9EtQ8zLXm7sOeazzEp6xxobOvJCBwoav
tPzT+vab5u8nNDIcLIAj/mYAjkjS7cog135qOE56WiTOW7gCB75C6WkiAQTOqZ7J
+AFUgwN9j61cdTeJW/NbPgndlpjK+HiTYeENdnBQ898/JmUblhzcR/QpMEih3QO/
Q7+AfejRpVPpOLDDJwRfc19b6ymZ27nJVQ4GChI6oKX4Po4JNo54UO09bRsCf9Eq
sq9EvCBsS6H0xw6Y7EmNab0BpW6iFUmac9Bj4cWh9trZ/bZwExW4YvwX+bDIM/A8
mqmpsZSbkE/RoEiKSS7NHc3XgVsGJ2czkftcGbnUBZmIaPVu6XVJyyBwM7GogESv
yuQGFbuSlOhrwphtNfpm0T+/vU/elaIPJS0Os2sgmPgGqHE+o5BndkZ/hD8c5Ec0
Zs64BZugQoLKLTJtn+JqVWd6PotXBgEazdechsQQfCqOwRUO8VP9Q7A/sPQpgAk8
UyMvQliHdF2FFE9BHYMMw2B8a05+MUogYAS+V4RB1mMl35Lv1W3nOvIszSkFGact
T4uh7/mQwekpR0AXRcYdF72YDuC7WvMG7cBvZe5oi1c1/vu0R+NgUw1yMiZp3f/C
xqM/h1QzQTxSaro4oJm6/nJr3hSj6yx83cPbQzusLAb0CkkGlqw977rxWC56rPUt
d7cMOG9L7dMPIzuQ6PkQY6ttgDpH176d2vZphfFqjyUb05ryA+vJw/+xh73le837
TaNeTemy+p2UlYdW2LkTrgz0v/t2CsiT6LL9uGyz0rGrs/bGJg3XPMxsukHanThd
KKm8leIE02ogDiSfy2Ozf+rdJUGDArr4Jb5IYGE8bQUdfdBvvb1eKDhgKvYHM5XE
ExnFQSa8pftsXjS2F7MQr397tBL6WNC+KPnbgXmLhJbmGvnuS7XaHkErrRQwD75M
tP6b2fZiKWz9gx+0nkOxM1PX+cPVWrgbrrvpJUZewe1LW+Mctuei8sXTkHQ9stq7
23xqQTUe9soXWy277wlPr1eXY2gnKkH7hc7flu5gGSoaG29g4okvu6hrTUJ4tJgd
0YaLF0uNt2LvgBNOVxHBFX09GzGsvxfhY9+dRl0CDq3oHvaWCLs52WYx0u6s0Oyq
mCKG9lTdKL57pyPAPR1iCZzTDLbjhdxMQUFQ7zHHfQksu5ui3MHnaA+BAijZgmi2
0rs/QEh7Wv1AJS2XkNoFN7CxBQueBmXb2OtsqNHPv4lbE17UrHUbi9GHoMhfaGMB
9YzcPP/3Qentc3az4T4HsZUdePakJguI3qLBKGLdXtn2JHNoJ/poCxtVEEQ474us
YZQvYXbBmeJ+kwczfabNqRdGDnN4e1bfSxnSiVCJJDK5EQGNatqCso5S+5jyAd6z
FBbOe72dJxacVdU0esOrRK0cafJpeeCNgtUiRCZeWiFi3d+daLgqcqEiaV2Obk99
SiG57HJDpMrQgyzVuucms3bRWlb8H38DBFjclt4ONFx5dymNR/C2QCm+FCXvuFEv
UHB9qJcdZuhjkRNszOrvkokJdWWt9GxRWQ6eR+raum0q+Q==
-----END PRIVATE KEY-----
+5
View File
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKQGVRsbYNwfFeCQU
4c2Nkjnme5k8eDQ1loKC5/qKNeGhRANCAAQtjdBx4U07ZO68fAkYnGbhCoeVTC9o
BejPCRmx9mOOhD3dKK5j9hsgVBd0RagUsgVwkq5xLKrvMB8ZoQe2jKRF
-----END PRIVATE KEY-----
+419 -6
View File
@@ -5,19 +5,285 @@
//! backend and reqwest — so rustls cannot auto-select a provider and tonic's
//! client TLS panics on first use. Each binary has to pin one, and it has to be
//! the same one, which is why the choice lives here rather than in either tree.
//!
//! Under [`FipsMode::On`] and [`FipsMode::Strict`] the provider is aws-lc-rs
//! filtered to what Go's `crypto/tls` allows when `GODEBUG=fips140` is `on` or
//! `only` (`crypto/tls/defaults_fips140.go`, Go 1.27.4, the version go.mod
//! requires). TLS 1.2 and 1.3 are all rustls implements, which is Go's FIPS
//! version list.
use rustls::crypto::aws_lc_rs;
use std::sync::{Arc, OnceLock};
/// Pin rustls's process-wide default provider to aws-lc-rs, matching the
/// volume server's TLS config. Idempotent: the first call wins and every
/// later one is a no-op, so callers do not have to coordinate.
use rustls::crypto::{
CryptoProvider, KeyProvider, SupportedKxGroup, WebPkiSupportedAlgorithms, aws_lc_rs,
};
use rustls::pki_types::{PrivateKeyDer, SubjectPublicKeyInfoDer, alg_id};
use rustls::sign::{Signer, SigningKey};
use rustls::{CipherSuite, NamedGroup, SignatureAlgorithm, SignatureScheme};
use crate::fips::{self, FipsMode, FipsModeError};
/// Go's `allowedCipherSuitesTLS13FIPS` and the AES-GCM part of
/// `allowedCipherSuitesFIPS`. Go also allows
/// `TLS_ECDHE_{ECDSA,RSA}_WITH_AES_128_CBC_SHA256`, which rustls does not
/// implement.
pub const FIPS_CIPHER_SUITES: &[CipherSuite] = &[
CipherSuite::TLS13_AES_128_GCM_SHA256,
CipherSuite::TLS13_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
];
/// Go's `allowedCurvePreferencesFIPS` as rustls 0.23 has them and Go enables
/// by default, in Go's preference order. rustls has no SecP384r1MLKEM1024 and
/// no P-521; it has MLKEM1024, which Go allows but enables only when
/// configured, so it is left out as Go leaves it out of its defaults.
fn fips_kx_groups() -> Vec<&'static dyn SupportedKxGroup> {
vec![
aws_lc_rs::kx_group::X25519MLKEM768,
aws_lc_rs::kx_group::SECP256R1MLKEM768,
aws_lc_rs::kx_group::SECP256R1,
aws_lc_rs::kx_group::SECP384R1,
]
}
/// Go's `allowedSignatureAlgorithmsFIPS`.
pub const FIPS_SIGNATURE_SCHEMES: &[SignatureScheme] = &[
SignatureScheme::RSA_PSS_SHA256,
SignatureScheme::ECDSA_NISTP256_SHA256,
SignatureScheme::ED25519,
SignatureScheme::ML_DSA_44,
SignatureScheme::ML_DSA_65,
SignatureScheme::ML_DSA_87,
SignatureScheme::RSA_PSS_SHA384,
SignatureScheme::RSA_PSS_SHA512,
SignatureScheme::RSA_PKCS1_SHA256,
SignatureScheme::RSA_PKCS1_SHA384,
SignatureScheme::RSA_PKCS1_SHA512,
SignatureScheme::ECDSA_NISTP384_SHA384,
SignatureScheme::ECDSA_NISTP521_SHA512,
];
/// The certificate key types Go's `isCertificateAllowedFIPS` accepts: RSA,
/// ECDSA on P-256, P-384 or P-521, Ed25519, and ML-DSA (Go allows ML-DSA for
/// its native module only). The RSA algorithms rustls verifies with take keys
/// of 2048 to 8192 bits, so Go's 2048-bit floor holds.
const FIPS_CERTIFICATE_KEYS: &[rustls::pki_types::AlgorithmIdentifier] = &[
alg_id::RSA_ENCRYPTION,
alg_id::ECDSA_P256,
alg_id::ECDSA_P384,
alg_id::ECDSA_P521,
alg_id::ED25519,
alg_id::ML_DSA_44,
alg_id::ML_DSA_65,
alg_id::ML_DSA_87,
];
/// The aws-lc-rs verification algorithms limited to Go's FIPS signature
/// schemes and certificate keys. With aws-lc-rs's current set that removes
/// nothing; the filter keeps an algorithm a later rustls adds out of FIPS
/// mode until Go allows it. Built once, since rustls needs `'static` slices.
fn fips_signature_verification_algorithms() -> WebPkiSupportedAlgorithms {
static ALGORITHMS: OnceLock<WebPkiSupportedAlgorithms> = OnceLock::new();
*ALGORITHMS.get_or_init(|| {
let default = aws_lc_rs::default_provider().signature_verification_algorithms;
let all = default
.all
.iter()
.filter(|alg| FIPS_CERTIFICATE_KEYS.contains(&alg.public_key_alg_id()))
.copied()
.collect::<Vec<_>>();
let mapping = default
.mapping
.iter()
.filter(|(scheme, _)| FIPS_SIGNATURE_SCHEMES.contains(scheme))
.copied()
.collect::<Vec<_>>();
WebPkiSupportedAlgorithms {
all: all.leak(),
mapping: mapping.leak(),
}
})
}
/// Loads private keys through aws-lc-rs and passes them through
/// [`restrict_to_fips`], so a FIPS-mode listener or client signs handshakes
/// only with Go's FIPS signature schemes.
#[derive(Debug)]
struct FipsKeyProvider;
static FIPS_KEY_PROVIDER: FipsKeyProvider = FipsKeyProvider;
impl KeyProvider for FipsKeyProvider {
fn load_private_key(
&self,
key_der: PrivateKeyDer<'static>,
) -> Result<Arc<dyn SigningKey>, rustls::Error> {
let key = aws_lc_rs::default_provider()
.key_provider
.load_private_key(key_der)?;
restrict_to_fips(key)
}
fn fips(&self) -> bool {
aws_lc_rs::default_provider().key_provider.fips()
}
}
/// Wraps `key` so it offers only [`FIPS_SIGNATURE_SCHEMES`], refusing a key
/// that can sign none of them, such as Ed448, with an error naming its type.
fn restrict_to_fips(key: Arc<dyn SigningKey>) -> Result<Arc<dyn SigningKey>, rustls::Error> {
if key.choose_scheme(FIPS_SIGNATURE_SCHEMES).is_none() {
return Err(rustls::Error::General(format!(
"{} private key is not allowed in FIPS mode, which accepts RSA, ECDSA P-256/P-384/P-521, Ed25519 and ML-DSA keys",
key_kind(key.algorithm())
)));
}
Ok(Arc::new(FipsSigningKey(key)))
}
/// How a refused key is named.
fn key_kind(algorithm: SignatureAlgorithm) -> String {
match algorithm {
SignatureAlgorithm::ED448 => "an Ed448".to_string(),
other => format!("a {other:?}"),
}
}
/// A signing key that offers only [`FIPS_SIGNATURE_SCHEMES`].
#[derive(Debug)]
struct FipsSigningKey(Arc<dyn SigningKey>);
impl SigningKey for FipsSigningKey {
fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
let allowed = offered
.iter()
.copied()
.filter(|scheme| FIPS_SIGNATURE_SCHEMES.contains(scheme))
.collect::<Vec<_>>();
self.0.choose_scheme(&allowed)
}
fn public_key(&self) -> Option<SubjectPublicKeyInfoDer<'_>> {
self.0.public_key()
}
fn algorithm(&self) -> SignatureAlgorithm {
self.0.algorithm()
}
}
/// The aws-lc-rs provider with Go's FIPS-mode TLS lists applied. It still
/// runs on the non-validated aws-lc-rs build, so `CryptoProvider::fips()` is
/// false.
pub fn fips_provider() -> CryptoProvider {
let default = aws_lc_rs::default_provider();
CryptoProvider {
cipher_suites: default
.cipher_suites
.into_iter()
.filter(|suite| FIPS_CIPHER_SUITES.contains(&suite.suite()))
.collect(),
kx_groups: fips_kx_groups(),
signature_verification_algorithms: fips_signature_verification_algorithms(),
key_provider: &FIPS_KEY_PROVIDER,
..default
}
}
/// The provider for `mode`: aws-lc-rs's default under [`FipsMode::Off`],
/// [`fips_provider`] otherwise.
pub fn provider_for(mode: FipsMode) -> CryptoProvider {
if mode.is_fips() {
fips_provider()
} else {
aws_lc_rs::default_provider()
}
}
/// The provider for this process's mode ([`fips::process_mode`]).
pub fn crypto_provider() -> CryptoProvider {
provider_for(fips::process_mode())
}
/// Pin rustls's process-wide default provider to [`crypto_provider`]:
/// aws-lc-rs, filtered to the FIPS lists when the process mode asks for it.
/// Idempotent: the first call wins and every later one is a no-op, so callers
/// do not have to coordinate.
pub fn install_default_crypto_provider() {
let _ = aws_lc_rs::default_provider().install_default();
let _ = crypto_provider().install_default();
}
/// Whether TLS 1.2 connections must use the Extended Master Secret, as Go
/// requires in FIPS mode. rustls requires it only of a validated provider,
/// so configurations SeaweedFS builds itself set `require_ems` from this.
pub fn require_ems() -> bool {
fips::process_mode().is_fips()
}
/// Why [`install_process_provider`] failed.
#[derive(Debug)]
pub enum InstallError {
Mode(FipsModeError),
/// A provider other than this mode's was installed first.
OtherProvider(FipsMode),
}
impl std::fmt::Display for InstallError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Mode(e) => e.fmt(f),
Self::OtherProvider(mode) => write!(
f,
"a rustls crypto provider other than the one for FIPS mode {mode} is already installed"
),
}
}
}
impl std::error::Error for InstallError {}
/// Records `mode` as this process's FIPS mode and installs its provider as the
/// rustls process default. Call it once at startup, before anything builds a
/// TLS configuration; it fails if a different provider got there first, so a
/// FIPS-mode process never runs on the unfiltered one.
pub fn install_process_provider(mode: FipsMode) -> Result<(), InstallError> {
fips::set_process_mode(mode).map_err(InstallError::Mode)?;
install_default_crypto_provider();
let installed = CryptoProvider::get_default().ok_or(InstallError::OtherProvider(mode))?;
if !same_lists(installed, &provider_for(mode)) {
return Err(InstallError::OtherProvider(mode));
}
Ok(())
}
/// Whether two providers offer the same suites, groups and signature schemes.
fn same_lists(a: &CryptoProvider, b: &CryptoProvider) -> bool {
let suites = |p: &CryptoProvider| {
p.cipher_suites
.iter()
.map(|s| s.suite())
.collect::<Vec<_>>()
};
let groups = |p: &CryptoProvider| {
p.kx_groups
.iter()
.map(|g| g.name())
.collect::<Vec<NamedGroup>>()
};
suites(a) == suites(b)
&& groups(a) == groups(b)
&& a.signature_verification_algorithms.supported_schemes()
== b.signature_verification_algorithms.supported_schemes()
&& a.signature_verification_algorithms.all.len()
== b.signature_verification_algorithms.all.len()
}
#[cfg(test)]
mod tests {
use super::install_default_crypto_provider;
use super::*;
#[test]
fn installing_is_idempotent_and_leaves_a_default_behind() {
@@ -25,4 +291,151 @@ mod tests {
install_default_crypto_provider();
assert!(rustls::crypto::CryptoProvider::get_default().is_some());
}
#[test]
fn off_is_the_unfiltered_default() {
assert!(same_lists(
&provider_for(FipsMode::Off),
&aws_lc_rs::default_provider()
));
}
#[test]
fn fips_mode_drops_chacha20_and_plain_x25519() {
for mode in [FipsMode::On, FipsMode::Strict] {
let provider = provider_for(mode);
let suites = provider
.cipher_suites
.iter()
.map(|s| s.suite())
.collect::<Vec<_>>();
assert_eq!(
suites,
vec![
CipherSuite::TLS13_AES_256_GCM_SHA384,
CipherSuite::TLS13_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
]
);
let groups = provider
.kx_groups
.iter()
.map(|g| g.name())
.collect::<Vec<_>>();
assert_eq!(
groups,
vec![
NamedGroup::X25519MLKEM768,
NamedGroup::secp256r1MLKEM768,
NamedGroup::secp256r1,
NamedGroup::secp384r1,
]
);
}
}
fn load(provider: &CryptoProvider, pem: &str) -> Result<Arc<dyn SigningKey>, rustls::Error> {
use rustls::pki_types::pem::PemObject;
provider
.key_provider
.load_private_key(PrivateKeyDer::from_pem_slice(pem.as_bytes()).unwrap())
}
const ML_DSA_44_KEY: &str = include_str!("testdata/mldsa44.pem");
const ED448_KEY: &str = include_str!("testdata/ed448.pem");
const P256_KEY: &str = include_str!("testdata/p256.pem");
const ED25519_KEY: &str = include_str!("testdata/ed25519.pem");
/// A key that signs only Ed448, which aws-lc-rs cannot load, to drive the
/// refusal.
#[derive(Debug)]
struct Ed448Only;
impl SigningKey for Ed448Only {
fn choose_scheme(&self, _offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
None
}
fn algorithm(&self) -> SignatureAlgorithm {
SignatureAlgorithm::ED448
}
}
#[test]
fn fips_mode_refuses_keys_outside_go_s_list() {
let err = restrict_to_fips(Arc::new(Ed448Only)).unwrap_err();
assert!(err.to_string().contains("an Ed448 private key"), "{err}");
assert!(
err.to_string().contains("not allowed in FIPS mode"),
"{err}"
);
assert!(load(&provider_for(FipsMode::On), ED448_KEY).is_err());
}
#[test]
fn fips_mode_allows_ml_dsa_as_go_1_27_does() {
let fips = provider_for(FipsMode::On);
let ml_dsa = load(&fips, ML_DSA_44_KEY).unwrap();
assert!(
ml_dsa
.choose_scheme(&[SignatureScheme::ML_DSA_44])
.is_some()
);
}
#[test]
fn fips_mode_keys_sign_with_fips_schemes_only() {
let fips = provider_for(FipsMode::Strict);
let p256 = load(&fips, P256_KEY).unwrap();
let signer = p256
.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256])
.unwrap();
assert_eq!(signer.scheme(), SignatureScheme::ECDSA_NISTP256_SHA256);
assert!(
p256.choose_scheme(&[SignatureScheme::ECDSA_SHA1_Legacy])
.is_none()
);
assert!(p256.public_key().is_some());
let ed25519 = load(&fips, ED25519_KEY).unwrap();
assert!(ed25519.choose_scheme(&[SignatureScheme::ED25519]).is_some());
}
#[test]
fn off_keeps_the_default_key_provider() {
let off = provider_for(FipsMode::Off);
let ml_dsa = load(&off, ML_DSA_44_KEY).unwrap();
assert!(
ml_dsa
.choose_scheme(&[SignatureScheme::ML_DSA_44])
.is_some()
);
}
#[test]
fn fips_mode_verifies_go_s_signature_schemes_only() {
let provider = fips_provider();
let mut schemes = provider
.signature_verification_algorithms
.supported_schemes();
let mut want = FIPS_SIGNATURE_SCHEMES.to_vec();
schemes.sort_by_key(|s| u16::from(*s));
want.sort_by_key(|s| u16::from(*s));
assert_eq!(schemes, want);
assert!(
provider
.signature_verification_algorithms
.all
.iter()
.all(|alg| FIPS_CERTIFICATE_KEYS.contains(&alg.public_key_alg_id()))
);
let default = aws_lc_rs::default_provider();
assert_eq!(
default.signature_verification_algorithms.all.len(),
provider.signature_verification_algorithms.all.len(),
"Go 1.27 allows every key type aws-lc-rs verifies"
);
}
}
+4
View File
@@ -6332,12 +6332,16 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"base64 0.22.1",
"bytes",
"crc32c",
"log",
"prost",
"protoc-bin-vendored",
"reqwest 0.12.28",
"rustls",
"rustls-native-certs",
"seaweed-common",
"thiserror 2.0.21",
"tokio",
"tonic",
+46 -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,49 @@ 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.
## Search indexed data only
The default search includes recent writes by scanning data that indexes do not
cover yet. To exclude that data, send `x-seaweedfs-vector-search-mode: indexed-only`
on `QueryVectors`. Omit the header, or set it to `all`, for the default behavior.
This is a SeaweedFS extension. With SigV4, the header must be signed.
For example, inject it before boto3 signs the request:
```python
def indexed_only(request, **kwargs):
request.headers["x-seaweedfs-vector-search-mode"] = "indexed-only"
client.meta.events.register("before-sign.s3vectors.QueryVectors", indexed_only)
try:
result = client.query_vectors(
vectorBucketName="embeddings", indexName="articles",
queryVector={"float32": embedding}, topK=10,
)
finally:
client.meta.events.unregister("before-sign.s3vectors.QueryVectors", indexed_only)
```
Indexed-only searches use the intersection of vector index coverage and the
coverage of each metadata index the filter requires, at one table version. Filters
must be conjunctions of string equality or `$in` predicates on ready indexed
metadata keys. An unavailable index or unsupported filter returns
`ValidationException`. A valid index with no eligible data returns an empty list.
A vector engine predating this extension returns `ServiceUnavailableException`;
the gateway never falls back to a full search.
The response includes `x-seaweedfs-vector-search-mode: indexed-only`,
`x-seaweedfs-vector-data-excluded: true|false`, and
`x-seaweedfs-vector-excluded-fragments`. The exclusion count describes coverage,
not the number of matching vectors. New writes, updates, and rewritten fragments
from compaction can be omitted until indexing catches up. Current deletions still
apply. Exact-search fallbacks stay within the eligible data; this option does not
guarantee a fixed latency.
Enterprise gateways send this mode to the shared single-engine backend using
`QueryIndexedVectors`; ordinary searches retain distributed routing. The shared
`Query` structure and existing query request/response messages are unchanged.
@@ -149,6 +149,52 @@ mod tests {
assert!(hits[0].distance < 1e-6);
}
#[tokio::test]
async fn indexed_only_skips_new_rows_until_indexed_and_honors_deletes() {
let dir = TempDir::new().unwrap();
let mut dataset = indexed_dataset(&dir, &["a"; 64]).await;
append_dataset(&mut dataset, &[vec![9.0; DIM]], &["b"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: vec![9.0; DIM],
k: 100,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let (hits, excluded) = crate::query::indexed_only(&dataset, &table, &query)
.await
.unwrap();
assert_eq!(excluded, 1);
assert_eq!(hits.len(), 64);
assert!(hits.iter().all(|h| h.key != "k64"));
dataset
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
.await
.unwrap();
let (hits, excluded) = crate::query::indexed_only(&dataset, &table, &query)
.await
.unwrap();
assert_eq!(excluded, 0);
assert_eq!(hits[0].key, "k64");
dataset.delete("key = 'k64'").await.unwrap();
let (hits, _) = crate::query::indexed_only(&dataset, &table, &query)
.await
.unwrap();
assert!(hits.iter().all(|h| h.key != "k64"));
let missing = write_dataset(&TempDir::new().unwrap(), &vectors(4, DIM), &["a"; 4]).await;
assert!(
crate::query::indexed_only(&missing, &table, &query)
.await
.unwrap_err()
.is::<crate::query::IndexedOnlyError>()
);
}
#[tokio::test]
async fn prefiltered_ann_matches_filtered_flat() {
let dir = TempDir::new().unwrap();
@@ -84,6 +84,20 @@ pub(crate) fn rewrite(filter: Expr, ready: &HashMap<String, String>) -> (Expr, V
(rewritten.unwrap_or(lit(true)), indexed)
}
pub(crate) fn columns(dataset: &Dataset, filter: &str) -> Result<Vec<String>> {
let mut scanner = dataset.scan();
scanner.filter(filter)?;
let expr = scanner.get_expr_filter()?.ok_or_else(|| {
crate::query::IndexedOnlyError("indexed-only requires an indexed metadata filter".into())
})?;
let count = split_conjunction_owned(expr.clone()).len();
let (_, indexed) = rewrite(expr, &ready_columns(dataset));
if indexed.len() != count {
return Err(crate::query::IndexedOnlyError("indexed-only supports conjunctions of string $eq/$in filters on ready metadata indexes".into()).into());
}
Ok(indexed.into_iter().map(|i| i.column).collect())
}
fn and(left: Option<Expr>, right: Expr) -> Expr {
match left {
Some(left) => Expr::BinaryExpr(BinaryExpr::new(
@@ -624,7 +638,7 @@ mod tests {
let few = |q: Query| {
let (dataset, table) = (&dataset, &table);
async move {
query::few_indexed_matches(dataset, table, &q)
query::few_indexed_matches(dataset, table, &q, None)
.await
.unwrap()
}
@@ -657,6 +671,99 @@ mod tests {
}
}
#[tokio::test]
async fn indexed_only_intersects_metadata_and_vector_coverage() {
use futures::TryStreamExt;
let dir = TempDir::new().unwrap();
let mut dataset = dataset(&dir, 300).await;
let batches = dataset
.scan()
.try_into_stream()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let batch = &batches[0];
let mut columns = batch.columns().to_vec();
let key = batch.schema().index_of("key").unwrap();
columns[key] = Arc::new(StringArray::from(
(0..batch.num_rows())
.map(|i| format!("new{i}"))
.collect::<Vec<_>>(),
));
let batch = RecordBatch::try_new(batch.schema(), columns).unwrap();
let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema());
dataset.append(reader, None).await.unwrap();
dataset
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
.await
.unwrap();
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: vec![1.0, 2.0, 3.0, 4.0],
k: 1000,
filter: Some(eq("author", "\"rare\"")),
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema());
dataset.append(reader, None).await.unwrap();
crate::index::build(&mut dataset, "vector", crate::index::INDEX_NAME, 4, true)
.await
.unwrap();
let tail = Query {
fragments: Some(vec![dataset.fragments().last().unwrap().id]),
..query.clone()
};
let (hits, excluded) = query::indexed_only(&dataset, &table, &tail).await.unwrap();
assert!(hits.is_empty());
assert_eq!(excluded, 1);
for limit in [None, Some(0)] {
let query = Query {
exact_match_limit: limit,
..query.clone()
};
let all = query::ann(&dataset, &table, &query).await.unwrap();
let (indexed, excluded) = query::indexed_only(&dataset, &table, &query).await.unwrap();
assert_eq!(excluded, 1);
assert!(all.len() > indexed.len());
assert!(indexed.len() >= 30);
}
for file in &dataset.fragments().last().unwrap().files {
std::fs::remove_file(dir.path().join("data").join(&file.path)).unwrap();
}
let dataset = Dataset::open(dir.path().to_str().unwrap()).await.unwrap();
assert!(query::ann(&dataset, &table, &query).await.is_err());
for limit in [None, Some(0)] {
let query = Query {
exact_match_limit: limit,
..query.clone()
};
assert!(query::indexed_only(&dataset, &table, &query).await.is_ok());
}
for filter in [
eq("other", "\"rare\""),
eq("author", "true"),
format!("NOT {}", eq("author", "\"rare\"")),
] {
let query = Query {
filter: Some(filter),
..query.clone()
};
assert!(
query::indexed_only(&dataset, &table, &query)
.await
.unwrap_err()
.is::<query::IndexedOnlyError>()
);
}
}
#[tokio::test]
async fn the_plan_reads_the_scalar_index() {
let dir = TempDir::new().unwrap();
+79 -55
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,39 +138,48 @@ 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]
async fn main() -> Result<()> {
weed_lance_worker::tls::install_default_crypto_provider();
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(
@@ -188,20 +189,32 @@ 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 mode = weed_lance_worker::tls::install_for_fips_mode(&security)?;
weed_lance_worker::security::check_signing_key_flag(
mode,
"--filer-signing-key (WEED_FILER_SIGNING_KEY)",
args.filer_signing_key.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 +223,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 +263,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 +275,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 +295,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,
@@ -327,7 +340,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 {
@@ -404,6 +417,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"
+235 -36
View File
@@ -6,8 +6,11 @@ use arrow_array::{Array, Float32Array, RecordBatch, StringArray, UInt64Array};
use futures::TryStreamExt;
use lance::Dataset;
use lance::dataset::scanner::Scanner;
use lance::index::DatasetIndexExt;
use lance_linalg::distance::DistanceType;
use lance_table::format::Fragment;
use roaring::RoaringBitmap;
use std::collections::HashSet;
use crate::table::VectorTable;
@@ -60,7 +63,7 @@ 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?.0, table).await
run(scanner(dataset, table, query, false, None).await?.0, table).await
}
/// Top-K with the ANN index where it covers the fragment and a flat pass over
@@ -75,35 +78,152 @@ pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Resu
/// 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>> {
if few_indexed_matches(dataset, table, query).await? {
return exact_in_scope(dataset, table, query).await;
ann_with_scope(dataset, table, query, None).await
}
#[derive(Debug)]
pub struct IndexedOnlyError(pub String);
impl std::fmt::Display for IndexedOnlyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
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()))
}
impl std::error::Error for IndexedOnlyError {}
pub async fn indexed_only(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
) -> Result<(Vec<Hit>, usize)> {
if query.postfilter {
return Err(IndexedOnlyError("indexed-only requires prefiltering".into()).into());
}
let mut eligible = indexed_fragments(
dataset,
&table.vector_column,
query.index_segments.as_deref(),
)
.await?;
if let Some(filter) = &query.filter {
for column in crate::indexed_filter::columns(dataset, filter)? {
eligible &= indexed_fragments(dataset, &column, None).await?;
}
}
let original = scope(dataset, table, query, None).await?;
let live: RoaringBitmap = dataset.fragments().iter().map(|f| f.id as u32).collect();
let original = original
.map(|ids| {
ids.into_iter()
.map(|id| id as u32)
.collect::<RoaringBitmap>()
})
.unwrap_or(live.clone())
& live;
eligible &= &original;
let excluded = (&original - &eligible).len() as usize;
if eligible.is_empty() {
return Ok((Vec::new(), excluded));
}
if excluded == 0
&& query.filter.is_none()
&& query.index_segments.is_none()
&& query.fragments.is_none()
{
return exact_in_scope(dataset, table, query).await;
let hits = ann(dataset, table, query).await?;
return if hits.len() < query.k {
Ok((exact_in_scope(dataset, table, query, None).await?, 0))
} else {
Ok((hits, 0))
};
}
let eligible: Vec<u64> = eligible.iter().map(u64::from).collect();
let hits = ann_with_scope(dataset, table, query, Some(&eligible)).await?;
Ok((hits, excluded))
}
async fn indexed_fragments(
dataset: &Dataset,
column: &str,
selected: Option<&[uuid::Uuid]>,
) -> Result<RoaringBitmap> {
if selected.is_some_and(|ids| ids.is_empty()) {
return Ok(RoaringBitmap::new());
}
let field = dataset
.schema()
.field(column)
.with_context(|| format!("no such field {column}"))?;
let mut covered = RoaringBitmap::new();
let mut found = Vec::new();
for index in dataset
.load_indices()
.await?
.iter()
.filter(|i| i.fields == [field.id])
{
if selected.is_some_and(|ids| !ids.contains(&index.uuid)) {
continue;
}
let bitmap = index
.fragment_bitmap
.as_ref()
.ok_or_else(|| IndexedOnlyError(format!("index coverage is unknown for {column}")))?;
covered |= bitmap;
found.push(index.uuid);
}
if found.is_empty() || selected.is_some_and(|ids| ids.iter().any(|id| !found.contains(id))) {
return Err(IndexedOnlyError(format!("no usable index for {column}")).into());
}
Ok(covered)
}
/// ANN and exact fallbacks restricted to the supplied fragments.
pub async fn ann_with_scope(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
restriction: Option<&[u64]>,
) -> Result<Vec<Hit>> {
if few_indexed_matches(dataset, table, query, restriction).await? {
return exact_in_scope(dataset, table, query, restriction).await;
}
let (scanner, indexed) = scanner(dataset, table, query, true, restriction).await?;
let hits = run(scanner, table).await?;
let short_prefilter = (query.filter.is_some() || restriction.is_some())
&& !query.postfilter
&& hits.len() < query.k;
if indexed && (short_prefilter || hits.iter().any(|h| !h.distance.is_finite())) {
return exact_in_scope(dataset, table, query, restriction).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>> {
async fn exact_in_scope(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
restriction: Option<&[u64]>,
) -> Result<Vec<Hit>> {
let exact = Query {
index_segments: None,
fragments: scope(dataset, table, query).await?,
fragments: scope(dataset, table, query, restriction).await?,
..query.clone()
};
run(scanner(dataset, table, &exact, false).await?.0, table).await
run(scanner(dataset, table, &exact, false, None).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 {
async fn scope(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
restriction: Option<&[u64]>,
) -> Result<Option<Vec<u64>>> {
let scope = match &query.index_segments {
Some(segments) if !segments.is_empty() => {
let mut ids = query.fragments.clone().unwrap_or_default();
ids.extend(
@@ -111,8 +231,25 @@ async fn scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<
);
Some(ids)
}
_ => query.fragments.clone(),
})
Some(_) => Some(query.fragments.clone().unwrap_or_default()),
None => query.fragments.clone(),
};
Ok(restrict(scope, restriction))
}
fn restrict(scope: Option<Vec<u64>>, restriction: Option<&[u64]>) -> Option<Vec<u64>> {
match restriction {
Some(ids) => {
let scope = scope.map(|ids| ids.into_iter().collect::<HashSet<_>>());
Some(
ids.iter()
.copied()
.filter(|id| scope.as_ref().is_none_or(|scope| scope.contains(id)))
.collect(),
)
}
None => scope,
}
}
/// Whether the rows of [`ann`]'s scope matching the filter's indexed
@@ -122,6 +259,7 @@ pub(crate) async fn few_indexed_matches(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
restriction: Option<&[u64]>,
) -> Result<bool> {
let limit = query.exact_match_limit.unwrap_or(DEFAULT_EXACT_MATCH_LIMIT);
let Some(filter) = &query.filter else {
@@ -143,7 +281,7 @@ pub(crate) async fn few_indexed_matches(
if indexed.is_empty() {
return Ok(false);
}
let scope = scope(dataset, table, query).await?;
let scope = scope(dataset, table, query, restriction).await?;
// An AND matches at most what its most selective indexed conjunct does.
for conjunct in &indexed {
let count =
@@ -195,6 +333,7 @@ async fn scanner(
table: &VectorTable,
query: &Query,
use_index: bool,
restriction: Option<&[u64]>,
) -> Result<(Scanner, bool)> {
if query.vector.len() != table.dimension {
bail!(
@@ -247,22 +386,13 @@ async fn scanner(
if use_index && !segments.is_empty() {
scanner.with_index_segments(segments.to_vec())?;
}
// Lance intersects the fragment list with the selected segments, so a
// scoped scan must name the segment-covered fragments itself: the universe
// is the listed ids plus the live coverage of the selected segments. An
// empty universe (or an empty-segment, fragment-less assignment) scopes to
// nothing — `with_fragments` with an empty list scans nothing.
let mut wanted: Option<Vec<u64>> = query.fragments.clone();
if let Some(ids) = &mut wanted {
if use_index && !segments.is_empty() {
ids.extend(
crate::segments::covered_fragments(dataset, &table.vector_column, segments).await?,
);
}
} else if use_index && query.index_segments.as_ref().is_some_and(|s| s.is_empty()) {
wanted = Some(Vec::new());
}
if let Some(ids) = wanted {
let fragments = if use_index {
scope(dataset, table, query, restriction).await?
} else {
restrict(query.fragments.clone(), restriction)
};
if let Some(ids) = fragments {
let ids: HashSet<_> = ids.into_iter().collect();
let frags: Vec<Fragment> = dataset
.fragments()
.iter()
@@ -340,6 +470,65 @@ mod tests {
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
}
#[tokio::test]
async fn indexed_only_scores_all_returned_distances() {
let dir = TempDir::new().unwrap();
let vectors: Vec<_> = (0..1024)
.map(|i| {
vec![
(i / 64) as f32 * 100.0 + (i % 64) as f32 * 0.01,
0.0,
0.0,
0.0,
]
})
.collect();
let mut dataset = write_dataset(&dir, &vectors, &vec!["a"; vectors.len()]).await;
dataset
.create_index(
&["vector"],
lance_index::IndexType::Vector,
Some("vidx".into()),
&lance::index::vector::VectorIndexParams::ivf_flat(16, DistanceType::L2),
true,
)
.await
.unwrap();
crate::testing::append_dataset(&mut dataset, &[vec![0.0; DIM]], &["late"]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let mut query = Query {
vector: vec![0.0; DIM],
k: vectors.len(),
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
for nprobes in [None, Some(1)] {
query.nprobes = nprobes;
let (hits, excluded) = indexed_only(&dataset, &table, &query).await.unwrap();
assert_eq!(excluded, 1);
assert_eq!(hits.len(), vectors.len());
for hit in hits {
let index: usize = hit.key[1..].parse().unwrap();
assert_eq!(hit.distance, l2(&query.vector, &vectors[index]));
}
}
dataset
.optimize_indices(&lance_index::optimize::OptimizeOptions::append())
.await
.unwrap();
query.k += 1;
let (hits, excluded) = indexed_only(&dataset, &table, &query).await.unwrap();
assert_eq!(excluded, 0);
assert_eq!(hits.len(), query.k);
assert!(hits.iter().all(|hit| hit.distance.is_finite()));
}
#[tokio::test]
async fn flat_returns_exact_top_k() {
let dir = TempDir::new().unwrap();
@@ -640,7 +829,12 @@ mod tests {
fragments: None,
exact_match_limit: None,
};
assert!(!scanner(&dataset, &table, &query, true).await.unwrap().1);
assert!(
!scanner(&dataset, &table, &query, true, None)
.await
.unwrap()
.1
);
crate::index::build(
&mut dataset,
&table.vector_column,
@@ -650,6 +844,11 @@ mod tests {
)
.await
.unwrap();
assert!(scanner(&dataset, &table, &query, true).await.unwrap().1);
assert!(
scanner(&dataset, &table, &query, true, None)
.await
.unwrap()
.1
);
}
}
@@ -195,6 +195,46 @@ mod tests {
assert_eq!(got, want);
}
#[tokio::test]
async fn indexed_only_keeps_assigned_segments_and_excludes_tail_work() {
let dir = TempDir::new().unwrap();
let mut dataset = testing::write_dataset(&dir, &testing::vectors(64, 4), &["a"; 64]).await;
crate::index::build(&mut dataset, "vector", crate::index::INDEX_NAME, 4, false)
.await
.unwrap();
testing::append_dataset(&mut dataset, &testing::vectors(4, 4), &["b"; 4]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let segments = index_segments(&dataset, "vector").await.unwrap();
let query = Query {
vector: vec![0.0; 4],
k: 100,
filter: None,
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
index_segments: Some(segments),
fragments: Some(vec![1]),
exact_match_limit: None,
};
let (hits, excluded) = query::indexed_only(&dataset, &table, &query).await.unwrap();
assert_eq!(excluded, 1);
assert_eq!(hits.len(), 64);
let tail = Query {
index_segments: Some(Vec::new()),
..query.clone()
};
let (hits, excluded) = query::indexed_only(&dataset, &table, &tail).await.unwrap();
assert!(hits.is_empty());
assert_eq!(excluded, 1);
let empty = Query {
fragments: None,
..tail
};
let (hits, excluded) = query::indexed_only(&dataset, &table, &empty).await.unwrap();
assert!(hits.is_empty());
assert_eq!(excluded, 0);
}
/// named_segment_fragments must carry the logical index name through —
/// a fanout planner groups tasks by name.
#[tokio::test]
@@ -0,0 +1,76 @@
//! weed-vector-cli under `fips.mode = strict` exits at startup when a JWT
//! key is too short for FIPS 140, before it dials anything.
use std::io::Read;
use std::process::{Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
/// Runs weed-vector-cli with `args` under `WEED_FIPS_MODE=strict` and a
/// security.toml holding `security`, without the caller's other WEED_
/// variables, and returns its exit status and stderr. Fails when it is still
/// running after 30 s, which means it accepted the keys.
fn run_strict(security: &str, args: &[&str]) -> (ExitStatus, String) {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("security.toml");
std::fs::write(&file, security).unwrap();
let mut command = Command::new(env!("CARGO_BIN_EXE_weed-vector-cli"));
for (name, _) in std::env::vars_os() {
if name.to_string_lossy().starts_with("WEED_") {
command.env_remove(name);
}
}
let mut child = command
.arg("--security-toml")
.arg(&file)
.args(args)
.env("WEED_FIPS_MODE", "strict")
.current_dir(dir.path())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
loop {
if let Some(status) = child.try_wait().unwrap() {
let mut stderr = String::new();
child
.stderr
.take()
.unwrap()
.read_to_string(&mut stderr)
.unwrap();
return (status, stderr);
}
if Instant::now() > deadline {
let _ = child.kill();
panic!("weed-vector-cli still running after 30 s: it accepted the short key");
}
std::thread::sleep(Duration::from_millis(100));
}
}
#[test]
fn a_short_key_in_security_toml_stops_the_cli() {
let (status, stderr) = run_strict(
"[jwt.filer_signing]\nkey = \"0123456789\"\n",
&["describe", "bucket$table"],
);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("jwt.filer_signing.key (10 characters) is shorter than the 14 characters"),
"{stderr}"
);
}
#[test]
fn a_short_signing_key_flag_stops_the_cli() {
let (status, stderr) = run_strict(
"",
&["--filer-signing-key", "short", "describe", "bucket$table"],
);
assert!(!status.success(), "{stderr}");
assert!(
stderr.contains("--filer-signing-key (WEED_FILER_SIGNING_KEY) (5 characters)"),
"{stderr}"
);
}
Loaded 100 of 1663 files, more files were not shown because too many files have changed in this diff. Show more