Commit Graph
16682 Commits
Author SHA1 Message Date
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