Commit Graph
1759 Commits
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 bc1b805c82 mq: copy a table-backed topic's sealed log data into its Iceberg table (#13256)
* mq: export logstore's log file offset range and control entry checks

The topic table writer decides what is sealed from a partition's file
offset ranges and drops the same control entries compaction drops, so it
calls these instead of keeping copies.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: tell which of a partition's files its leader will not write again

A topic table may only take what is sealed. The fence names a writer
and an epoch, not a file, and each flushed window lands whole as a new
file under it, so every log file but the one holding the highest offsets
is sealed; the newest may still be followed by a window in flight. A
sealed fence takes no more windows, so all of its files are. Parquet
left by mq.topic.compact rewrites earlier logs and is always sealed.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a topic table's copied offsets in its snapshot summary

Each append records seaweedfs.mq.offsets, the first offset of every
partition not yet in the table. A snapshot that rewrote files without
carrying the map defers to its newest ancestor that has one; a table with
snapshots and no map anywhere holds rows of unknown offsets and is not
written to.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: build a topic table's rows from log entries

A message becomes a row of its table: the system columns from the log
entry, then the record's fields by name, or the whole message in _value
for a schemaless topic. Rows are laid out in the table's current schema
through iceberg-go's Arrow mapping, so the Parquet file they are written
as carries the table's field ids and the types Iceberg readers expect.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: compare topic tables by name in topictable

The table writer in the worker has to tell whether topic.conf still names
the table a job was proposed for, by bucket ARN, namespace and name, the
same way the broker compares a configure request with what is stored. The
comparison moves next to the rest of the topic table layout so both call
it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's offset map through maintenance snapshots

Compaction, delete rewrites and manifest rewrites keep a table's rows,
so the offsets a topic table holds are unchanged by them. Their
snapshots now carry the parent's seaweedfs.mq.offsets, so the topic
writer and readers find the map on the current snapshot rather than
only on an ancestor that snapshot expiry may remove.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: start a table's running totals at its first snapshot

Totals were only carried from a parent that recorded them, so a table
whose first snapshot the worker wrote never got total-records or
total-data-files, and no later snapshot could carry them. A snapshot
without a parent adds to an empty table, whose totals are zero.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's sealed log data into its Iceberg table

copyTopicTable reads each partition from the offset the table's current
snapshot records up to what its leader has sealed, through the merged
reader that already serves log files and compacted parquet, and writes
the rows as data files under data/<_partition>/ named by their offset
range. A file holds one partition value, so it never spans partitions or
days, and its rows are one contiguous offset run in offset order.

The append goes through commitWithRetry and records the advanced offset
map in seaweedfs.mq.offsets. Each attempt re-checks that topic.conf
still names the table and that the table still names the topic, and
re-reads the map: a partition another writer moved since this run
planned keeps that writer's offset, and this run's files for it are
removed, so no offset is appended twice. A run that dies before its
commit leaves only unreferenced files for orphan removal. Log files are
left in place; the broker cannot read the table yet.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: run mq_topic_table for topics that name an Iceberg table

The worker registers an mq_topic_table job beside iceberg_maintenance and
runs it in the Iceberg lane. Detection reads every topic.conf under
/topics; a topic naming a table is due once one of its partitions has
128 MiB sealed past the table's offsets or a sealed file 5 minutes old.
Execution takes the filer lock mq.table.<namespace>.<topic>, so one
writer copies a topic at a time, and copies only while topic.conf still
names the table the job was proposed for; a topic that left it ends the
job without failing it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy only into the table whose UUID topic.conf recorded

A table dropped and replaced at the topic's table name still carries
the name, and may carry the topic's property if its creator copied it.
The broker records the UUID of the table it created or adopted in
topic.conf, so the writer checks it before planning and again before
each commit attempt, and stops rather than append the topic's offsets
to a table that is not the one the topic holds.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep keyless and valueless messages in a topic table

The table becomes a topic's only copy once copied logs are deleted, and
the writer dropped what compaction drops: every message without a key
or without a value. Those are data; a Kafka record with a null key is
one. The only control entry the log holds is a publisher's close
marker, which the broker stores without its Ctrl, as an entry with
neither key nor value. IsControlMarker names exactly that, IsControlEntry
keeps its wider rule for compaction, and the writer skips markers only.

A keyless message gets a null _key. A skipped marker's offset stays
below the partition's offset in the map, so the table records it as an
offset that held no message rather than a gap left to fill.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: change a topic's table under its table writer's lock

A configure that left a table checked it for snapshots, then saved
topic.conf. The table writer checks topic.conf before each commit, so a
detach saved between that check and the commit's CAS left a table
holding the topic's data with no topic. The broker now takes the
writer's filer lock, mq.table.<namespace>.<topic>, before the release
check and keeps it through the topic.conf save, so it sees what the
writer committed, and the writer sees the change before committing.

The wait is bounded at 15 seconds: a configure behind a long copy is
Unavailable and retried rather than holding the configure RPC. The lock
key moves to topictable so the broker and the worker share it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: make a topic table's record columns optional

A field's is_required became a required column, so a message missing
that field could not be written and the table writer stopped at its
offset. Once copied logs are deleted the table is the topic's only copy,
so every message needs a row. Record fields now map to optional columns
at every level; the system columns stay required. Adopting a table still
refuses one whose record columns are required, since it could not take
such a message.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq: keep a message its topic's record type cannot hold in _value

A schematized topic's tombstone, or a value that is not a RecordValue
of its type, stopped the table writer at its offset, and once copied
logs are deleted the table is the only copy. Every topic table now has
an optional _value column. A message whose value is empty, does not
parse, carries bytes a RecordValue does not have, names a field the
table lacks, or holds a value its column cannot take gets null record
columns and its raw bytes in _value. A decoded message leaves _value
null. A row is checked whole before any column takes it, so a fallback
leaves no partial row behind.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: copy a topic's history into its table in bounded runs

A run read every sealed offset past the table's map and committed only at
the end, so a topic attached with a long history could not finish within
the job's one-hour timeout: each attempt rewrote the same files, removed
them on cancel, and the map never moved. A run now stops at a file boundary
once it has written 4 GiB and commits the offsets its files cover; the next
detection picks up the rest.

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

* mq: decode a record read back from compacted parquet into its columns

logstore's parquet reader hands back a schematized row as its RecordValue,
which still holds the file's _ts_ns, _key and _offset columns. The row
writer took those for fields outside the table, so every message the copy
read from mq.topic.compact's parquet landed as raw _value with null record
columns. Those three fields are the entry's own and are now passed over.

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

* mq: map a repeated field already typed as a list to one list

The Kafka protobuf and JSON Schema decoders describe a repeated field with
both a ListType and IsRepeated, and their values are one ListValue deep.
mapField wrapped the list type again, so the column became list<list<T>>
and every message with a non-empty repeated field fell back to raw _value.
Avro gives the item type with IsRepeated, which still gets wrapped once.
MQ's own parquet schema already ignores IsRepeated on a list type.

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

* mq: keep a decimal past its column's precision in _value

rescaleDecimal checked only that the rescaled value fit 128 bits, so an
unscaled value from 10^38 up to 2^127 was written into the decimal(38,18)
column, which engines then read as an overflow or null. The value is now
checked against the column's precision, so such a message keeps its raw
bytes in _value like any other value the record type cannot hold.

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

* mq: bound a published decimal before rescaling it

A DecimalValue's scale, precision and bytes come from the publisher,
and rescaling to the column built 10^|18-scale| before checking
anything, so one message with an extreme scale could hold a worker's
CPU and memory on every retry of the copy. A scale or precision beyond
the column's 38 digits, or a magnitude longer than 32 bytes, cannot fit
decimal(38, 18) and is refused before any arithmetic; the message keeps
its row with its bytes in _value like any other value its column cannot
take.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep a topic table's files when its commit's outcome is unknown

A commit whose update of the table entry failed without an answer, a
reset connection or a deadline, may still have been applied by the
filer. The run then deleted its data files and manifests, and
commitWithRetry its new metadata file, leaving a committed snapshot
pointing at files that were gone.

Such a failure is now errCommitOutcomeUnknown, and commitWithRetry keeps
the metadata file for it. The topic table writer reads the table again:
a snapshot it built that is in the current lineage is a commit, kept and
reported as one. Otherwise, or when the table cannot be read, the files
stay for orphan removal, since an update still in flight could land
after the read. Only a refused commit, a conflict or a stopped run,
deletes them.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: count a partition's rows after its last flush

copyPartition returned total and flush() in one statement, and Go does
not order reading total against calling flush, so the rows of the last
file could be left out of the count. The last flush now runs first.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: report the rows a topic table commit kept

A run's rows_written was every row it staged, though a commit attempt
drops the files of a partition another writer already moved, and a run
that commits nothing reported its staged rows all the same. It is now
the record count of the files the committed snapshot added.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: wait for a topic's table writer outside topicConfLock

A configure that moved a topic off its table waited up to 15 seconds
for the table writer's lock while holding topicConfLock, which every
configure, lookup cache miss and rebalance of every topic takes, and a
caller that gave up kept waiting.

The configure now reads topic.conf first and, when the request moves
the topic off the table it names, takes the writer's lock before
topicConfLock, the order the writer keeps since it never takes
topicConfLock. The wait ends when the caller's context does, and a grant
that arrives after that is released. A configure that finds the table
changed under topicConfLock without holding the writer's lock is
Unavailable and retried.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* mq broker: bound the topic.conf read a table change starts with

The read that decides whether a configure must wait for the table
writer runs before topicConfLock, and so before the 30 second bound
lockTopicConf puts on calls made under it. A caller without a deadline
then hung on a filer that took the read and never answered. The read
now gets the same bound of its own, still outside topicConfLock.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: keep what an unanswered maintenance commit may reference

Compaction, delete rewrite and manifest rewrite delete everything they
wrote when their commit fails. When the failure is an update of the
table entry that went unanswered, the filer may have applied it, and
the table then points at data files, manifests and a manifest list that
were just deleted. Those are now left for orphan removal on
errCommitOutcomeUnknown, as the topic table writer already does;
conflicts and other definite failures still clean up. Snapshot expiry
deletes nothing before its commit succeeds and needed no change.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: test a topic table retry that keeps only one partition's files

A run whose commit loses to a writer that copied only one of its
partitions keeps the other partition's file. The test checks that the
retry reports only that file's rows and that each offset lands once.

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

* mq broker: wait for the detach's refused lock request in the table lock test

A fixed sleep did not show the detach had reached the table lock, so a
late goroutine let the lookup pass with nothing waiting. The fake filer
now counts refused lock requests and the test waits for the first one.

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

* mq broker: check the table writer's lock before saving a table change

A configure that moves a topic off its table holds the writer's lock
from its release check through the topic.conf save, but never looked at
it again. A lease that lapsed meanwhile, its renewals failing, may
already be the writer's, which can then commit to the table the
configure is about to detach. The configure now checks that it still
holds the lock right before the save and is Unavailable otherwise.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: check a topic table copy's lock and topic last before committing

Each commit attempt checked the lock, topic.conf and the table's owner
before writing its manifests and manifest list, and nothing after, so a
lease that lapsed or a detach that landed while they were written went
unnoticed. The attempt now checks again once they are written, the last
step before commitWithRetry saves the metadata file and updates the
table pointer.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* worker: read a topic's conf with the topic table job's context

The table writer and detection read topic.conf with ReadConfFile, which
takes no context, so a filer that took the read and never answered held
the job, its worker slot and its renewed table lock, and held up
detection, past any cancel. They now read through
ReadConfFileWithMetadata with the job's or the detection's context, so
a cancelled job ends and lets its lock go.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:29:34 -08:00
Chris LuandClaude Opus 5.5 3f2f625822 s3: publish bucket events to each notification target's MQ topic (#13244)
* mq: report when a published message is acknowledged

Publish now returns a channel the publisher closes once the broker acks
that message, including an ack that arrives on a later stream after a
resend. A caller that has to know its message is stored, such as the S3
gateway answering a request only after its event is durable, can wait on
it with its own bound; callers that do not care ignore it.

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

* s3: build bucket event records in the AWS shape

An Event is what one operation did to one object; Record turns it into
an eventVersion 2.7 record for one rule, and Message wraps that record
in the Records envelope a consumer receives. The key is form-encoded per
path segment as AWS does it, size and eTag are left off removals, and
the sequencer is the filer's commit stamp as 16 hex digits, so one key's
sequencers compare as strings in commit order. The s3:TestEvent message
is built here too.

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

* s3: publish bucket event records to each target's MQ topic

The Publisher runs one worker per enabled target. The worker creates the
target's topic, s3.notify-<target> with 4 partitions and 7 days of
retention, then hands records to the MQ publisher keyed by bucket/key so
one object's events stay in one partition in order. Setup retries with
backoff, so a broker that is down or still taking the balancer lock after
a cold start delays records instead of losing them. A removed or
disabled target's worker stops; its topic is left for retention to age
out, since a forwarder may still be draining it.

Publish queues every record and waits up to 2 seconds, or until the
request ends, for all of them to be acked, and reports whether they
were. A record not acked by then stays queued and is still sent; the MQ
publisher resends it across leader changes. Each target's queue holds
10000 records; past that, and for records whose target has no worker, a
record is dropped. Acked, late and dropped records, the queue depth and
the wait are exported as metrics.

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

* s3api: start a bucket event publisher with the gateway

The gateway creates one event publisher and syncs it with the target
registry whenever the registry loads or changes, so each enabled target
gets its topic and worker. The publisher bootstraps from the broker the
command started beside the gateway, passed in as MqBroker once it bound,
and from every broker the masters list, so a gateway running without its
own broker still finds the cluster's. Broker connections use the
grpc.msg_broker TLS section. Shutdown stops the workers.

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

* s3api: send the test event before storing a notification configuration

Unless x-amz-skip-destination-validation is true, PUT notification
publishes an s3:TestEvent to the topic of every target the configuration
names, in parallel, and fails with InvalidArgument listing the
destinations whose topic did not ack it within the publisher's 2 second
wait. Nothing is stored in that case. The registry checks still run
with the header, and an empty configuration sends nothing.

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

* s3api: publish ObjectCreated events for PUT and POST

A PUT, including a "dir/" marker, publishes ObjectCreated:Put and a POST
upload ObjectCreated:Post, after the filer commit and before the
response, once per matching rule of the bucket's configuration, waiting
for the acks within the publisher's bound. A failed write publishes
nothing and a slow or absent broker never fails the request.

The sequencer is the filer's stamp of the commit. putToFiler records it,
from the routed ObjectTransaction or the lock path's CreateEntry, with
the committed size, into the request so the handler finds it; the marker
write and a create recovered after an ambiguous route return none, and
take the gateway's clock instead.

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

* s3api: publish ObjectCreated events for copy and multipart completion

CopyObject, including a metadata-only copy onto itself, publishes
ObjectCreated:Copy, and CompleteMultipartUpload publishes
ObjectCreated:CompleteMultipartUpload, both after the commit and before
the response; a copy that keeps the connection alive publishes before
its final answer.

The write wrappers these use dropped the transaction response, so they
now return the filer's commit stamp: routedMkFile, writeMultipartObject,
routedVersionedFinalize, routedMultipartFinalize, routedSelfCopy and
finalizeCopyDestination. Writes that go off the owner, through mkFile,
still return none and the event takes the gateway's clock.

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

* s3api: publish ObjectRemoved events for deletes

DeleteObject and DeleteObjects publish ObjectRemoved:DeleteMarkerCreated
when a delete without a version id leaves a marker in place of the key,
in a versioning-enabled or suspended bucket, and ObjectRemoved:Delete
for any other delete, including the delete of a marker by its version
id. The record carries the marker's or the deleted version's id.
DeleteObjects publishes one event per key it deleted and waits for all
of them at once.

The routed delete wrappers now return the filer's commit stamp:
routedDeleteSpecificVersion, routedDeleteNullVersion,
routedDemoteNullVersion and createDeleteMarker; deleteMutationResult
carries it to the handler. A suspended delete uses the stamp of the null
version's delete, since the marker write after it returns none. Deletes
on the lock path go through DeleteEntry, which has no stamp, and take
the gateway's clock.

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

* mq: report the ack of a published record too

PublishRecord now returns the same ack channel as Publish, so a caller
publishing to a topic with a record type can wait for its record to be
stored. Both go through doPublish, which registers the waiter for every
message.

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

* s3: carry bucket events as schematized records

A notification topic now has a record type, EventRecordType, the single
source for its flat snake_case columns: the event, requester, bucket and
object fields, the commit stamp as sequencer, and multipart columns for
later. event_time, event_name and bucket_name are required, the rest
optional, and changes to it are additive only. The topic is configured
with it, with bucket_name and object_key as key columns and the schema
format left empty as for the other schematized topics, and records go
out through PublishRecord.

The record holds raw values: the object key unencoded, the sequencer as
an int64, and nulls where a value is absent, such as size and eTag on
removals. Render turns records into the AWS JSON a destination receives,
the Records envelope with eventVersion 2.7, a form-encoded key and a hex
sequencer, or the test event message for an s3:TestEvent, so forwarders
produce exactly the body the gateway used to publish.

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

* s3: shut a stopped target's publisher down even while it is blocked

With the broker away long enough to fill a partition's unacked buffer,
the worker blocks inside PublishRecord. Removing, disabling or closing
the target only cancelled the worker's context, which the blocked worker
never looked at, so the publisher and its queued records lived on and
resumed sending once the broker came back. Stopping a target now shuts
its MQ publisher down directly, which releases the blocked publish, and
does it in the background so Sync and Close do not wait for the flush. A
publisher that finishes setting up after the stop is shut down at once,
and a worker that dequeues a record after the stop drops it.

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

* s3api: publish nothing for a retried multipart completion

A CompleteMultipartUpload retried after the object committed is answered
from that commit and writes nothing, yet the handler still published an
ObjectCreated:CompleteMultipartUpload, with size 0 since no commit was
noted. AWS sends the event once, for the completion that created the
object, so the handler now publishes only when the request itself
committed.

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

* s3api: take an event's principal from the authenticated identity only

With auth off, the gateway keeps the s3-account-id header the client
sent, and an event's principal_id fell back to it, so any client could
name itself as the requester in the record a destination trusts. The
principal is now the identity name authentication put in the request
context, or anonymous.

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

* s3api: turn notifications off instead of exiting on a bad broker TLS config

The event publisher loaded the grpc.msg_broker client TLS with
LoadClientTLS, which exits the process on a config it cannot use, such
as a cert without its key, so a broker-only TLS mistake took the S3
gateway down even with no notification targets. It now loads it with
TryLoadClientTLS and, on an error, logs it and runs without a
publisher: object writes publish nothing and a notification
configuration's test event fails. It never falls back to an insecure
connection.

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

* s3: count a record dropped while its request waits only as dropped

A record dropped while a request waited for it, by a PublishRecord error
or its target being stopped, was counted dropped where it was dropped,
and then late when the request's wait ran out, which it also sat
through in full. Each queued record now carries a done signal that both
its ack and its drop close, so the wait ends as soon as the record's
fate is known and the drop is not counted again as late. Late still
counts a record that was neither acked nor dropped when the request
answered.

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

* mq: let a caller cancel starting a topic publisher

NewTopicPublisher returned only once a partition lookup succeeded, and
retried the lookup for as long as the broker refused it, with nothing a
caller could stop it with. It now takes a context that bounds the start:
the topic configuration runs under it, and cancelling it stops the
lookup loop and returns an error. A publisher already returned is not
affected. Existing callers pass context.Background().

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

* s3: stop a removed target's publisher that is still starting

A target's MQ publisher was started without the worker's context, so a
target removed while its partitions had no leader kept its publisher
looking them up, and its worker waiting, until a lookup succeeded. The
worker's context now bounds the start, so removing or disabling the
target ends both.

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

* s3: bound each broker's ConfigureTopic during a target's setup

Setup asked each broker in turn to configure the target's topic with
the worker's context alone, so a broker that accepted the call and never
answered held the worker there for good. Each broker now gets 10
seconds before setup moves on to the next, and a stopped worker does not
ask the rest.

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

* s3api: stamp a suspended delete's event with its marker write

A suspended-bucket delete removes the null version, then writes the null
delete marker and points latest at it. Its DeleteMarkerCreated event
took the stamp of the first step, so a write landing between the steps
got a later sequencer although the marker it lost to is what remained.
The event now takes the stamp of the pointer write, the delete's last
commit.

To get it, MkFile, the gateway's mkFile and
updateLatestVersionInDirectory return the CreateEntry stamp, and
createNullDeleteMarker returns it. createDeleteMarker's unrouted path
and writeMultipartObject off the owner now return their write's stamp
too instead of none.

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

* mq: bound each broker's ConfigureTopic when a publisher starts

NewTopicPublisher configures the topic again before its lookups, with
no deadline per broker, so a broker that accepted the call and hung
held the start until the caller gave up, even with a healthy broker
next in the list. Each broker now gets 10s before the next is tried.

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

* s3api: sequence a key's events only with stamps from its owner filer

The previous change stamped a suspended delete's DeleteMarkerCreated
with the null marker's pointer write, but that write goes to the
gateway's default filer, not the key's owner. Filer clocks differ, so a
delete could get a smaller sequencer than the PUT before it, and a
consumer deduplicating on the sequencer would drop it as stale.

Routing the marker write to the owner would move the suspended delete
onto the transaction path, a change to the write itself. Until then the
event goes back to the stamp of the null version's routed delete on the
owner, and gateway clock when the delete is not routed. The same
reasoning applies to the other stamps that change began returning from
off-owner writes, a delete marker or a multipart object written through
mkFile, so those return none again, and MkFile, mkFile and
updateLatestVersionInDirectory go back to returning only an error.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3: count each queued record once as acked or dropped, and late apart

A drop counted the record as dropped and then closed its done channel,
so a request whose wait ran out between the two still saw it pending and
counted it late in the same counter. Each queued record now has a
terminal outcome, acked or dropped, set once by compare-and-swap, and
notification_records_total counts that outcome alone, so every lost
record shows as dropped exactly once.

Late moves to its own counter, notification_records_late_total, counted
once per record when its request stops waiting on it before it is acked
or dropped; that record is still counted acked or dropped when it
settles.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

* s3api: publish the event of a completion recovered after its commit

When a finalize committed but returned an error, completeMultipartUpload
answered from committedCompletion without noting the commit, so the handler
published no ObjectCreated:CompleteMultipartUpload. A retry is answered as
a replay and publishes nothing either, so the event was lost although the
object exists. The recovery now notes the commit when the stored object
holds this attempt's parts, stamped by the gateway clock as the filer's
stamp is not known. One answered from another attempt's commit stays
silent.

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

* s3api: sequence a recovered completion's event with its entry's commit stamp

A completion whose finalize committed but returned an error is answered
from the stored object, and its event took the gateway clock. The stored
entry carries CommitTsNs, the meta log stamp the committing filer gave
the write, from the same sequence as the stamps the routed write paths
return, and peers that replicate the entry keep it. The event now takes
that stamp, and falls back to the gateway clock only for an entry
written by a filer that predates it.

Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:53:18 -08:00
Chris LuandClaude Opus 5.5 04bbf1ae0f filer: keep the default broker off the debug port (#13242)
weed filer -s3 checked the broker port against the filer, metrics,
read-only, WebDAV, IAM and SFTP ports but not -debug.port, which the
debug server binds before the broker starts. weed server already
includes it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:33:00 -08:00
Chris LuandClaude Opus 5.5 45458336e1 s3: run a message queue broker beside every S3 gateway (#13235)
* mq broker: let an embedding command own the broker's start failure and shutdown

startQueueServer now returns an error when the broker cannot start instead
of exiting, binds its port before creating the broker so one that cannot
serve never registers with the master, and stops when an optional
shutdownCtx is cancelled. Profiling setup moves to weed mq.broker, since an
embedded broker read the standalone command's profile flags. weed mq.broker
and weed server -mq.broker still exit on a start failure.

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

* s3: run a message queue broker beside the gateway by default

weed s3 now starts a broker on -mq.broker.port (17777) once it has reached
its filer, using the masters and filer group the filer reports. The broker
is its own gRPC server: it binds the gateway's -ip.bind, advertises the
address the gateway registers with the master, and joins the cluster like
any other broker. It stops with the gateway. A broker that cannot start,
say because the port is taken, is logged and the gateway keeps serving.
-mq.broker=false turns it off.

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

* server: start the message queue broker with the S3 gateway

weed server -s3 now runs a broker beside its gateway, started by the
gateway once it reaches the filer. -mq.broker=false leaves it out. An
explicit -mq.broker or -mq.agent still starts the broker on its own, and
then the gateway does not start a second one. Only that explicit broker
exits the server when it cannot start; the one that comes with -s3 is
logged, so a host already running a broker on the port keeps its gateway.

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

* mini: run the message queue broker beside the S3 gateway

weed mini now starts a broker with its S3 gateway on -mq.broker.port
(17777, below the Linux ephemeral range), binding and advertising mini's
-ip.bind and -ip like the other services. The port joins mini's port
layout, so a taken port moves to the next free one unless it was given
explicitly. The broker stops with the gateway, before the filer it
flushes to. -mq.broker=false or -s3=false leaves it out.

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

* filer: start the message queue broker with the S3 gateway

weed filer -s3 now runs a broker beside its gateway on -s3.mq.broker.port
(17777), the same way weed server -s3 does: it binds and advertises where
the gateway does, takes the filer's -dataCenter and -rack, stops with the
gateway, and a broker that cannot start is logged while the gateway keeps
serving. -s3.mq.broker=false leaves it out.

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

* mini: list the message queue broker when it is running

The S3 gateway now binds its broker's port before it starts serving, as it
does for the Iceberg and Lance listeners, and records whether the bind
worked. Once mini sees the S3 port answer, the result is final: the
progress board shows the broker ready or failed, and the welcome banner
lists its address only when it bound. With -mq.broker=false or -s3=false
neither shows it.

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

* s3: keep the default broker off the gateway's own ports

The broker binds before the gateway binds its ports, so a gateway started
with -port=17777, -port.grpc=17777 or -port=7777 (gRPC port 17777) lost
its port to the default broker and exited. weed s3, weed server -s3 and
weed filer -s3 now compare the broker port with the gateway's HTTP,
HTTPS, gRPC, Iceberg, Lance and metrics ports first. A default broker
port that clashes skips the broker with a warning; a broker port given
on the command line that clashes is an error.

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

* mini: reserve explicitly set gRPC ports before placing other ports

Mini only kept derived gRPC ports free while it placed the other
services, so the broker's default port could take an explicit
-s3.port.grpc=17777 and push the S3 gRPC server to another port. An
explicit gRPC port is now reserved too: the default broker moves off it,
and an explicit broker port on it is rejected.

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

* server: keep the default broker off the ports of the servers it starts

With -volume.port=7777 the volume gRPC port is 17777, the default broker
port. The volume server binds its gRPC port only after a master answers,
so the broker could take it first and the whole process exited.

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

* mini: keep an explicit gRPC reservation when a derived one moves

When the filer's HTTP port was taken and moved, dropping its old derived
gRPC port also dropped an explicit -s3.port.grpc on the same port, so an
explicit -mq.broker.port could share it.

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

* server: bind the broker beside S3 where the gateway binds

With -ip.bind=0.0.0.0 -s3.ip.bind=127.0.0.1 the broker that comes with
the gateway listened on every interface. It now takes the gateway's bind
and advertised address, as under weed s3 and weed filer -s3.

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

* server: keep the default broker off the volume public port

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

* mq broker: report a bad TLS config instead of exiting

The embedded broker loaded grpc.msg_broker TLS through LoadClientTLS and
LoadServerTLS, which exit on a bad config, so a cert without a key or
without grpc.ca took the whole S3 gateway down. The broker now loads TLS
before binding through the error-returning loaders, exported from the
security package as TryLoadClientTLS and TryLoadServerTLS, and returns
the error like any other start failure: the gateway logs it and keeps
serving, while weed mq.broker and weed server -mq.broker still exit.

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

* s3: start the gateway's broker by default only with broker TLS

Without grpc.msg_broker TLS the broker accepts any peer, so the broker
beside weed s3, weed server -s3 and weed filer -s3 now starts on its own
only when grpc.msg_broker has a cert and key in security.toml. Otherwise
it stays off and the gateway logs one line saying so and that
-mq.broker=true (-s3.mq.broker=true for the filer) runs it without TLS.
An explicit true starts it either way and an explicit false keeps it
off. weed mini, a single-process dev setup, keeps its broker on.

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

* filer: keep the default broker off the ports of the servers it starts

weed filer -s3 checked the broker port only against the gateway's ports,
so with -webdav -webdav.port=17777 the broker could bind 17777 first and
WebDAV then took the whole filer down. The check now also covers the
filer's own HTTP, gRPC and read-only ports, its metrics port, and the
WebDAV, IAM and SFTP ports when those run, as weed server does. A
default broker port that clashes skips the broker with a warning; a
clashing -s3.mq.broker.port is an error before the servers start.

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

* server: keep the default broker off the filer read-only and debug ports

The port check beside -s3 left out -filer.port.public and, with -debug,
-debug.port, so a broker on 17777 could still take a port the filer or
the debug server binds. Both are now in the list. WebDAV, SFTP and IAM
were already covered when enabled.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:53:36 -08:00
ec1032d642 filer.remote.sync: a source chunk gone for good no longer wedges the write-back (#13220)
* filer.remote.sync: a source chunk gone for good no longer wedges the write-back

An entry whose chunk the volume servers answer 404 for, even with
readDeleted=true, can never be uploaded: the bytes no longer exist in the
cluster. A volume lost with its disk leaves such entries behind (for
example a filer restored from a metadata backup onto a new volume server
while some chunks had not been written back yet). filer.remote.sync
retried the create event forever, every ~2 s, and since a failing event
holds the directory's processed watermark, no later change under the
mount was ever written back again. We hit this in production: one photo's
chunk answered 404 for hours and more than 11,000 later changes waited
behind it.

Now, once the filer confirms the entry is still the one the event
described (the existing supersession check), the upload ends with
errSourceGone when:

- every location answered 404 for sourceGoneGrace (5 min) over
  sourceGoneMinAnswers (3) attempts in a row, or
- the master cannot locate the chunk's volume at all ("failed to locate",
  the whole volume lost with its disk) for sourceGoneLookupGrace (30 min,
  the filer deletion retry's figure for "volume not found").

It logs one ERROR line naming the path, the chunk's fid and the
destination, with a per-process count, and every caller treats the event
as handled so the offset advances. A path found gone is remembered with
its fid (bounded to 10,000), so later events of the same entry are skipped
at once; any other outcome (success, superseded, another error, a failed
supersession lookup) forgets it and starts the grace again, so a volume
server that has not loaded its volume yet, or a stale location, is not
mistaken for lost data.

Only the source decides. The upload body is wrapped in a recorder that
keeps the first error the chunk reader returned, because remote clients
wrap a body read failure in their own errors (the AWS SDK's RequestError
has no Unwrap). The recorder forwards ReadAt and Seek, so s3manager keeps
reading parts in place. A 404, 5xx, timeout or any other error from the
remote itself never reaches the recorder and keeps retrying as before.

A rename of an entry that was written back now deletes the old key only
after the new one is written: when the entry's local data is gone, the old
key keeps the last remote copy (logged) instead of being deleted before an
upload that can never succeed. The gateway's rename path, which deletes
first, does not acknowledge errSourceGone and keeps failing visibly.

util/http:
- GetAuthenticated (the encrypted chunk read) reports a 404 as ErrNotFound,
  as the unencrypted read paths already do, with the same error text;
  readEncryptedUrl wraps with %w instead of %v and treats a 404 as
  retryable, like the plain read, so it tries the other locations.
- A chunk read is ErrNotFound only when no location of the pass failed
  differently (NotFoundEverywhere): a 404 from one replica while another is
  down, answers 5xx or is throttled does not mean the chunk is gone. This
  is applied once in hedgedChunkPass (both RetriedFetchChunkData paths) and
  in the manifest's retriedStreamFetchChunkData loop.

Tests:
- filer_remote_sync_gone_test.go: a plain and an encrypted chunk served 404
  by a test volume server end in errSourceGone on the third attempt and are
  counted once; a remote that answers 404 with readable chunks never does;
  the tracker's grace, answer count, reset, fid change and remembered path;
  the lookup-miss grace; ReaderAt kept by the recorder; a rename keeps the
  old key when the entry is gone and deletes it after the write otherwise.
- TestGetAuthenticatedNotFound; TestRetriedFetchChunkDataNotFoundEverywhere
  (plain direct, plain stream, encrypted; a 404 and a 503 in either order
  is not ErrNotFound).
- Mutation checks: each fails with readEncryptedUrl back on %v, with the
  write error classified instead of the body's read error, with
  NotFoundEverywhere dropped from hedgedChunkPass, with the old key deleted
  first, and with the recorder hiding ReadAt.
- go vet and go test of weed/util/http, weed/command, weed/filer and
  weed/replication/... pass; weed/util/http also with -race.

* filer.remote.sync: renames keep the old key until the new one holds the content; gone is per entry; missing volumes opt-in

- A sighting is counted per entry content (the sorted chunk file ids),
  not per failing chunk. An uploader reads the parts of a ReaderAt body in
  parallel, so the chunk that fails first changes between attempts; keyed
  on it, the grace restarted every time and a large file missing several
  chunks held the offset forever. The tracker's `seen` map is bounded, and
  the log names the first chunk "and N more" instead of every fid.
- On every rename the old key is deleted only after the new one holds the
  content: also when the event's old entry carries no stamp (an upload
  whose stamp a rename in between refused leaves an unstamped copy), and
  in the superseded branch, where the old key is what uploadCurrentEntry
  copies a remote-only entry from. uploadCurrentEntry reports when the
  current entry's data is gone, and the old key stays then. A multipart or
  system path whose old key cannot be deleted no longer skips the stamp.
- A volume the master cannot locate counts only with
  -sourceGoneVolumeMissing=<duration> (default 0: never): a volume server
  that is down or in maintenance looks the same, and an entry written off
  is not retried. It suits a deployment whose master and volume server run
  as one process.
- filer.remote.gateway's rename writes the new key first, deletes the old
  object after, and keeps it when the source data is gone.

Tests: TestRetriedWriteFileSourceGoneAcrossChunks (two lost chunks read in
turn), TestSupersededRenameUploadsCurrentEntry "uncached between the check
and the upload" and "current entry's chunks gone: the old key stays",
TestRenameOfGoneEntryKeepsTheOldKey "old entry unstamped",
TestSourceGoneGraceFor (lookup miss off by default, on with the flag);
each fails with its fix undone. The test remote's DeleteFile removes the
object, as a real remote does.

* filer.remote.sync: evidence kinds apart, a gone entry counted once, the copy owns its source's cleanup; gateway keeps the old object on a superseded rename

- Lookup misses and 404s no longer share one run of sightings
  (sightingKey = content + grace): with -sourceGoneVolumeMissing set, a few
  minutes of "failed to locate" followed by one 404 met the 404 grace with
  the misses' start and answers.
- observe reports whether this call found the entry gone; a replayed event
  of an entry already gone is skipped without another log line or count.
- A superseded rename whose current entry is remote-only leaves the old key
  to completeRemoteOnlyRename, which removes its source only while it is
  the object the stamp describes; an unconditional delete after it could
  remove a replacement.
- filer.remote.gateway: a superseded rename keeps the old object (logged)
  instead of deleting it before the superseding event has written the new
  key.

Tests: TestSourceGoneTrackerCountsOnceAndKeepsEvidenceApart,
TestSupersededRenameUploadsCurrentEntry "the old key replaced during the
copy"; each fails with its fix undone. The gateway change has no test of its
own (its rename path needs a reachable filer).

* filer.remote.sync: drop -sourceGoneVolumeMissing, a lookup miss keeps retrying

A volume the master cannot locate looks the same whether it was lost or
its server is down, so no default can write such an entry off safely, and
a flag for the one-process layout is not worth carrying. Only a 404 from
every location counts as gone; a lookup miss retries as before.

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

* filer.remote.gateway: a superseded rename settles its old object

A rename the filer has moved past kept the renamed-from object for good,
so every rename followed by a delete or a rewrite before the gateway
reached it left an orphan on the remote. Settle it the way
filer.remote.sync's uploadCurrentEntry does: copy from it when the entry
has become remote-only, and otherwise delete it, since it no longer holds
the entry's content.

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

* filer.remote.sync, filer.remote.gateway: a superseded rename copied from a later rename's source settles its own old key

When the entry became remote-only through another rename onto it, the copy
reads that rename's source and removes it, and nothing read or removed the
event's own old key any more. Delete it then, in both commands.

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

* filer.remote.gateway: reset cached remote clients after the superseded-rename test

A cached client kept the previous run's recorder, so the test failed under
-count above one.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:15:37 -08:00
Chris LuandClaude Opus 5.5 0872953b81 mount: resolve NFS file handles across a weed mount restart (-nfsExport) (#13020)
* mount: persist a created file's entry at create time under -nfsExport

A file created over NFS gets a handle at create time. With creation
deferred to flush, a mount that stops before the flush leaves no entry for
the next mount to resolve that handle to.

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

* mount: resolve NFS file handles of files an earlier mount had open

With -nfsExport, the mount records on the filer the path of each file it
has open, keyed by inode, and drops the record a minute after the last
close. A "." lookup on a node id the mount does not know reads that
record, so the NFS server can reopen its files after the mount restarts or
another mount takes over. A failed read answers EIO rather than ESTALE.

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

* mount: record NFS handles at open, not on every path refresh

A writeback close flushes after the last release, and the flush refreshes
the handle's path. Recording there renewed the record of a file no longer
open, so it was never removed. Opens and creates now record, and a path
refresh only moves an existing record.

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

* mount: leave writeback creates deferred under -nfsExport

With writeback caching an eager create runs as an async filer RPC that an
unlink does not wait for, so a quick create+unlink could bring the name
back. Writeback mounts already accept losing unflushed files on a crash.

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

* mount: retain a recorded handle path only once it matches the file

A path read from the filer record was retained before the lookup checked
it, so a stale one kept answering ESTALE without reading the record again.
It is now retained right before LookupHandle, and never over a forgotten
inode or path the table already holds.

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

* mount: count NFS handle opens, keep other mounts' records, retry writes

A reopen that attached a new handle before the close registered its
release left a removal pending for an open file; opens are now counted.
Records carry the writing mount's signature, so a delayed removal leaves
a record another mount wrote since. A failed write is retried while the
inode's state is unchanged, and the put runs under the attempt context.

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

* mount: keep one NFS handle registration per mount in an inode's record

Two mounts with the same file open shared one record, so the one that
closed last removed the path the other still had open. Each mount now
replaces or drops only its own registration, and a lookup uses the newest.

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

* mount: name a mount's NFS handle registrations by host and mount directory

A restarted mount drew a new random signature, so it never replaced or
removed the registrations its predecessor left for files it had open.

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

* mount: take turns on an NFS handle record through the lock manager under -dlm

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

* mount: retry an NFS handle record update when its lock is not granted

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

* mount: renew an NFS handle record's lock for the whole update

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

* mount: resolve an NFS handle record to the newest path under the mount root

Another mount rooted elsewhere could hold the newest registration of a
hard-linked inode, hiding this mount's own valid path.

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

* mount: register an NFS handle at the path the mount knows now

A rename could move the inode after an opener read its path but before
the new handle was registered, so the record kept the old path; a stale
opener could also move an existing record back.

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

* mount: keep no NFS handle records with -filer.tokenFile

The filer refuses KvGet and KvPut to scoped tokens, so the records would
only fail: log at startup instead, and keep the in-process handle support.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:31:17 -08:00
Chris LuandClaude Opus 5.5 f65234685a filer.sync: check the stream bottleneck test by peak jobs in flight (#13233)
TestConcurrencyIneffectiveOnStreamBottleneck compared the wall-clock
rates of separate runs at concurrency 32 and 512 and failed on a loaded
32-bit runner when one run took 1.6x longer than the other. The ratio
measured runner load, not the processor.

Record the most jobs that ran at once instead. While it stays below the
smallest limit, the limit never holds back an event, which is why a
larger -concurrency cannot help a stream-limited sync.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:01:24 -08:00
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
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 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
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
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
Chris LuandClaude Opus 5.5 2b0bff0135 filer.sync: warn when the source metadata log no longer covers the sync (#13143)
* filer.sync: warn when the source metadata log no longer covers the sync

A sync replays the source's metadata log from its saved position, or from
the oldest log file when it has none. Once older log days are purged, a
position older than the log silently skips the purged changes, and a fresh
sync never copies entries whose last change was purged, so the target ends
up incomplete without any sign of it.

At start, compare the position with the oldest log file the source keeps;
for a fresh sync, look for a child of the source path whose last change
(commit time, or mtime for entries without one) predates the log, and log
a warning naming it.

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

* filer.sync: skip excluded and multipart upload entries in the log gap check

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

* filer.sync: run the log gap check without delaying the subscription

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:56:31 -08:00
50f7c73101 s3 backend: HTTP/1.1 client defaults for disable_http2 (#13126)
* s3 backend: HTTP/1.1 client defaults for disable_http2

## Problem

`disable_http2` (#11897) keeps the cloud tier's S3 client on HTTP/1.1, so every tier upload and range read gets a connection of its own. The rest of the client still has the defaults sized for one multiplexed HTTP/2 connection:

- Go's idle pool keeps only 2 connections per host, so a burst of concurrent range reads redials TLS for almost every request once the burst is over and the next one starts;
- the wait for response headers is the 60 s bound every tier client has;
- the SDK retries 3 times.

On a Ceph RGW-based S3 service, HTTP/2's small flow-control window held tier uploads at 18 MB/s and made 24 concurrent cold scans take 52 s each; on HTTP/1.1 they took 3.7 s each, but only with a larger idle pool, a shorter header bound and more retries for the 503 SlowDown answers that the extra parallelism draws.

## Fix

With `disable_http2 = true` the tier client also gets:

- an idle pool of 100 (`MaxIdleConns` and `MaxIdleConnsPerHost`);
- `ResponseHeaderTimeout` of 30 s;
- `MaxRetries` 5, so the SDK's retryer backs off on 5xx, SlowDown and throttling.

`max_connections` and `idle_connection_timeout_seconds` apply as before. Without `disable_http2` the client is unchanged. The scaffold `master.toml` mentions the defaults.

## Tests

`TestS3BackendHTTP1ClientDefaults` in `weed/storage/backend/s3_backend/s3_sessions_test.go`: with `disable_http2` the transport has the idle pool and the 30 s header bound, and the client 5 retries; without it (and with `max_connections` set) the client keeps the SDK's retries, the default idle pool and `s3ReadTimeout`. It fails without the change.

`go vet ./weed/storage/backend/s3_backend/` and `go test ./weed/storage/backend/s3_backend/`: ok. `go build ./weed`: ok.

* s3 backend: keep the larger idle pool for every tier client

A tier client on a plain http:// endpoint, or on a TLS service that offers
no HTTP/2, speaks HTTP/1.1 without disable_http2 and had the same 2 idle
connections per host, so each burst of concurrent reads redialed. HTTP/2
keeps one connection, so the pool size does not change it. The header
bound and retries stay with disable_http2.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:53:24 -08:00
442e0a24c6 iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s (#13138)
* iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s

## Problem

The Iceberg REST catalog vends table-scoped S3 sessions on load and create with one process-wide lifetime, `-iceberg.credentialDurationSeconds` (default 3600). A client has no way to ask for less, and nothing can go below STS's 900 s floor. Some deployments want short sessions for some callers (a one-off read, a session handed to a less trusted process) without shortening them for every client: a process-wide 900 already breaks clients that keep a loaded table object for longer than its session (PyIceberg does not refresh vended credentials; DuckDB, Spark and Trino re-load and are fine).

The Iceberg REST spec has no parameter for a credential lifetime. The precedent is `DurationSeconds` on AWS STS and on Lake Formation's `GetTemporaryGlueTableCredentials`.

## Fix

- **Request header** `X-SeaweedFS-Credential-Duration-Seconds` on a load or create that asks for vended credentials (`X-Iceberg-Access-Delegation: vended-credentials`). A positive whole number of at most 9 digits is passed to the vendor; a missing, malformed, zero, signed or overlong value is ignored without an error, so clients that never send it see no change.
- **It can only shorten a session.** The vended lifetime is `min(asked, configured)`; with no configured duration the ceiling is STS's `TokenDuration`, capped at `MaxSessionLength` as STS caps it. A request at or above the ceiling changes nothing (the configured duration is sent, as before).
- **Floor:** new `-iceberg.credentialMinDurationSeconds` (`-s3.iceberg.credentialMinDurationSeconds` on `weed server` and `weed mini`), **default 900, which keeps today's behaviour exactly.** A request below the floor is raised to it. Values outside 1-900 mean 900, with a warning at startup; the setting can only lower the floor.
- **STS:** `AssumeRoleForPrincipalRequest` gains `MinDurationSeconds`, a per-request floor honoured only within (0, 900]. Only the catalog's vend sets it, and only when the client actually shortened the session: a vend at the configured duration keeps the 900 s floor (so a configured `credentialDurationSeconds` under 900 is still refused), and AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials and every other action keep 900 through the unchanged `validateSessionDurationSeconds`. `MinSessionDurationSeconds` names the 900.
- **Caching:** load answers now send `Vary: X-Iceberg-Access-Delegation, X-SeaweedFS-Credential-Duration-Seconds`, so a cache never hands a session vended for one lifetime to a request that asked for another.
- The client learns the lifetime it got from `s3.session-token-expires-at-ms`, as today. The Lance namespace vend passes 0 (unchanged).

## Tests

- `weed/s3api`: `TestVendDurationRequestOnlyShortensTheSession` (real STS and trust policy; the lifetime read from the session JWT's `exp - iat` and `max_dur`): nothing asked keeps 3600; 120 honoured; 60 at a floor of 60; 7200 capped to 3600; 30 raised to a floor of 60; floor unset, 900 or 1200 keeps 900. `TestVendFloorDoesNotLowerAssumeRole`: with the floor at 60 the vend mints 60 s (positive control) while AssumeRole and AssumeRoleWithCredentials on the same server refuse 60 s. `TestVendDurationRequestRespectsMaxSessionLength`, `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`.
- `weed/iam/sts`: `TestSessionFloorIsLoweredOnlyForTheRequestThatAsks`.
- `weed/s3api/iceberg`: `TestCredentialDurationHeaderReachesTheVendor` (the accepted and ignored header forms), and the Vary test updated.
- Each rule undone turns its test red (request ignored: `TestVendDurationRequestOnlyShortensTheSession`, `…RespectsMaxSessionLength`; floor applied to every vend: `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`).
- `go vet` and `go test` of `weed/s3api`, `weed/s3api/iceberg`, `weed/iam/sts`, `weed/iam/integration`, `weed/command` pass, `-race` on `weed/s3api/iceberg`, and `weed` builds.

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

* iceberg: let a shortened vend fit a caller credential with less than 900 s left

A vend the caller shortened below 900 s (with a lower catalog floor)
needs only that floor of the caller's credential to remain, not 900 s.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-30 10:52:41 -08:00
576eb98ce9 mount: leave -cacheMinFreeSpace free on the chunk cache's disk (#13124)
* mount: leave -cacheMinFreeSpace free on the chunk cache's disk

weed mount sizes its on-disk chunk cache by -cacheCapacityMB alone and
preallocates each cache file in full when it creates it. With a capacity
larger than the free space of the disk holding -cacheDir, the cache takes
that disk down to nothing: the preallocations run until fallocate fails,
and chunk writes fill the rest. The mount's metadata cache (a leveldb
store under -cacheDir) and the swap files of dirty pages (-cacheDirWrite,
which defaults to -cacheDir) live on the same disk, so once it is full
their writes fail with ENOSPC, and writes whose dirty pages spill to
swap return EIO to the application. The same happens when several mounts
share a cache disk and together are configured beyond it.

-cacheMinFreeSpace is the free space the cache leaves on that disk,
written like the volume server's -minFreeSpace: a percentage like 1 or a
size like 10GiB, 1 by default, as for volume servers.

- When the cache opens, its disk layers shrink to the space above the
  floor, counting the cache files already in the directory as the cache's
  own. With no room the disk tier keeps no files.
- Each new cache file preallocates only what the disk holds above the
  floor at that moment, so the files of one cache, or the caches of
  several mounts opening together, stop reserving at the floor.
- A chunk write that lands in blocks its file already holds, preallocated
  or written, goes ahead as before, even with the disk under the floor.
  A write that takes new disk space, into a file a rotation truncated or
  where nothing could be preallocated, goes ahead only while the space
  above the floor covers it. The disk is read at most once a second, and
  the cache counts what it takes in between, so it cannot run past the
  floor between readings. A rotation gives the truncated file's blocks
  back, so the write after it reads the disk again.

A chunk the cache cannot place is not cached, like any other miss. The
webdav server's cache passes no floor and behaves as before.

* mount: read the cache disk on every write that takes space, leave the index files room

Review follow-ups.

- take reads the disk each time, instead of once a second less what the
  cache took since, so a write sees what other mounts sharing the disk
  wrote, and what a rotation gave back. It runs only for writes past the
  blocks a file already holds, and a statfs costs little next to the
  write.
- The index files (.idx and the leveldb maps) grow by a few dozen bytes a
  chunk beside the data files that the cache size counts. Sizing leaves
  them a sixteenth of the room above the floor.
- The cache's own files count as room by the blocks they hold, so a file
  that was preallocated but not yet written when the mount exited counts
  in full when the cache reopens.
- weed fuse checks -o cacheMinFreeSpace in the parent as well: the parent
  waits for the child's signal, and a child that rejects the value never
  sends it.

* mount: keep the resolveCacheDirs doc comment on resolveCacheDirs

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

* mount: say -cacheMinFreeSpace stops new disk space, not every chunk

Under the floor the cache still fills the blocks its files already hold.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:48:28 -08:00
Chris LuandClaude Opus 5.5 d49876a7aa filer: every filer store reads KV keys in batches (#13119)
* filer: read KV keys a few at a time for a store without batch reads

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

* abstract_sql: read KV keys with one query

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

* redis: read KV keys in one pipeline

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

* etcd: read KV keys in read-only transactions

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

* mongodb: read KV keys with one query

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

* cassandra: read KV keys concurrently

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

* hbase: read KV keys concurrently

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

* elastic: read KV keys concurrently

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

* arangodb: read KV keys with one request

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

* foundationdb: read KV keys in one transaction

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

* ydb: read KV keys with one query

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

* tarantool: send KV reads before waiting for any

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

* filer: every filer store reads KV keys in batches

KvBatchGet moves from the optional KvBatchReader onto FilerStore. A listing
now reads the hard link records of its waiting entries together from any
store, a path-specific one included.

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

* tikv: count only the record reads of a listing in its test

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

* filer: return every batched key that pads to the same stored row

SQL, MongoDB and YDB pad a short KV key with zero bytes, so "short" and
"short\x00" read the same row. KvBatchGet kept only the last such key.

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

* filer: read keys in a plain loop when KvGetEach runs one at a time

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 23:10:49 -08:00
Chris LuandClaude Opus 5.5 46b10efcce mount: refuse a stale truncate over a peer's chunks and keep later times when merging a flush (#13100)
* mount: refuse a merge whose local truncate cuts chunks a peer wrote

A flush refused by IF_ENTRY_EQUAL replays the handle's truncate onto the
stored entry. The truncate was made over the handle's base, so a chunk a
peer committed after that base was dropped or clipped silently, losing
data the peer had already fsynced. Like a stale whole-file rewrite over a
peer's chunk change, it now fails the merge. A base chunk the peer only
shortened carries no peer data and is still cut.

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

* mount: keep the later mtime and ctime when merging a delayed flush

The merge took every attribute the handle changed from the handle, so a
flush that waited behind a peer's commit moved mtime and ctime back to
the handle's older write. Each time is now merged as one value (seconds
and nanoseconds were merged field by field, so a moved second could take
the peer's nanoseconds): the handle's time stands unless a peer moved it
too and later.

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

* mount: let a truncate merge pass the handle's own committed chunks

A flush whose commit answer was lost finds its own chunks in the stored
entry while its base is still the older one. Those chunks are the
handle's writes, not a peer's, so they do not refuse the merge.

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

* mount: do not keep a stored copy of a chunk the merge re-adds from the handle

A stored chunk the base lacks but the handle holds is the handle's own
commit whose answer was lost. The merge appends the handle's chunks after
the stored ones, so keeping the stored copy referenced the chunk twice.

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

* mount: take the manifests of a failed flush's fold for the handle's own chunks

A flush can commit its folded manifests and lose the answer. The handle
reverts to the member chunks and keeps its old base, so the next merge
found the stored manifest, knew neither its file id nor its key, and
refused it as a peer write across the handle's truncate.

The handle now remembers the folds of flushes that failed over its base,
and a merge unfolds them in the stored entry before comparing, so the
members match the handle's chunks. A peer's manifest is still refused.

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

* mount: take a retried flush's own stored fold for its own chunks

The client retries a request whose connection dropped, and the first try
may have stored the flush's folded manifests. The retry is then refused
over them before the fold is recorded as failed, and the merge took the
manifest for a peer's write across the handle's truncate. The merge now
unfolds the flush's own fold in the stored entry as well; the condition
still names the entry as stored.

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

* mount: keep every fold the filer may hold instead of the last four

Dropping the oldest of four could forget the fold the filer committed,
and the merge then refused that manifest again. A fold is now kept only
when the flush failed without the filer's answer, or when the refusal
lookup shows it stored, so a refused flush no longer adds one, and the
list ends with the base.

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

* mount: keep a flush's fold when its first request may have been stored

A precondition verdict on a retried send does not prove the first send
stored nothing, and a failed refusal lookup then hid that it had. The
create now counts the sends of the request that carries the fold and
keeps the fold whenever the flush fails and that request was sent more
than once or never got the filer's answer. That covers both flush paths,
so revert is back to only restoring the chunks.

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

* mount: drop the failed folds a refused create shows were not stored

A refusal means the stored entry moved off the handle's base, so no
request guarded by that base can store another fold. After the refusal
lookup the handle keeps only the folds whose manifests the stored entry
holds, at most one, which bounds the list over a base.

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

* mount: bound the failed folds a handle keeps over one base

Flushes that keep failing with no filer answer each saved a new fold the
filer may hold, so the list grew for as long as the outage lasted. Once a
handle keeps maxFailedFolds folds over its base, its flushes send their
chunks unfolded for the filer to fold, and no kept fold is dropped.

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

* mount: keep the failed folds a refusal lookup does not show

The refusal comes from the file's write owner, but the lookup after it can
read a filer that lags behind and still shows the base. Pruning the folds
against that read forgot a fold the owner had stored, and once its manifest
showed up a pending truncate took it for a peer's chunk on every flush. The
maxFailedFolds limit bounds the list, so the folds stay until the base moves.

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

* mount: drop the chunks a failed flush sent that the handle has cut since

A flush that commits with its answer lost, then a truncate of the handle,
left the next merge with the handle's own committed chunks in the stored
entry, outside both base and the handle. The truncate check took them for
a peer's writes and refused every later flush over the base. A failed
flush now records the file ids of the chunks it sent that base lacks, and
the merge drops those the handle no longer holds: it cut or replaced them.

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

* mount: copy the failed flush's sent set with a loop

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

* mount: keep folding past maxFailedFolds instead of sending chunks unfolded

The filer folds a flat chunk list itself, into manifests the handle does
not know: a lost answer then left one of them across a pending truncate,
and an acknowledged one gave the handle flat chunks under a folded base.
Flushes fold as before, and the handle stops keeping folds past the limit
while it still records the chunks they sent.

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

* mount: read the stored manifests a refused merge cannot name

A fold changes no content, but a manifest the handle does not know sat in
the stored entry as one chunk: across a pending truncate it refused the
merge, though it can hold the handle's own chunks (a fold it did not keep,
or one the filer made). When the merge is refused, the flush reads those
manifests, replaces them with the chunks they hold and merges again.

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

* mount: hold the chunks the filer stored after a plain acknowledged flush

The filer folds a flat chunk list (the mount's own fold failed), and the
acknowledgement makes the stored entry the base while the handle kept the
flat chunks. A later merge took them for writes of the handle, which can
bring back chunks a peer's truncate removed. As after a merge, the handle
now takes the stored chunks, keeping those attached since the request.

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

* mount: keep a bounded record per failed flush instead of a growing set

The set of chunk ids failed flushes sent grew with every overwrite while
commits failed, and each failure copied it whole. Each failed flush the
filer may have stored (a send got no verdict) now keeps one record, its
fold and the ids it sent, built once and at most maxFailedFlushes over a
base. Past that, a merge refuses the chunks of a flush it did not keep
that the handle has cut since, as a peer's.

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

* mount: register the chunks a rebase or install gives the handle for reads

A handle that takes the stored chunks after a flush (or a peer's, after a
merge) can get manifests the filer made, and resolving them needs the
file's read token. rebaseEntry and installRewrittenChunks now record the
chunks under the file's path before the read view resolves them.

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

* mount: keep every chunk id a failed flush sent, cap only the folds

Past four failed flushes over one base the handle stopped recording what a
later flush sent. If that flush was stored with its answer lost, a truncate
of its chunks was refused as a peer's write and kept failing after the
filer came back. The ids now go into one set shared by the base's marks,
each kept once and never copied, until the base moves. Only the folds stay
capped: a stored manifest past the cap is read when a refused merge cannot
place it.

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

* mount: fail a flush over a peer's chunk change unless -concurrentWriteMerge

A content flush refused because another mount committed first used to
merge the handle's writes onto the stored entry. That merge now runs
only with the new -concurrentWriteMerge mount option (off by default).
By default a stored chunk change that neither the base nor the handle
holds fails the flush with EIO, and a peer's chunk event no longer
rebases a dirty handle. Attribute-only changes and the handle's own
commits (a lost answer, its own truncate) still merge.

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

* mount: recognize the shortened references a failed flush sent

A truncate shrinks a base chunk in place, keeping its file id. A failed
flush that may have stored such a reference recorded only file ids base
lacks, so a later truncate saw its own stored reference as a peer's
change and failed with EIO by default.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:34:30 -08:00
Chris LuandClaude Opus 5.5 a963c1309c worker: purge the filer metadata log from a lifecycle job that keeps it past every TTL (#13101)
* worker: share the one-filer-per-store selection with other filer jobs

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

* worker: add a meta_log_purge job that keeps the log past every TTL

The job deletes whole metadata log days once per filer store, keeping
every day that the longest filer.conf TTL, the longest S3 lifecycle rule,
a registered retention floor or a running replay job's cursor still
needs. A floor input that cannot be read stops the run before anything
is deleted.

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

* worker: register meta_log_purge in the lifecycle lane

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

* maintenance: stop purging the metadata log from the default scripts

The meta_log_purge job now deletes old log days, keeping what TTLs,
lifecycle rules and replay jobs still need. fs.log.purge stays for
manual use.

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

* worker: let an idle filer_ttl rule's read position release the log

filer_ttl no longer needs events up to read_ns, and an idle rule keeps an
old ts_ns while read_ns advances, so the floor follows the later of the
two.

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

* worker: cap min_retention_days so a huge value cannot overflow

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

* worker: show the min_retention_days limit in the admin form

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

* worker: give a registered retention floor the store's filer client

A floor that only gets a context cannot tell which cluster or store it
answers for, so it cannot ask that cluster's master or read the store's
own settings. Pass the filer client the job already holds.

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

* worker: keep the log an unfinished lifecycle walk will replay

A cold-start or recovery walk that resumes across runs rewinds its
shard cursor to the walk's start minus the longest lifecycle TTL once it
completes. Until then only its walk checkpoint records that start, so a
walk running for more than a day let the purge delete the creation
events the rewound replay reads. A checkpoint with buckets done or
partly walked now holds the floor at started_ns minus that TTL.

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

* worker: hold the walk start until the checkpoint goes stale

A walk clears its checkpoint in finish() before each of its shards saves
the rewound cursor, so a purge scan that read the old shard cursor and
then the cleared checkpoint saw neither. A cleared checkpoint keeps
started_ns, so every live checkpoint now holds the floor at its start
minus the longest lifecycle TTL. A finished one stops holding once it
has not been saved for cursorStaleAfter.

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

* worker: read walk checkpoints before the shard cursors they rewind

A purge scan that read a shard cursor, then a checkpoint that a later
walk had already replaced, saw neither the earlier walk's hold nor the
rewind its shards saved. A walk replaces its checkpoint only after the
previous walk's rewind is on disk, so reading the checkpoints first
always sees one of the two.

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

* lifecycle: save a fresh walk's checkpoint at its first progress

A walk that progressed during its first save interval and then stalled
for more than a day had no checkpoint on disk, so the metadata log purge
saw nothing holding the days its completion replays. A fresh walk now
saves on its first finished entry or bucket; a resumed walk already has
its record on disk and keeps the interval.

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

* lifecycle: rewrite an unchanged shard cursor so its mtime stays fresh

A shard stuck on RETRY_LATER saved identical bytes each pass, and
SaveInsideFiler skips identical content, so the file's mtime aged past
the meta log purge's staleness cutoff while the shard still needed it.

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

* worker: keep the log day a reader from the cursor lists first

Log files are named for their flush start, so a file from just before
midnight holds events after a cursor just past it. The reader backs off
one flush interval before choosing its first day; the purge now does too.

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

* worker: stop the meta log purge on an unreadable lifecycle policy

LoadCompileInputs reports a bucket whose lifecycle XML does not parse
separately from its error, so the purge used the shorter floors and
deleted days that bucket's rules may need once the policy is fixed.

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

* worker: read shard cursors with the replay's loader in the meta log purge

A shard cursor the replay refuses, such as an empty object, decoded as
a zero position and released the purge; it now stops the run instead.

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

* worker: saturate the meta log purge's TTL plus a day

A lifecycle TTL near the largest duration wrapped negative once a day
was added, so the purge fell back to the shorter floors; the walk hold
at started_ns minus that TTL likewise dropped below zero and was lost.

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

* worker: leave disabled lifecycle rules out of the meta log purge floor

AllActivePriorStates activates every compiled rule, so a disabled rule
still held the log for its TTL, and disabling it could not release it.

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

* worker: compute the meta log purge floor in SafeKeepFrom

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

* shell: fs.log.purge keeps the logs the meta log purge floor needs unless -force

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

* shell: run the fs.log.purge floor test without a master client

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:33:26 -08:00
db0ec9e9b3 filer: count and time the gRPC requests by method (#13107)
* filer: count and time the gRPC requests by method

The filer's request metrics cover its HTTP API. The mounts and the S3
gateway reach it over gRPC, so on a cluster used through them the filer
reported its store operations and nothing about the requests behind
them: how many lookups, creates, renames or listings arrive, how long
each kind takes, how many end in an error.

Two metrics for the gRPC port, filled by a unary and a stream
interceptor: SeaweedFS_filer_grpc_request_total{method, code} and
SeaweedFS_filer_grpc_request_seconds{method}. A stream is counted when
it ends, and timed unless the client holds it open (a subscription, a
client stream). A lookup that finds nothing returns ErrNotFound without
a status; it is labelled NotFound rather than Unknown.

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

* filer: label a call ending in its context's error as gRPC reports it

A handler that returns ctx.Err() reaches the client as Canceled or
DeadlineExceeded; status.Code labelled it Unknown.

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

* filer: count a health watch without timing it

grpc.health.v1.Health/Watch stays open until the client leaves, so its
duration is the connection's lifetime, like a subscription's.

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

* metrics: dashboard panels for the filer's gRPC requests

Calls, errors by code, and p99/p50 durations by method, in the Filer row.

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

---------

Co-authored-by: MapleWhiteZZZ <18653045+MapleWhiteZZZ@users.noreply.github.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-29 10:26:52 -08:00
Chris LuandClaude Opus 5.5 207aa69a9d filer: keep the metadata log in its own collection, with room reserved for it (#13102)
* filer: grow the metadata log collection on its own, fall back when it is full

metaLog.volumeGrowthCount (default 2) is sent with assigns into the
metadata log collection, so it grows by a few volumes instead of the
master's default growth. When that collection cannot take the piece, the
assign falls back to the collection the log uses without the override, so
a full cluster does not stall the log.

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

* filer: keep the metadata log in its own collection by default

metaLog.collection now defaults to filer-meta, so purging old log days
empties whole volumes instead of leaving log chunks scattered across the
default collection's volumes. Setting it to "" keeps the log in the
filer's -collection as before.

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

* volume: default -max to 10 to leave room for the metadata log collection

The default collection still grows by 7 volumes; the extra slots keep
the filer's metadata log collection (2 volumes by default) from taking
them. Go and Rust volume servers share the new default.

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

* filer: bound the meta log collection's share of the assign budget

A meta log collection that cannot grow (for example a replication the
cluster cannot place) keeps answering with retryable errors, so the
first assign used the whole shared budget and the fallback was never
tried. Give it 10s, then fall back, and skip it for a minute after a
failure instead of waiting on it at every flush.

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

* filer: name the default meta log collection so no bucket maps to it

A bucket named filer-meta mapped to the same collection, and deleting
it from the admin page or weed shell drops the collection directly at
the master, taking the metadata log with it. Bucket names cannot
contain "_", and filer group buckets map to "<group>_<bucket>".

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

* filer: clear the meta log overrides after the viper test

Setting the collection back to its default value kept an explicit
override, so the defaults test passed even without the SetDefault.

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

* filer: retry the meta log collection once its fallback also fails

The pause after a failed meta collection assign kept pieces on the shared
collection for a full minute even when that assign failed too, so meta
volumes that finished growing stayed unused while every flush failed.

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

* filer: pick a default meta log collection no grouped bucket maps to

Filer group "_filer" with bucket "meta" maps to "_filer_meta". The
default now keeps its only "_" in front, and the test checks every
group and bucket split of it.

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

* filer: default the meta log collection to _meta

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

* filer: keep the default meta log collection on bucket delete

A filer that logs elsewhere did not treat _meta as reserved, so deleting a
bucket a storage rule maps to _meta dropped the collection other filers
write their logs to.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 10:01:16 -08:00
Chris LuandClaude Opus 5.5 4ff3147ee5 worker: filer_ttl job removes expired rows from stores without native TTL (#13084)
* worker: add a filer_ttl job that walks filer.conf TTL paths

A filer store without native TTL keeps the rows of expired entries until
something looks them up or lists their directory. The job lists every
TTL path subtree once per filer store, so the filer drops the expired
rows it meets.

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

* worker: register the filer_ttl job in the lifecycle lane

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

* filer: re-check an expired entry under its path lock before a listing deletes it

A listing deleted the expired entries it collected by path after the page
was read, so a write that replaced one in between lost its new row. The
delete now re-reads the row under the lock writers take, and in one
conflict-checked transaction on stores that refuse a commit over another
writer's change; anything but a still-expired row is kept.

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

* worker: read each filer store's own filer.conf, chunk-backed included

Filers with separate stores keep separate filer.conf files, so one
filer's rules could hide another store's TTL paths. A config stored in
chunks read as empty. An unreadable config now fails the detection
instead of reading as no rules.

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

* command: count filer_ttl among the mini default job types

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

* worker: resume an unfinished filer_ttl walk from its checkpoint

The walk position is saved in the job's filer store every 30s and at
the first failure, keyed by store signature, and cleared when a pass
completes. The next run skips the prefixes and subtrees already walked,
unless the TTL prefix set changed or the pass is over 7 days old.

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

* worker: save the filer_ttl checkpoint as soon as a walk fails

The first failure froze the checkpoint but only the end of the run saved it,
so a worker killed while walking later prefixes lost it. stop now saves it at
once; the end of the run saves again only if that save failed.

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

* worker: keep a path TTL rule from expiring the filer_ttl checkpoint

A filer.conf TTL rule over /etc/ gave the checkpoint that rule's TTL, so an
interrupted pass could lose its record long before checkpointMaxAge. The
checkpoint is now written with its own TTL of checkpointMaxAge, which the
filer keeps instead of the rule's.

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

* worker: remove a filer_ttl checkpoint the new pass will not resume from

An overwrite keeps the stored entry's Crtime, and the checkpoint's TTL counts
from it, so a pass that replaced a rejected record could lose its own record
before checkpointMaxAge. load now deletes a record it rejects, and the new
pass creates a fresh one.

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

* worker: expire filer_ttl entries from metadata events per TTL rule

Each run replays every filer.conf TTL rule's metadata events from that
rule's cursor up to the run start, and looks up each entry whose TTL has
passed so the filer removes its row. The first entry not yet due holds the
rule's cursor, so a later run replays it. A rule without a cursor, or
whose TTL changed, is listed once to reach rows older than its replay
window. The periodic full walk and its checkpoint are gone.

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

* filer: re-check an S3-expired entry under its path lock before a listing deletes it

A listing deleted an S3-expired object by the row it had read, so an upload
that replaced it after the page was read was removed. The delete now re-reads
the row under the path lock and removes it only if it is still S3-expired.

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

* filer: remove an expired row a lookup meets in a conflict-checked transaction

A lookup that met an expired row deleted it by path, so a replacement written
through another filer between the read and the delete was lost, even on
stores that refuse conflicting commits; a failed delete was hidden behind not
found. The lookup now re-reads and deletes through deleteIfExpired and returns
the delete error.

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

* worker: keep a failed filer_ttl lookup that ties a done event

When the first event at a timestamp was done and the second one's lookup
failed, the cursor already stood at that timestamp, so the retry subscribed
after it and skipped the failed event. A failed lookup now holds the cursor
below a tie, as a waiting entry does.

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

* worker: hold a filer_ttl event whose entry the filer still serves

A lookup that returned the live entry counted as done, so when the worker's
clock ran ahead of the filer's near the deadline the event was skipped and
the row stayed. An entry the filer still serves with the same deadline now
holds the cursor like one not yet due.

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

* worker: keep a path TTL rule from expiring the filer_ttl cursors

The cursors were written without a TTL, so a filer.conf TTL rule covering
/etc/seaweedfs/filer_ttl gave them the rule's TTL and every rule was listed
again once they expired. When a rule covers them they are now written with a
TTL of their own, which the filer keeps.

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

* worker: list a filer_ttl rule again for a live entry its replay cannot reach

A new rule nested under a longer one started its replay one TTL back, so a
live entry the enclosing rule had stamped with its longer TTL, written before
that, was in neither rule's replay: the nested rule now owns it and the
enclosing rule skips it. The listing of a new rule now records the earliest
deadline of such entries, and the rule is listed again then.

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

* worker: hand a removed filer_ttl rule's replay to the rule enclosing it

When a nested rule was removed, its entries became the enclosing rule's, but
that rule's cursor could already be past their events, so they were never
replayed. The enclosing rule now replays from the earlier of both cursors.

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

* worker: list a filer_ttl rule whose unfinished events the filer no longer keeps

When fs.log.purge removed the event of an entry still waiting for its TTL,
the rule's cursor matched, so the rule was never listed and the replay never
met the entry again. A rule whose cursor is older than the oldest kept
metadata log is now listed, and its cursor moves to that log. The cursor also
records how far a replay read with nothing left waiting, so a quiet rule is
not listed just because old logs were purged.

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

* worker: leave S3 lifecycle expiry to the s3_lifecycle job in filer_ttl

An entry whose TTL an S3 lifecycle rule set carries the S3 expiry flag;
s3_lifecycle evaluates and removes it. filer_ttl no longer looks such
entries up, and their deadline no longer holds a TTL rule's cursor.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:20:03 -08:00
Chris LuandClaude Opus 5.5 a7cc8fb767 filer, docs: 503 in the upload wait flag help; Yandex restart after a token refresh (#13096)
* filer: flag help names the 503 an upload gets after the wait

The filer answers an upload that found no slot within
-inflightUploadDataTimeout with 503 and Retry-After: 1, not 429.

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

* docs: a restart after a Yandex token refresh may need a new token

The client keeps the refresh token Yandex returns in memory only, and
Yandex does not say whether the stored one survives the rotation, so the
doc no longer promises that a restart keeps working.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 15:34:59 -08:00
a9fda6b50f filer clients: authenticate filer gRPC calls with per-call admin tokens (#13039)
* Add per-call filer authentication sources and pooled client wrappers

* Authenticate gateway filer calls with per-call admin tokens

* Authenticate shell admin and synchronization filer calls

* Authenticate workers MQ and remaining filer client paths

* Cache filer client signing keys and sign subscriptions with the shared key

Re-reading security.toml on every filer RPC cost about 125us against 8us for
signing. Keep the keys for up to a second, re-reading at once when a WEED_
override or the configuration directory changes. When the file exists but
cannot be read, keep the last keys read, else the startup keys, as
FilerAdminKeys does, so a process without a key stays tokenless. Metadata
subscriptions prefer the shared key, as filer peers do, because older filers
verify subscription admin tokens only with it.

* Authenticate admin-script, maintenance and filer.conf shell paths

Plugin worker admin scripts and master maintenance scripts build their own
shell options and carried no filer token source; fs.configure and
s3.bucket.quota.check read filer.conf without it.

* filer.cat: report a failed read; isolate key overrides in the admin-script test

filer.cat ignored the error from its filer call and exited successfully,
leaving a truncated -output file. Report the error and exit with failure.
The admin-script token test now clears the WEED_ signing-key overrides,
which take precedence over security.toml.

* security: refuse gRPC keys too short to sign; query engine uses client TLS

Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The
startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key,
and filer client token sources check the keys they read, so a reloaded or
per-endpoint security file with a short key is refused instead of
panicking when the next RPC signs.

The query engine's broker client dialed every master, filer and broker in
plaintext, so the admin token it now sends could cross the network in the
clear. It dials with the grpc.client TLS settings instead, and weed-sql
loads security.toml as weed-db does.

* security: per-endpoint admin tokens ignore WEED_ key overrides

FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and
WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with
-a.security and -b.security signed both clusters' admin tokens with the
one key, handing each cluster a token valid on the other. A per-endpoint
file now supplies its own keys only.

* weed-sql, weed-db: refuse to start on an unreadable security.toml

Both only warned when security.toml was present but could not be read or
parsed. They then dialed without the grpc.client TLS settings while the
filer token source could still sign admin tokens from WEED_ environment
keys, so the tokens could travel in plaintext. They now exit with an
error that does not quote the file; a missing file is still fine.

* pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients

Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the
existing helpers instead of keeping two names for each. Callers without a
token source pass nil.

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

* util: return the read error from ReadConfiguration

Fold ReadConfigurationWithError into ReadConfiguration. The error is
returned and not logged, since parser errors can quote values; the
existing reload callers already warn when no file was read.

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

* security: keep the test-only filerAdminToken helper in the test

It had no production caller. The test helper now resolves keys through
filerClientKeysFrom, as the token sources do.

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

* util: read security.toml once in LoadSecurityConfigurationOrError

It validated the file, then merged it with a second read whose failure
was ignored and whose parser error was logged. It now merges with one
read and logs nothing from the parser. Viper's search also treats a
directory the process cannot search as holding no file; a candidate
that cannot be checked for lack of permission is now refused too.

* security: verify admin subscription tokens with the gRPC clock leeway

CheckGrpcMetadataSubscription checked admin tokens strictly, while unary
filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second
client admin tokens, a subscriber whose clock trailed the filer's by more
than ten seconds was refused with a matching key. It now takes the leeway,
and the filer passes its configured one. The leeway check moves from the
server package to security.IsFilerAdminTokenWithLeeway so both use it.

* util: start without security.toml only when every candidate is confirmed absent

A candidate whose check fails for any reason other than not existing,
such as a symlink loop, is refused like one the process cannot search.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:59 -08:00
c812a37c83 feat(grpc): serve grpc.health.v1 on every server, add health-check-only client certificates (#13049)
* feat(grpc): serve grpc.health.v1 on every server, add health-check-only client certificates

Every gRPC server built by pb.NewGrpcServer now answers the standard
grpc.health.v1.Health service, so blackbox_exporter's grpc prober,
grpc_health_probe and Kubernetes grpc probes can check SeaweedFS ports.
Check("") reports the server; Check(<service>) reports whether that
service is registered on the port.

grpc.health_check_commonNames lists client certificate common names that
pass the mTLS handshake on every component but may call only the health
service; any other RPC gets PermissionDenied. A monitoring probe can then
check the port and its certificate without a credential that opens the
whole gRPC API.

Fixes #5012

* seaweed-volume: serve grpc.health.v1 on the gRPC port

Mirrors pb.NewGrpcServer registering the health service on every Go
server: the whole server, the volume service and the health service
answer SERVING, other names NotFound.

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

* seaweed-volume: confine grpc.health_check_commonNames to the health service

Mirrors the Go healthCheckOnlyTap: a client certificate whose common name
is on [grpc] health_check_commonNames passes the handshake even when
allowed_commonNames is set, and any RPC outside grpc.health.v1.Health is
refused with PermissionDenied. WEED_GRPC_HEALTH_CHECK_COMMONNAMES
overrides the key like the other WEED_GRPC_ settings.

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

* seaweed-volume: end health watches when the gRPC server shuts down

Graceful shutdown waits for open streams, so a client holding a health
Watch kept the volume server from reaching store close. Clearing the
reported statuses ends every Watch stream once the shutdown signal fires.

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

* pb: end health watches before gRPC graceful stop

GracefulStop waits on open streams, and Watch held its stream until the
client left, so a connected probe kept volume and admin worker shutdown
from finishing and made filer and S3 wait out their drain timeout.
StopHealthWatches ends those streams; every GracefulStop path calls it
first.

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

* scaffold: point mTLS health probes at an exec probe

The built-in Kubernetes grpc probe sends no client certificate, so it
cannot pass an mTLS port; grpc_health_probe run as an exec probe can.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:50:34 -08:00
7bbb65fa80 master: /col/delete requires an explicit collection name (#13055)
* master: /col/delete requires an explicit collection name

A /col/delete request without a collection parameter, or with an empty
one, read as the empty-named default collection and deleted it. Return
400 instead, and accept collection=_default (the keyword weed shell
uses) to delete the default collection deliberately.

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

* master: keep a collection literally named _default addressable by /col/delete

collection=_default now names the empty-named collection. A collection
created with that literal name would have been unreachable, and a request
meant for it would have deleted the default collection instead. Resolve
the keyword to the literal collection when one exists, and refuse the
request when both exist.

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

* master: /col/delete accepts only the DELETE method

A GET is expected to be safe, yet a bare GET or a link prefetch deleted
the named collection. Any other method now gets 405 with an Allow
header, and the docs, benchmark help and test helpers send DELETE.

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

* master: /col/delete accepts _default_ for the default collection

When a collection literally named _default exists next to the default
collection, collection=_default is refused, which left the default
collection with no way to be named. Accept the _default_ spelling that
weed shell collection.delete already takes; it always means the
default collection.

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

* master: /col/delete keeps a literal _default_ collection addressable

_default_ now resolves like _default: to the literal collection when one
exists, to the default collection otherwise, and refuses the request when
both exist.

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

* REST_API: /col/delete when both keyword names are literal collections

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-27 14:56:18 -08:00
397a156104 security: a fips.mode setting that Go checks against GODEBUG and the Rust binaries apply to TLS (#13029)
* util: refuse to start when fips.mode in security.toml disagrees with GODEBUG

security.toml gains [fips] mode = "off" | "on" | "strict", also settable
as WEED_FIPS_MODE: one setting that states the FIPS 140-3 mode of every
process in a deployment, so the Rust binaries, which do not run on the Go
runtime, can follow it. Go processes keep taking their behaviour from
GODEBUG=fips140 and now check it against the setting:
LoadSecurityConfiguration and `weed worker` exit when "off" runs without
fips140=off, "on" without fips140=on, or "strict" without fips140=only,
naming the setting and the GODEBUG value it needs. An unknown value is
refused; unset or empty changes nothing.

Refs #12839

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

* rust: fips.mode with FIPS-mode TLS in weed-volume, weed-worker and weed-vector

seaweed-common gains a fips module: FipsMode resolved from fips.mode in
the security.toml a binary uses, with WEED_FIPS_MODE over it. Each binary
resolves it once at startup, logs it and installs the matching rustls
provider as the process default, refusing to start on an unknown value or
when another provider was installed first.

Under "on" and "strict" the provider is aws-lc-rs filtered to the lists
Go's crypto/tls applies in FIPS mode: TLS 1.3 AES-GCM suites and TLS 1.2
ECDHE AES-GCM suites (no ChaCha20-Poly1305), X25519MLKEM768,
SecP256r1MLKEM768, P-256 and P-384 (no plain X25519), Go's ten signature
schemes (no ML-DSA). Configurations SeaweedFS builds require the Extended
Master Secret in that mode, and the volume server refuses a non-FIPS suite
in tls.cipher_suites instead of falling back. sw-client installs the same
provider instead of ring. Unset or "off" keeps aws-lc-rs's default
provider unchanged.

This is behavioural parity only: the provider still runs on the
non-validated aws-lc-rs build.

Refs #12839

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

* util: refuse a fips.mode that is not a string

viper's GetString turns an array or a table into "", so mode = ["strict"]
under [fips] skipped the GODEBUG check while the Rust binaries refused the
same file. RequireFipsMode now reads the raw value (ViperProxy.Get, under
its lock) and exits when it is not a string, naming its source; an absent
or empty value still means unset, and WEED_FIPS_MODE still wins.

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

* rust: read fips.mode with the parser that reads the JWT keys

seaweed_common::fips::resolve parsed security.toml with the toml crate,
while the volume server reads the rest of the file with its own lenient
loader. A file with [fips] mode = "on" beside an unquoted value the loader
accepts resolved to off and logged "fips.mode unset", although the JWT
keys from the same file were applied. Each binary now reads fips.mode
with the loader it uses for everything else and hands the value to
resolve: the volume server through its line parser, the worker and vector
engine through their parsed Security table, which already refuses a file
that is not TOML. A security.toml the volume server finds but cannot read
stops startup. A missing setting is still off, and WEED_FIPS_MODE still
wins. seaweed-common no longer depends on toml.

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

* sw-client: offer only FIPS signature schemes with insecure_skip_verify

With https.client.insecure_skip_verify, reqwest installs its own verifier,
which advertises a fixed scheme list including SHA-1 and Ed448 whatever
the process provider allows. In FIPS mode the volume transport now builds
its rustls configuration itself on the process provider: the server
certificate and host name are not checked, as the setting asks, but
handshake signatures are verified with the provider's algorithms, only its
schemes are offered, and TLS 1.2 requires the Extended Master Secret.
Outside FIPS mode the reqwest path is unchanged.

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

* seaweed-common: sign only with Go 1.27's FIPS schemes, allow ML-DSA

The FIPS provider kept aws-lc-rs's key provider, so a FIPS-mode listener
signed handshakes with whatever scheme its key and the peer agreed on,
outside the list the provider verifies with. Keys now load through a
provider that limits each key to the FIPS signature schemes and refuses a
key that can sign none of them, such as Ed448; the volume server and the
worker's gRPC TLS name the certificate and key files in that error.

The lists follow Go 1.27.4, which go.mod now requires: its
defaults_fips140.go allows ML-DSA-44, -65 and -87 as signature schemes and
ML-DSA certificate keys (for Go's native module only), so they are allowed
here as well. Go also allows MLKEM1024 but does not enable it by default,
so it stays out of the key exchange list as in Go's defaults. "off" keeps
the default key provider.

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

* mount: skip the truncate manifest test on freebsd like its fake filer

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-27 12:47:44 -08:00
e743f99bb5 util: keep a request's context while its handler works quietly past the idle timeout (#13040)
* util: keep a request's context while its handler works quietly past the idle timeout

A request that the server works on for longer than the listener's idle
timeout, without reading or writing, lets that timeout end net/http's
background read: the read the server keeps waiting while a handler runs,
to see a client hang up. net/http takes the failed read for the client's
connection failing and cancels the connection's context, so the request in
progress, and every later request on the kept-alive connection, run with a
canceled context. #10212 covered a long write-only response, whose writes
now extend the read deadline; an answer that has not started yet has
nothing to extend it.

On the S3 gateway (-idleTimeout 120 s) such requests are the ones that
answer only when their work is done, e.g. a large CopyObject into a
versioned bucket, which the copy keep-alive of #12862 does not cover. After
one, the next requests on that connection fail within a millisecond: a
ListObjectsV2 answers 500, a GetObject and a PutObject 499
ClientDisconnected while the client is still connected. The filer's HTTP
listener has a 10 s idle timeout by default.

PauseIdleTimeoutWhileHandling, which newHttpServer now installs next to the
ConnContext hook it already sets (S3, filer, IAM and master HTTP), takes
reading out of the activity timeout from the moment a request's body has
been read to its end (at once when it has none) until its handler returns:
the client is waiting for the answer, so a connection that carries nothing
means the server is at work. Reading a body, writing an answer and waiting
for the next request stay under the timeout, and a client that closes its
connection still cancels the context. Over HTTP/2 the frame reader keeps no
deadline while such a handler runs and gets it back when the last one
returns.

Tests: weed/util/net_timeout_test.go (a quiet handler over HTTP/1.1, TLS
and HTTP/2, and the next request on the same connection; the same after a
1 MiB body; a stalled body, an idle connection, an idle HTTP/2 connection
and a client hang-up still end as before; concurrent requests; a waiting
read held by the pause and released at its end; the context loss without
the wrapper) and weed/command/server_http_test.go (newHttpServer).

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

* webdav: serve through newHttpServer so quiet handlers keep their context

weed webdav serves a util.Listener with an idle timeout (10 s by default)
but built a bare http.Server, so it had neither ConnContext nor the idle
timeout pause. A COPY or MOVE of a large file answers only once it is done,
and like the S3 and filer handlers it then lost its context, and so did
every later request on the connection.

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

* util: pause the idle timeout for HTTP/1.x requests only

HTTP/2 has no background read to protect: when its connection carries
nothing for the timeout, the frame reader's deadline closes the connection,
and no later request runs on it. That deadline is also what ends a stream
whose client stopped reading, since the answer waits for flow-control
credit, not on the socket, where the write deadline would end it. With the
pause on HTTP/2 requests, a download whose client stopped reading held its
handler and connection until the client acted, and a stream that declared
content-length 0 but never ended could hold its handler the same way.

Pause only HTTP/1.x requests; HTTP/2 keeps the timeout it had.

Tests: TestStalledDownloadStillTimesOut over HTTP/1.1, TLS and HTTP/2 (the
HTTP/2 case was still waiting after 8 s with the pause on HTTP/2) and
TestOnlyHTTP1RequestsArePaused; the HTTP/2 quiet-handler cases are gone,
with them the HTTP/2 subtest that flaked under -race.
TestPauseUnderConcurrentRequests gets a 1 s idle timeout, so that a request
waiting for its turn on a slow run does not find its connection closed.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-26 21:56:12 -08:00
e9a5d733b1 weed: report host THP policy; build: declare Go 1.27.4 to match the releases (#13025)
* weed: report the host transparent huge page policy at startup

Go maps the heap with MADV_HUGEPAGE, so the host THP policy applies to a
SeaweedFS process whether or not the operator asked for it, and the advice in
the Go GC guide depends on the heap size. Operators had no way to see which
mode a node actually runs in.

Log enabled/defrag/khugepaged.max_ptes_none once at startup from the
long-running commands, and print the Go toolchain in `weed version` so a
support bundle identifies the runtime that produced the binary. Nothing
changes the policy: THP is host-wide, and GODEBUG=disablethp=1 remains the
only per-process control.

Refs #5437

* build: declare Go 1.27.4, the toolchain the releases already use

The 4.55 release binaries report go1.27.4 (`go version -m` on the published
tarball), while go.mod still said 1.26.6, the Dockerfiles pinned golang:1.26,
and the release workflows left the Go version to the action default of "the
latest stable at build time". A source build, a container and a downloaded
tarball therefore ran different toolchains from the same tag, and the next
release could silently pick up another one.

Set the go directive to 1.27.4 in the root module and in the four modules that
build in CI, bump the 16 Dockerfiles, and pin goversion: 1.27.4 in the 16
release and dev action steps.

`go mod tidy` now emits the two require blocks Go 1.27 expects; no dependency
version changed. Go 1.27's gofmt realigns 8 files.

* weed mini: report the THP policy after quieting stderr

The startup line ran from the dispatch point before runMini applied
quietMiniLogs, so every weed mini start on Linux printed it to stderr,
which mini keeps for the welcome banner, warnings and errors. Log it
from runMini after quietMiniLogs so it lands in the log file only.

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

* util: report whether the Go heap can use huge pages

The runtime advises only GC metadata with MADV_HUGEPAGE and leaves the
heap arenas to the host default, so under enabled=madvise the heap stays
on small pages. The log still printed go_heap_disabled=false there, which
reads as "the heap uses THP". Report go_heap_thp, true only under
enabled=always without GODEBUG=disablethp, and drop the struct comment
that said the heap is mapped with MADV_HUGEPAGE.

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

* util: count an inherited PR_SET_THP_DISABLE in go_heap_thp

A launcher can disable THP for the process with prctl, and children
inherit it, so enabled=always alone does not mean the heap gets huge
pages.

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

* util: read GODEBUG disablethp the way the runtime does

The runtime applies GODEBUG left to right, so with
disablethp=1,disablethp=0 the heap keeps THP, while the helper stopped at
the first disablethp=1. The helper also missed other nonzero values such
as disablethp=2, which the runtime treats as disabled, and trimmed spaces
around keys, which the runtime keeps. Take the last disablethp with an
integer value, treat any nonzero value as disabled, and match keys
exactly. The parser now takes the GODEBUG string, so it is tested without
changing the environment.

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

* util: honor per-size THP policies in go_heap_thp

Since Linux 6.8 each anonymous huge page size has its own policy in
hugepages-<size>kB/enabled, and only "inherit" follows the top-level
knob. A 64kB size set to "always" gives the unadvised heap huge pages
under a top-level "madvise" or "never", and a 2048kB size set to "never"
takes them away under "always", but the log judged only the top-level
value. Read the per-size policies and report go_heap_thp=true when any
size reaches the heap. Under a top-level "never", the "disabled by the
host" line is now printed only when no size reaches the heap.

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

* util: report go_heap_thp=unknown when the process setting is unreadable

If PR_GET_THP_DISABLE fails, for example because a seccomp profile
rejects it, the process THP setting is not known, but the log treated it
as allowed and could print go_heap_thp=true. Print go_heap_thp=unknown
in that case. It stays false when the host or GODEBUG already rules out
heap huge pages.

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

* util: report go_heap_thp=unknown when a per-size THP policy is unreadable

An unreadable hugepages-<size>kB/enabled was skipped, so the log could
say the host disabled THP while that size allowed it. Keep it as an
empty mode and report unknown unless a readable size already allows
huge pages.

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

* ci: take the Go version from go.mod in tests and releases

posix-compliance pinned GO_VERSION 1.26 and built go 1.27.4 modules only
through the GOTOOLCHAIN auto-switch; nine workflows used go-version ^1.26 and
the kafka jobs ran in golang:1.26-alpine. Read the version from go.mod with
go-version-file, as the other setup-go steps already do, moving checkout ahead
of setup-go where it came after so the file exists. The posix report takes the
version from the setup-go output.

The release and dev builds pinned goversion 1.27.4 in 16 places. The pinned
go-release-action reads the go directive when goversion is go.mod, so the
binaries now follow go.mod without a second copy of the version.

* weed: report the THP policy from every long-running command

mount, worker, iam, master.follower, the filer sync/backup/remote/replicate
daemons and the mq agent and kafka gateway keep serving after startup like
the commands already listed; mount is likely where heap size matters most.

fuse is not listed: its first process starts a child with the same arguments
and waits, so logging at dispatch would print the line twice. It logs in
runFuse just before handing over to runMount, which only the child reaches.

---------

Co-authored-by: Konstantin Lebedev <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:36:36 -08:00
77a6787335 Bound upload memory: admission by size, gateway holder writes, 503/SlowDown back-pressure, body deadline (#13021)
* util: one admission rule for upload limits

* operation: mark gateway fan-out holder writes as client traffic

* volume: bound upload admission, limit gateway holder writes, 503 on timeout

* volume: charge unknown-length uploads half the budget, document client wait cap

* s3, filer: admit uploads by inFlight+size and charge unknown lengths a chunk

* s3: answer a volume overload as SlowDown with Retry-After

* operation: cut an upload whose body crawls below the minimum rate on any host

* operation: make the slow-commit deadline test honour the request context

* s3: stop chunk uploads when the client goes away

* operation: treat a body deadline cut as back-pressure, not a same-holder retry

A body that crawls past the body deadline returns from retriedUploadData at
once, like an overload, and counts toward the single reassign the chunk loop
and the filer retry gate give back-pressure. A watchdog cut keeps its retry on
a fresh conn. Both still match ErrUploadStalled and stay reassignable.

* operation: apply the body deadline only to uploads that opt in

UploadOption.BodyDeadline and ChunkedUploadOption.BodyDeadline turn the
body deadline on; S3 chunk uploads (relay and fan-out) and the filer's chunk
loop set it. Mount, filer.sync, filer.copy and UploadWithRetry keep the stall
watchdog only, as before the deadline existed.

* s3, operation: check a chunk cancelled with its client is deleted from every holder

A volume commits on a context that ignores the cancel, so a chunk whose
caller went away after sending the body may still land. The chunk loop
already deletes the fid from every holder after a failed attempt; pin that
for the relay and fan-out paths and for an S3 PUT whose client goes away.

* s3: count a request's declared bytes in the circuit breaker byte limits

The per-bucket and global byte counters go back to the declared length (an
unknown length counts one chunk), so a bucket bytes limit still rejects a
single PUT larger than it. Only the upload budget uses the capped gateway
charge.

* s3: answer copy chunk overloads as SlowDown, tidy the client-gone checks

CopyObject and UploadPartCopy map a volume overload or an exhausted stall to
SlowDown, as PutObject does. The client-gone log check matches the mapper's
context.Canceled test, the truncated-body case drops a check the first case
already makes, and the Retry-After test reads the headers actually sent.

* filer, volume: clamp the filer charge chunk, set the upload gauge under the lock

A filer with -maxMB 0 charges its default chunk size instead of nothing. The
volume server sets its in-flight upload gauge inside the critical section.
The upload limit tests wait until the waiter is parked before releasing,
check handleUploadRequest gives its charge back, and use CI-safe bounds.

* volume: cap the Rust server's client upload-slot wait at 5s

Same cap as the Go volume server's volumeClientUploadWaitCap, so a gateway's
body deadline never fires before the 503.

* operation: reflow the body deadline comment

* volume(rs): count a gateway's src=client holder write against the upload limit

Mirrors operation.IsReplicaForward: only a primary-to-replica forward
skips the upload budget; a gateway's ?type=replicate&src=client fan-out
waits like any client write.

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

* volume(rs): admit uploads by inFlight+size, reserved atomically

Mirrors the Go volume server's waitForUploadSlot: an upload is admitted
by util.UploadAdmits (idle server, or inFlight + size within the limit)
and reserves its bytes in the same step, so concurrent waiters cannot
all pass one check. Primary-to-replica forwards and unlimited servers
are counted but never refused. UploadLimitCond counts once per waiting
upload, and the wake-up is armed before each check so a release in
between is not missed.

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

* volume(rs): charge an unknown-length upload against the upload limit

Mirrors the Go volume server's uploadCharge: a chunked upload without
Content-Length reserves one file's worth of budget, at most half the
limit and at least 1 byte, instead of 0.

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

* volume(rs): a zero -inflightUploadDataTimeout waits the 5s client cap

The Go volume server now reads 0 as the 5s cap (its flag help says so);
the Rust server used a 2s wait.

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

* volume(rs): close a rejected large or unknown-length HTTP/1 upload

Mirrors the Go volume server's uploadRejectCloseThreshold: the 503 for
a body over 256 KiB, or one without a length, carries Connection: close
instead of keeping the connection for a body nobody reads.

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

* volume(rs): drop src from a primary's replica forward

A client upload carrying src=client kept it on the forward, so replicas
treated the forward as gateway fan-out and could refuse it after the
primary had already appended. Go's ReplicatedWrite builds a fresh query.

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

* volume(rs): keep the upload admission CAS buildable on rust 1.91.1

Atomic try_update is stable only since 1.95.

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

* volume(rs): refuse an upload the in-flight counter cannot hold

A replica forward added its charge with fetch_add, so a Content-Length
near i64::MAX wrapped the shared counter negative and let later client
uploads past admission. The forward now reserves with a checked add and
answers 503 when the size does not fit; the client CAS adds only after
admission passes. With no upload limit the counter only feeds the gauge,
so it keeps wrapping arithmetic.

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

* volume: refuse an upload the in-flight counter cannot hold

A replica forward added its charge unchecked, so a Content-Length near
math.MaxInt64 wrapped inFlightUploadDataSize negative and let later
client uploads past admission. Under the lock the reservation now
checks that the counter can hold the charge and answers 503 otherwise,
matching the Rust volume server.

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

* volume: keep the request body on a rejected upload

Replacing r.Body with http.NoBody hid the server's early close of the
unread body from net/http before Go 1.27, so it skipped the FIN-then-wait
close and reset the connection under a client still sending. Go 1.26.6,
the version go.mod declares, then failed
TestUploadLimit503ReachesGoClientForLargeBody with a write error instead of
the 503.

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

* util: compare upload admission without forming inFlight+size

* operation: reassign a chunk after a 429 as after a 503

* s3: do not count a chunk assignment the client cancelled as a filer failure

* filer: charge an upload by its request chunk size, and an inline upload by its whole body

* s3: hold an aws-chunked body to its X-Amz-Decoded-Content-Length

* volume: answer a rejected small-body upload without waiting for its body

* s3: fill the upload budget before testing that a release wakes every waiter

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:34:47 -08:00
Chris LuandClaude Opus 5.5 a00dbff13b sftp: apply the bucket's default Object Lock retention to uploads (#13017)
* s3_objectlock: read a bucket's default retention from its entry

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

* sftp: give uploads into an Object Lock bucket its default retention

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

* sftp: match uploads against the cleaned buckets folder

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:25:48 -08:00
dcce121d95 weed fix.recover: recover needles past damaged .dat regions (#13002)
* feat: weed fix -verify to resync past damaged regions in .dat

Plain `weed fix` walks .dat by trusting each needle header, so a damaged
region in the middle loses or misindexes everything after it, and a torn
or garbage tail ends up in the index and keeps the volume read-only.

-verify reads every needle, checks structure and CRC32, and on a failure
searches forward at needle alignment for the next verifiable needle. Each
skipped region is reported as zero-fill / garbage / garbage+zeros with its
length, zero windows and the fid of the needle that was hit. The index is
rebuilt from verified needles only (old one kept as .idx.bak); -truncateTail
cuts trailing garbage so the load-time integrity check passes, -dryRun only
reports. Works with the 5BytesOffset build.

* feat: add weed fix.verify, a read-only check of .dat files

Runs the same needle/CRC verification and resync scan as `weed fix -verify`
but never writes: no .idx rebuild, no truncation. Takes folders and/or .dat
files, filters with -collection / -volumeId, prints the damaged regions
(optionally to -report) and exits 0 when clean, 3 when damage was found and
1 when a file could not be verified. The scan options are shared with
`weed fix -verify`.

* feat: weed fix -compact, verify and compact a damaged volume in one pass

-compact implies -verify. While the .dat is scanned, every verified needle
gets an index entry, and from the first damaged region in the middle of the
file the needle bytes are streamed into a new .cpd as well (the intact prefix
before it is copied as one block). The result is a .dat without the damaged
regions and an append-ordered .idx that matches it exactly, so a full volume
scrub no longer complains about the .dat size. The compaction revision is
bumped like a vacuum does.

A volume without damage is left untouched, and damage only at the tail is just
cut off in place, so neither costs a .dat copy. The old .idx is kept as
.idx.bak and the old .dat as .dat.bak (-deleteOriginal removes it). The free
space needed for the new .dat is checked before anything is written, a failing
swap is rolled back, and progress is printed every 30s.

* refactor: reuse backend, super block and throttler code in weed fix -compact

- create the .cpd with backend.CreateVolumeFile and preallocate the bound of
  the new .dat; the result is truncated to its real length at the end
- read the super block with super_block.ReadSuperBlock (also in the verifier)
  and write the bumped compaction revision with SuperBlock.Bytes()
- throttle the .dat writes with util.WriteThrottler (-compactionMBps)
- fsync the directory before and after swapping the new files in

ReadSuperBlock cannot read a super block with extra data, so such volumes are
rejected with its error instead of being handled by a hand-written parser.

* refactor: drop helpers that duplicate existing code in weed fix -compact / fix.verify

- util.FsyncDir instead of a local fsyncDir
- io.NewOffsetWriter instead of a hand-written WriterAt adapter; the throttle
  now sits in one small writer wrapper used for both the prefix copy (via
  io.CopyBuffer) and the streamed needles, replacing the manual copy loop
- needle.NewVolumeId instead of strconv for volume ids parsed from file names

* fix: resync in weed fix -verify must not accept payload-less look-alikes

After damage, a few bytes of a needle's tail followed by the next record's
header could parse as a payload-less needle and be confirmed only because the
file ended right after it, so a made-up key got into the index and swallowed
the real delete record behind it.

A payload-less candidate is now accepted without a verifiable successor only
if it is a size-0 tombstone ending exactly at the end of the file (or, with a
set timestamp, leaving less than a header); a set but implausible v3
timestamp rejects it. Anything else needs the next needle to verify.

* test: recovery integration tests for damaged .dat heads (#5674, #12914)

- zero-filled head (aligned and cut next record): all survivors indexed,
  region reported as zero-fill, trailing tombstone kept
- plain weed fix stops at the first bad header (#12914 item 1) while
  -verify recovers the needles behind it
- a needle rewritten after a damaged region is indexed at its newest copy
- a zeroed superblock fails with an explicit unsupported-version error and
  fix.verify counts it as not verifiable (exit 1)
- v1/v2 needle layouts verify cleanly

* fix: reject a super block extra in fix -verify

A super block extra describes an erasure-coded layout; the .dat behind it was
re-striped into .ecXX shards and is not a plain needle file. Scanning it as
one silently produced damage reports instead of telling the operator the file
is out of scope. Return an explicit error instead.

* fix: guard fix -verify/-compact against pending compaction commits and -dir.idx

- refuse to start while a .cpc marker exists: an interrupted vacuum commit is
  pending and the volume server must reconcile it first (roll forward/back);
  writing a rebuilt .idx or new .cpd/.cpx over that decision would race it
- clear a stale .cpc after a completed swap so it can never be rolled forward
  later (defensive; the start guard already refuses this state)
- spell out in the help and print after a rebuild that the index is written
  next to the .dat: with a separate -dir.idx directory the .idx must be moved
  there and any stale .ldb dropped
- tests: refusal leaves the marker and writes no .idx; a completed swap clears
  a marker that slipped past the guard

* refactor: narrow this change to weed fix -verify

Drop weed fix.verify and weed fix -compact from this change; they follow in their own pull requests. -report, -windowMB and -zeroWindow go with them: the scan uses fixed windows and prints its report to stdout.

* fix: weed fix -verify: address review findings

- -maxNeedleSizeMB limits only guesses made while resynchronising; a record
  reached at a known boundary may be as large as the file allows
- a v2/v3 record whose parsed fields do not add up to its size, or a live
  record without data, is damage: a zero fill over the data length used to
  pass as an empty file because the CRC is only checked when there is data
- a stamped v3 delete record found after damage stands on its own when its
  time is believable, not older than the last verified record and followed
  by zero padding, so a delete before a damaged tail is not lost
- a read error while searching for the next needle fails the run instead of
  ending the scan and treating the rest as a garbage tail
- keys whose newest record is damaged while an older copy is indexed are
  reported as stale-version warnings
- the rebuilt index is staged as .idx.tmp and swapped in when complete; a
  stale .ldb next to it is removed so the volume server rebuilds it
- -ignoreError reports a volume that cannot be verified and goes on
- -truncateTail does not cut a tail it could not read and removes a partial
  tail backup
- volume ids are parsed as uint32
- the test fixture stamps every record the way the volume server does

* fix: weed fix -verify: prove deletes found after damage, swap the index safely

- a delete record found while resynchronising must prove itself: a v3 one
  needs a believable time not older than the last verified record and zero
  padding (every v3 writer stamps deletes); a v1/v2 one needs the following
  records to reach data that passes its CRC, or the exact end of the file.
  Stray bytes in a zero-filled region used to pass as deletes of live keys.
- the rebuilt index is fsynced before the swap, the previous one is kept as
  a hard link, and the new one replaces it in one rename, so a live .idx
  exists at every moment
- .sdx and .rdb caches are removed with the .ldb
- -verify exits non-zero when it found damage, like plain fix and -verifyCrc
- with -ignoreError a file name whose volume id does not fit uint32 is
  reported and the batch goes on
- the help and the printed hint say that a volume server prefers an .idx
  next to the .dat over the one in -dir.idx

* fix: reject weed fix flag combinations -verify cannot honour

-verify -remoteFile skipped an explicit .dat and reported success, -dryRun
and -truncateTail were silently ignored without -verify, and -dryRun -ecx
still rebuilt EC indexes. Check the combinations before any file is touched.

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

* fix: apply -volumeId before rejecting an out-of-range volume file name

With -volumeId set, an unrelated file such as 4294967296.dat aborted the
run before the filter could skip it.

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

* fix: check the data length before reading a record body in fix -verify

A damaged size field at a known record boundary made the scan allocate and
read a body of that size before rejecting it. Check that the data length
after the header fits the record first, as the resync probe already does.

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

* fix: accept a v1/v2 delete chain that reaches the end of the file on its last probe

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

* fix: keep an implausible needle timestamp out of the fix -verify resync baseline

The data CRC does not cover the v3 timestamp, so a corrupted one passed and
then rejected every genuine delete record found after later damage. Report
it as a warning instead of using it as the lower bound.

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

* fix: stop fix -verify on a read error at a known record boundary

An EIO while reading a record was treated like damaged bytes: the scan
resynchronised past the unread record and the rebuilt index dropped it.

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

* fix: sync the fix -verify tail backup before truncating the .dat

A crash right after the truncate could persist it before the backup's data
or directory entry, losing the cut bytes from both files.

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

* fix: let fix -verify -truncateTail retry when a tail backup already exists

After a backup succeeded and the truncate failed, the next run hit the
existing backup and could not get past O_EXCL. Keep the first backup and
save the tail under a new name, as the index backup does.

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

* fix: drop stale index caches before fix -verify swaps in the new index

Removing them after the rename left a window where a crash paired the new
.idx with the old .ldb, whose newer LOG skips the replay.

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

* test: pin fix -verify fixtures to needle version 3

-verify reads v1 to v3 records, so its fixtures should not follow the
build's current needle version.

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

* fix: refuse fix -verify on remote-tiered volumes

A remote-tiered volume is read from its remote .dat through the existing
.idx, so rebuilding that index from a local .dat would point it at the
wrong bytes.

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

* fix: pick a free backup name when fix -verify retries within one second

backupName fell back to path.bak.<unix time> without checking it, so a
second retry in the same second reused that name and the exclusive
create (or the .idx hard link) failed. Add a .<n> suffix until the name
is free.

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

* fix: refuse fix -verify when the volume info cannot be read

An unreadable or unparsable .vif may name a remote tier, so treat it like one
and keep the existing index.

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

* refactor: pass weed fix -verify options explicitly

* feat: move weed fix -verify into a weed fix.recover command

* docs: weed fix.recover help, point weed fix at it

* fix: keep the volume file helpers below runFix

Leaves the region between VisitNeedle and runFix as on master.

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

* test: build fix.recover fixtures at needle version 3

fix.recover reads needle versions 1 to 3, so its tests must not follow
GetCurrentVersion; writeFixTestVolume now takes the version.

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

---------

Co-authored-by: whitefox <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:24:05 -08:00
f079b68f2b filer: grpc_require_token with authenticated filer-to-filer peer calls (#13011)
* filer: require bearer tokens for configured gRPC calls

* filer: authenticate owned peer RPCs with per-call admin tokens

* filer: retain scoped forwarding refusals with required authentication

* filer: preserve tokenless HTTP forwarding outside require mode

* filer: honor clock tolerance for gRPC admin fallback

* filer: preserve caller token on lock owner forwards

* filer: forward caller auth on target ping

* filer: authenticate startup peer digest checks

* filer: verify required subscription bearers independently of mTLS

* filer: assert exact caller bearer on forwarded ping

* filer: sign peer tokens with the gRPC verification key

peerContext signed filer-owned RPCs with jwt.filer_signing.key only. With
grpc_key as the only key and require-mode on, peer calls went out tokenless
and were refused. With both keys set, peers that verify with grpc_key and
lack the shared-key admin fallback refused the shared-key token even with
require-mode off. Sign with the key filesystem gRPC verifies, and keep the
shared key for metadata subscriptions, whose verifier accepts admin tokens
signed only with it.

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

* filer: keep a subscription token's scope over mTLS in require-mode

Require-mode admitted a dedicated subscription bearer without the mTLS
shortcut, but the handler re-checked it with the certificate, which
granted the full stream past the token's prefixes and expiry.

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

* filer: delete uploaded chunks when the write owner refuses authentication

A forwarded HTTP append or offset write that the owner refused as
Unauthenticated kept its new chunks as if the outcome were unknown,
orphaning them.

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

* filer: hand the admitted subscription scope to the handler

The handler re-verified a dedicated subscription token after reading the
request. If the token expired in between, an mTLS peer fell back to the
certificate and got an unrestricted stream. The interceptor now passes
the scope it admitted, and the handler refuses it once expired.

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

* filer: accept grpc_key admin tokens on metadata subscriptions

A filer with only grpc_key signs peer subscriptions with it, but the
subscription verifier checked admin tokens against the shared key only,
so with a subscribe key set the aggregator's peer streams were refused.
An unscoped grpc_key token already has full filer gRPC access.

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

* filer: delete the generated manifest when the write owner refuses authentication

A forwarded HTTP append that crossed the manifest threshold left the
manifest blob it had uploaded orphaned when the owner refused the call
as Unauthenticated. The blob alone is deleted, since the manifest also
lists committed chunks.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:18:28 -08:00
fb0a734dc4 feat(remote_storage): add Yandex Disk as a remote storage backend (#13012)
* feat(remote_storage): add a Yandex Disk backend

Yandex Disk joins s3/gcs/azure as a remote storage type, so it can back
remote mounts and sink replication (filer.remote.sync, filer.remote.gateway)
without a separate sink.

The Disk API has no buckets and no place for a file's mtime: a top-level
folder under yandex_root plays the bucket, and the entry's modification time
and content encoding travel as custom resource properties (seaweedfs_modified,
seaweedfs_content_encoding; rclone_modified is read too). The client also
handles the API's asynchronous operations (202 + operation polling), the
short-lived, single-use download links (a fresh link per read and per retry),
single-PUT uploads, mkdir -p of an S3-style key's parents, server-side copy
for a remote-only rename, and a ranged read that refuses a short body.

A caller-supplied endpoint goes through the guarded client like the s3 and
azure endpoints.

* feat(shell): configure and issue Yandex Disk tokens

remote.configure gains the yandex flags (token, client_id, client_secret,
root, trash, app_folder, endpoint). A refreshable token is issued in two
steps without a browser on the server: -yandex.oauth_url prints the
authorization url and keeps the app credentials, -yandex.code exchanges the
copied code for a token and stores it. The token and the client secret are
masked in the configuration listing.

docs/remote-storage-yandex.md walks through the OAuth app, both token flows,
the mount and replication commands, and the platform's limits.

* fix(remote_storage): handle missing Yandex folders on stat, copy and upload

A missing object is confirmed against the bucket folder rather than its
immediate parent, as the gcs client does: a key whose subfolder does not
exist yet (a rename destination) is a missing object, not a vanished mount,
and the sync only proceeds on ErrRemoteObjectNotFound.

CopyFile creates the destination's parent folders, so a remote-only rename
into a folder the remote does not have yet succeeds. The Disk API answers a
missing parent with 409 DiskPathDoesntExistsError; upload and copy treat it
like a 404, and the fake answers the way the API does.

An operation poll refreshes the token once on 401 and then fails, instead of
polling without a pause until the operation deadline.

* fix(remote_storage): retry a locked Yandex resource

A folder that is still being deleted asynchronously answers a write with
423 DiskResourceLockedError for a moment. The client now retries it with the
same backoff as 429/5xx/509, and the error stays transient for the sync's
upload retry when the client's retries run out.

* fix(remote_storage): harden the Yandex backend after review

Traverse reports objects only, like the s3, gcs and azure clients: its
callers (remote.cache, remote.copy.local) read the stamp of every entry, and
a folder came with none.

Deletes no longer reach what they were not meant for. A Disk API delete is
recursive, so DeleteFile keeps a folder that took a file's place on the
remote, and DeleteBucket removes an empty bucket folder only, the rule S3 and
GCS apply to a bucket.

CopyFile keeps the destination until its replacement exists: it copies with
overwrite and removes the old object (to the trash when configured) only when
the service kept it anyway. It refuses to replace a folder, treats a copy
onto itself as done, and carries the source's resolved modification time,
including rclone_modified and the service's own time.

Every metadata request and operation poll has a deadline that covers
reading the answer, and a token refresh or code exchange has its own, so a
stalled endpoint cannot block the client. Redirects are checked like the
transfer links, an endpoint that would send the token over plain http is
refused unless it is on a loopback host, a 202 without an operation link is
an error, and a read with an offset and no size starts at the offset.

* chore(seaweed-volume): keep only the Yandex fields in the remote.proto copy

* yandex: retry a failed operation poll

One throttled, failed or timed-out status poll ended a wait of up to 30
minutes while the operation kept running on the service, so a large
delete or copy was reported failed and redone.

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

* yandex: refresh a token once for concurrent 401s

Every request rejected with the same access token replaced the token
source, so N concurrent 401s refreshed, and rotated the refresh token,
N times.

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

* yandex: retry an operation poll whose answer was cut short

A status poll that got its 200 headers but lost the connection before the
JSON body ended failed with io.ErrUnexpectedEOF, which the poll retry did
not treat as transient, so the wait ended while the operation kept running.

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

---------

Co-authored-by: Konstantin Lebedev <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:31:14 -08:00
Chris LuandClaude Opus 5.5 dbc64144ca mount: support NFS re-export file handles after inode eviction (-nfsExport) (#12979)
* mount: update go-fuse for the export support option

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

* mount: optionally retain the paths of forgotten inodes

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

* mount: answer lookups of "." and ".." for file handle decoding

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

* mount: add -nfsExport to negotiate export support and retain forgotten inodes

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

* mount: test file handle lookups of "." and ".."

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

* mount: fail a file handle lookup when its path now holds another file

A "." lookup resolved a forgotten inode by its remembered path, so a
file created at that path since was served to the old handle. Compare
the entry's inode with the handle's and answer ESTALE on a mismatch.

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

* mount: register a file handle's inode under the table lock

A "." lookup checked the file at the remembered path and then registered
it with Lookup, which hands back whatever inode holds the path by then.
LookupHandle takes the reference on the handle's own inode, or enters it
at the path only while no other inode holds it.

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

* mount: keep a forgotten inode's retained path across a rename

A rename whose source inode the kernel had already forgotten left the
retained path at the old name, so its file handle failed with ESTALE.
An index from retained path to inode lets MovePath move it.

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

* mount: register a file handle only at its current retained path

A rename between resolving a forgotten inode's path and registering it
moved the retained entry, yet LookupHandle still entered the old path.
It now compares the path with the retained one under the table lock.

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

* mount: drop the target a forgotten inode is renamed over

Moving a forgotten inode's retained path onto a live name left the
replaced inode mapped there. Once a retained entry moves, the target is
taken apart as for a live source and reported as replaced.

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

* mount: test that a renamed path-inode file fails its file handle closed

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

* go.mod: use the go-fuse v2.9.5 release

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:58:56 -08:00
Chris LuandClaude Opus 5.5 36aea0020e weed fix: add -verifyCrc to index needles with damaged data as deleted (#12972)
* fix: add -verifyCrc to leave needles with damaged data out of the index

weed fix reads only record headers, so a needle whose data was damaged is
indexed and fails on every read. With -verifyCrc it reads each body and
checks it; a needle that fails is not indexed, an older copy of its key is
not brought back, and fix exits non-zero.

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

* fix: read each record to verify it, so a read error fails instead of dropping it

The scan passes a body buffer even when reading it failed, so -verifyCrc
took bytes it never read for damage. Read the record through a handle of
its own, drop it only when its bytes are corrupt, and fail the scan on any
other read error. -verifyCrc needs the local .dat.

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

* fix: -verifyCrc rejects a record with a size but no data

A needle with no data is written with size 0, and the CRC covers only the
data, so a record whose data size was zeroed parsed cleanly and skipped
the CRC check. Treat it as corrupt, as the tail repair does.

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

* fix: index a needle that fails -verifyCrc as deleted

Leaving it out of the index let loading the volume read the bytes past
the last indexed needle as an interrupted append: the older copy of the
key came back and the damaged record was cut. Handle it like a delete
marker, so with -includeDeleted its tombstone keeps the key deleted and
the loader leaves the .dat alone.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:49:16 -08:00
Chris LuandClaude Opus 5.5 d6a657cd92 weed compact -method data: copy past an unreadable record like -method index (#12970)
* storage: resume data compaction past an unreadable record

Compacting by data follows record headers through the .dat, so one corrupt
header ended the scan: the compaction failed, or, when the header's size
jumped past the end, every record after it was dropped. Compacting by index
copies past such a record.

When the scan stops on a corrupt header or jumps past live records, resume
it at each live record the index places further on. A read error still
fails the compaction.

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

* storage: do not copy a record whose header size disagrees with the index

A live record whose header carries a damaged size was copied with that
size, and the compacted volume indexed a needle it could not read. The
index records each live record's size, so a header that disagrees is
damaged: skip it, and let the scan resume at the next live record.

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

* storage: verify a live record's body instead of comparing its size with the index

Data compaction copied a record whose body failed to parse, and the size
check dropped an intact record when only its index row was wrong. Read the
body only for the record the index points at, drop it on the same errors
-method index drops on, fail on any other read error, and keep the size
the record itself carries.

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

* storage: resume data compaction at every live record the scan did not reach

The resume started past the last header the scan parsed, so a corrupt size
that landed on a later valid header lost the live records it jumped over.
Track the records the scan copied or dropped, resume at each live record it
did not reach in .dat order, and stop a resumed scan at a record an earlier
pass already handled so nothing is copied twice.

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

* command: read the compacted volume's version from its super block in tests

Compaction can write a different needle version than the source volume,
so parse the .cpd with the version it records instead of the current one.

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

* storage: do not walk a run of damaged headers again on every resume

A record whose header id is damaged is not marked as handled, so each
resume at one of a run of such records walked the rest of the run before
reaching a copied record, which is quadratic in the run length. Remember
the offsets resumed scans pass, skip resuming at them, and stop a resume
when it reaches one.

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

* storage: count the resumed scans' reads in the damaged-run test

The kept keys come out the same when every resume walks the rest of the
run, so bound the reads made through the volume's data backend instead.

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

* storage: drop a record whose header size runs past the end of the .dat

Reading such a record sized its buffer from the corrupt header: a size
near 2 GiB allocated that much on 64-bit and panicked in makeslice on
32-bit. Check the record end against the file size first and drop the
record as unreadable.

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

* needle: compute ReadBytes slice bounds in int

NeedleHeaderSize+size was Size arithmetic and wrapped for a damaged size
near MaxInt32, so the slice panicked instead of failing the read.

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

* needle: fail ReadNeedleBlob for a size that does not fit in an int

On 32-bit a damaged size near MaxInt32 made the buffer length negative
and panicked in makeslice. Return ErrorSizeInvalid instead.

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

* needle: compare DataSize bounds in uint64

On 32-bit builds int(DataSize) is negative for a damaged DataSize of
0x80000000 or more, which passes the bounds check and panics on the
slice instead of returning ErrorCorrupted.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:48:55 -08:00
9ffb5fe185 filer, s3, filer.sync: one digest per cluster, set by the filer's -digest and followed by its clients (#12913)
* util, filer: choose the digest at filer startup with -digest

NewMd5 and NewSha1 returned SHA-256 cut to size whenever the process ran
under GODEBUG=fips140=only, so the kind of digest a cluster stores followed
each process's own environment. They now follow a digest mode set once at
startup: util.SetDigest("md5"|"sha256"), or "" to keep following
fips140.Enforced(). The default is unchanged.

weed filer -digest, weed server -filer.digest and weed mini -filer.digest
set it; fips140=only refuses md5 at startup. The leveldb2/leveldb3
directory-key marker follows the mode, as do the places that compare a
NewMd5 digest with Content-MD5 or pass it on as one: S3 PutObject, filer
HTTP uploads, the Content-MD5 the filer returns, and the uploader's
Content-MD5 to volume servers. Places that verify Content-MD5 with a real
MD5 (volume servers, S3 request bodies and archive uploads) keep keying on
fips140.Enforced(), since they can check it whenever MD5 is available.

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

* filer, command: report the filer's digest and make its clients use it

GetFilerConfigurationResponse carries the filer's digest mode in a new
field 16, digest. weed s3, mount, webdav, sftp, iam and filer.copy adopt
it before they serve or write, so a gateway started with a different
GODEBUG writes the same kind of ETag and chunk digest as the rest of the
cluster. A process under fips140=only refuses a filer that reports md5. A
filer that reports no digest predates the field; the client then keeps
its own mode and logs a warning.

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

* filer.sync, s3 sink: keep digests within one kind

filer.sync copies entry digests and ETags as they are, so syncing a filer
with digest sha256 into one with md5 left SHA-256 ETags in the md5
cluster. It now reads both filers' digests and refuses to start when they
differ, with a warning when either filer does not report one.

The S3 sink sent the entry digest as Content-MD5 unless its own process
ran under fips140=only. From a sha256 source into a target that checks
Content-MD5 every single-part upload failed with BadDigest and the backup
retried it forever. It now asks the source filer for its digest once and
forwards the entry digest only when that is md5.

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

* filer.meta.backup, filer.backup, filer.replicate: keep digests within one kind

filer.meta.backup opened its backup store in its own digest mode, so a copy
of a sha256 filer made by a process outside fips140=only got MD5 directory
keys and could not be opened as that filer's store. It now adopts the source
filer's digest before the store opens.

filer.backup and filer.replicate with a filer sink copied entry digests into
the target filer without comparing digests, as filer.sync did before. Both
now refuse, and exit, when the source and target filers report different
digests. replication.CheckDigestsMatch is the shared check; filer.sync uses
it too.

weed server and weed mini apply -filer.digest before they start the master
and volume server, so every part of the process hashes with one digest.

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

* filer, filer.sync: refuse a peer filer with another digest; exit on mismatch

Filers peering through the meta aggregator now compare digests. A peer with
a store of its own would replay entries holding the other kind of digest
into this filer's store, so its changes are refused and the reason logged
on every reconnect. A fresh filer bootstrapping from such a peer refuses the
copy, so a new filer whose digest differs from the existing filers' exits at
startup. A peer on the same store writes into it directly, and refusing its
stream would only starve this filer's subscribers, so that mismatch is
logged as an error and the stream kept.

filer.sync exits with status 1 when the two filers use different digests,
as filer.backup and filer.replicate do: it is a configuration error a
restart cannot fix.

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

* filer: -digest help says a store keeps the digest it was created with

The help text said existing data keeps the digest it was written with,
which reads as if the flag could be changed on a store with data. Stores
that hash keys stop finding existing entries under another digest, so the
text now says to set it when the store is created, and that switching means
copying the metadata into a new store with fs.meta.save and fs.meta.load.

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

* filer, s3, replication, admin, iceberg: address review of the digest checks

- A filer checks its peers' digests on every start, not only at the fresh-store
  bootstrap: the store signature is written when the store opens, so a fresh
  filer refused at bootstrap restarted as an initialized store and served
  without its peers' files.
- Under digest sha256 with MD5 available (not fips140=only), a client's
  Content-MD5 is checked against a separate real MD5 of the body, in S3 object,
  part and directory-marker uploads and in filer HTTP uploads. It goes
  unchecked only when no MD5 can be computed.
- filer.backup and filer.replicate exit only on a DigestMismatchError; a filer
  that cannot be reached is retried, so a backup started before its target is
  up resumes once the target answers.
- The admin file browser and Iceberg compaction write chunks into a filer they
  do not follow at process level. They read that filer's digest and pass it to
  the chunk upload (ChunkedUploadOption.Digest), so their content and chunk
  digests match the filer's.

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

* filer, s3 sink: retire digest-refused peers; no Content-MD5 for an unknown digest

- A peer refused for its digest counts as unreachable: the check now runs
  before notePeerReachable and its error wraps errPeerUnreachable, so the
  subscribe loop retires the peer from the low watermarks after the usual
  grace instead of keeping its zero watermark, which held every aggregated
  subscriber at the settled horizon.
- When the source filer's digest cannot be read, the S3 sink no longer sends
  the entry digest as Content-MD5: it may be a SHA-256 digest the target
  would reject.
- TestCheckPeerDigest skips the cases that need MD5 locally under
  GODEBUG=fips140=only.

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

* iceberg, util: tests for the per-filer digest

The Iceberg tests' fake filer serves GetFilerConfiguration, which uploads now
call to read the target filer's digest; it reports none, as a filer that
predates the setting does. TestNewContentMd5 computes a real MD5, so it skips
under GODEBUG=fips140=only.

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

* filer: bound each startup peer digest read with a timeout

CheckPeerDigests read each peer's configuration with the caller's context,
which at startup has no deadline, so a peer that accepted the connection but
never answered held the filer's startup. Each read now has its own
peerDigestReadTimeout (10s, inside the one-minute announce cap), after which
the peer is logged and skipped like an unreachable one.

setDigestForTest restores the previous digest setting instead of the default.

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

* util, s3, filer: one-shot digests for data held in memory

Md5For hashes with md5.Sum or sha256.Sum256 instead of writing into a
hash.Hash, and the Content-MD5 checks of S3 directory markers and of filer
uploads saved inside the filer use BodyMd5Of on the bytes they already hold.
Streaming uploads keep their io.TeeReader.

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

* filer: hash Content-MD5 on the upload's digest hash, not on its body

teeContentMd5 wrapped the request body in a TeeReader before
uploadRequestToChunks. CodeQL's go/reflected-xss query follows the body
from r.Body through the chunk upload to upload_content.go's
w.Write(prepared.data), which it resolves to the response-writer
wrappers in s3vectors, s3tables, webdav and server/common.go. Those
flows exist on master from other sources (extract, tagging, the
multipart POST); the wrapped body put them through lines this PR
changed, so CodeQL reported six of them as new.

newUploadHash now builds the digest hash that uploadReaderToChunks and
the inline-append paths already tee the body into, and adds the
separate MD5 there; uploadBodyMd5 reads it back for the check. The body
reaches uploadRequestToChunks as on master. Behaviour is unchanged:
under digest sha256 with MD5 available, Content-MD5 is checked against
the body's MD5, including empty and inline appends.

Checked with CodeQL 2.27.6 (go-queries 1.6.16, ReflectedXss.ql) on this
tree: no flow of the nine reflected-XSS results passes a changed line.

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

* replication: keep the ReadFilerSignature name and return the digest with it

Renaming it to ReadFilerSignatureAndDigest left its other callers with an
undefined function. Keep the name and add the digest to what it returns.

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

* util: keep HashToInt32 off the digest mode

HashToInt32 names things that processes derive on their own, such as a
mount's local socket path and MQ partition key hashes. weed mount adopts
a -digest=sha256 filer's digest before it names its socket, while
weed shell mount.configure keeps md5 and dialed a different socket.
Follow GODEBUG only, as before the digest setting.

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

* filer.meta.backup: wait for the source filer's digest instead of exiting

A backup with a saved offset used to start its stream loop and retry
until the source filer answered. Reading the digest first made it exit
when started before the filer. Retry the read; exit only when the
digest is refused.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-24 20:17:26 -08:00
Chris Lu e22704d25e mini: bind Admin and WebDAV to -ip.bind by default (#12971)
weed mini is a single-host sandbox whose other components already
listen on -ip.bind without authentication. Moving the unauthenticated
Admin UI and WebDAV to loopback broke setups that open them from
another machine on a private network. -admin.allowInsecureBind and
-webdav.allowInsecureBind now default to true; set them to false to
keep an unauthenticated Admin or WebDAV on loopback. The Admin worker
gRPC control plane still defaults to loopback.

Claude-Session: https://claude.ai/code/session_011UpvahFvcQGAmXWpPrXZY1
2026-11-24 17:49:44 -08:00
07e1299f98 mount: add -idmap to allow ID-mapped bind mounts (#12922)
* mount: add -idmap to allow ID-mapped bind mounts

FUSE allows ID-mapped mounts only for a server that announces FUSE_ALLOW_IDMAP.
Once announced, the kernel sends uid and gid 0xFFFFFFFF on most requests after checking permissions itself, so the checks that read the caller treat that value as already checked.

* fuse: refuse an unsupported -o idmap before starting the child

The child exits on checkIdmap, but the parent waits for its readiness signal
and never returns, so weed fuse -o idmap hung on macOS and FreeBSD.

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

* mount: refuse -idmap on Windows instead of ignoring it

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

* fuse: take -o defaultPermissions as the mount flag

-o defaultPermissions=false was forwarded to the kernel as an unknown
option, which failed the mount, and left the flag at true, so
-o idmap,defaultPermissions=false passed the idmap check.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 15:25:34 -08:00
Chris LuandClaude Opus 5.5 1f1d6d057b webdav: optional Basic Auth; mini keeps unauthenticated WebDAV on loopback (#12956)
* webdav: optional HTTP Basic Auth from [webdav.basic_auth]

WebDAV reaches the filer over gRPC, so neither the filer JWT nor the
filer's Basic Auth covers it, and it had no authentication of its own.
With a password set in [webdav.basic_auth], every request needs it.
Without one, startup warns when the gateway listens beyond loopback.

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

* mini: bind WebDAV to loopback unless Basic Auth is set

weed mini starts WebDAV by default on -ip.bind, which is 0.0.0.0, so
anyone on the network could read, write and delete all bucket data even
with S3 IAM on. Without [webdav.basic_auth], bind it to 127.0.0.1, as is
done for the unauthenticated Admin UI. -webdav.allowInsecureBind keeps
the network bind.

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

* command: treat a bracketed IPv6 loopback as loopback

-ip.bind='[::1]' failed net.ParseIP, so mini moved an unauthenticated
WebDAV or Admin listener off it to 127.0.0.1.

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

* security.toml: note TLS for WebDAV Basic Auth

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:57:50 -08:00
0f3a9b315c filer: assignment tokens and chunk proofs for scoped writes (#12923)
* filer: assignment tokens and chunk proofs for scoped writes

* filer: tighten scoped chunk identities and write boundaries

* filer: apply gRPC key removal on config reload

* filer: prevent scoped chunk alias and remote append data loss

* filer: guard scoped writes across stored data representations

* filer: preserve lazy scoped admission lookups

* filer: avoid summing chunk counts for map capacity

* filer: keep a scoped assign in its path's collection

A scoped token could name another bucket's collection in AssignVolume and
upload chunks there, charging that bucket's quota and losing them when that
collection is deleted. A scoped caller now gets the collection its path
resolves to; naming a different one is refused before the master call.

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

* filer: rotate gRPC keys and bind chunk proofs to collections

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 12:30:46 -08:00
9fc8a6aec2 mount: read SSE-S3 objects through the S3 gateway (#12909)
* mount: read SSE-S3 objects through an authenticated S3 gateway

* mount: check each comma-joined mount option against -sseS3ReadEndpoint

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

* mount: read a mounted version file by its object key and version id

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

* mount: read a current null-version object without s3:GetObjectVersion

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

* mount: declare -sseS3ReadEndpoint with the other mount options so weed fuse accepts it

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

* mount: require the canonical bucket path as the root of an SSE-S3 read mount

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

* mount: fall back to the null version when the current object is another version

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

* master: list the S3 endpoint each S3 gateway advertises

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

* s3: advertise the gateway's S3 endpoint to the master

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

* mount: find the S3 gateway through the masters instead of -sseS3ReadEndpoint

-sseS3Read turns gateway reads on. The reader lists the S3 endpoints the
filer's masters have registered, prefers HTTPS, and picks another gateway
when the current one cannot be reached.

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

* mount: retry an unreachable S3 gateway read on a different gateway

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

* mount: warn when -sseS3Read falls back to a plain-HTTP gateway

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

* mount: do not retry an unreachable HTTPS gateway over plain HTTP

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

* mount: tell HTTPS gateways apart by the parsed URL scheme

An S3 gateway advertised as HTTPS://host lost the HTTPS preference and
the plain-HTTP fallback guard, since the check matched the raw string.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 10:32:18 -08:00
Chris LuandClaude Opus 5.5 c7cf9db27c fix/compact: stop at records past EOF, report -ignoreError failures, clean up failed compaction (#12915)
* fix: do not index a record that runs past the end of the .dat

A truncated .dat, or a header whose size points past the file end, left
weed fix indexing a needle the volume cannot serve. Stop the scan at such a
record instead.

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

* fix: exit non-zero under -ignoreError when a volume fails

-ignoreError kept going but always exited 0, so an empty or partial index
looked like success. Record the failure in the exit status, and keep the
existing .idx when the super block could not be read.

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

* compact: remove the partial .cpd/.cpx when compaction fails

A failed weed compact exited through glog.Fatalf and left a partial .cpd
next to the volume. Remove both outputs and report the failure in the
exit status instead.

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

* fix: skip the end-of-file check for a volume on a remote tier

The scan reads the remote object when the .vif lists one, so a retained
local .dat is the wrong length to check records against.

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

* fix: keep a key deleted when its last record is truncated

Stopping before a truncated delete record left the key's earlier live
record in the index, so a deleted file came back. Drop the key instead.

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

* fix: return the .idx open error from SaveToIdx

The bare return gave back the nil named result, so a failure to open the
index looked like a successful save.

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

* fix: exit non-zero when a record is cut off by the end of the .dat

A record past EOF ends the scan like a bad header does, so report it the
same way while keeping the index of the records before it.

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

* compact: close the volume before removing a failed compaction's output

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

* fix: remove a failed .idx only after SaveToIdx opened it

An open failure no longer reaches the caller's cleanup, so an existing
.idx that could not be opened is left in place.

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

* test(s3vectors): drop the worker and CLI flags #12906 removed (#12911)

* test(s3vectors): start weed-worker with only --admin

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:58:26 -08:00
430ca2b585 filer: path- and method-scoped gRPC tokens (scope enforcement, fail closed) (#12904)
* filer: path- and method-scoped tokens on the filesystem gRPC service

* filer: close scoped admission and compatibility gaps

* filer: test subscription key ambiguity and retained write success

* filer: assert verified peer chains survive subscription fallback

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

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

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

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

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

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

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

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

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

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

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

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

* filer: require write grants for scoped lock mutations

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

* filer: enforce WORM retention for scoped mutations

* filer: refuse scoped writes through shared hard links

* filer: drop series notes from scope comments

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

* filer: refuse scoped subtree mutations across WORM rules

---------

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

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

* admin: tell workers where the Lance Namespace is

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

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

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

* helm: weed-worker needs only the admin address

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

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

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

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

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

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

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

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

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

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

* helm: give admin the filer group

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

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

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

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

* helm: drop worker.namespaceUrl

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

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

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

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

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

* helm: weed-vector sizes its own caches

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

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

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

* mini: leave an explicit WEED_VECTOR_SECURITY_TOML to the engine

---------

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

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

* mount: retain response tokens across read cache eviction

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

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

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

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

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

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

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

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

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

---------

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

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

* admin: tell workers where the Lance Namespace is

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

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

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

* helm: weed-worker needs only the admin address

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

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

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

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

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

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

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

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

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

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

* helm: give admin the filer group

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

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

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

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

* helm: drop worker.namespaceUrl

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:23:36 -08:00