mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
cd0f60a2f0858c07ea202b00ebf8df19e65a10a2
432
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ae99aae2cb |
mq: report the caller's deadline when a broker sees it first (#13303)
* mq: report the caller's deadline when a broker sees it first doConfigureTopic checked ctx.Err() to tell the caller's deadline from a broker failure. A broker's DeadlineExceeded status (or its RST_STREAM, which gRPC maps to DeadlineExceeded once the deadline has passed) can arrive before the context's own timer has run, so ctx.Err() was still nil and NewTopicPublisher returned the wrapped gRPC error instead of context.DeadlineExceeded. Once the deadline is behind us, wait for the context's timer before reading ctx.Err(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: let the configure call start before its deadline passes in the test The deadline the test reported had already passed when NewTopicPublisher started, so the check before the first broker caught it and the check after the call was never exercised. The fake broker now moves the deadline behind us only once it has the call, and answers with its own DeadlineExceeded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
97cac5f5e5 |
test: fix mq tests broken by separately merged changes (#13285)
* mq/logstore: rename the tiered copy of a duplicated test name TestTimeReadWithNothingNewKeepsItsPosition was added in both merged_read_test.go and merged_read_table_test.go by changes that merged separately, so the package's tests stopped compiling. The table-backed one becomes TestTieredTimeReadWithNothingNewKeepsItsPosition. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * query engine: make the topic table test's control entry a close marker The test's offset 5 had no key but kept its value, which was a control entry before keyless messages became data. Now only an entry with neither key nor value is skipped, so the baseline scanned that message in both partitions and counted 22 rows instead of 20. Offset 5 drops its value too, so it is the close marker the test means. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2574cedfd3 |
s3: publish a recovered PUT's event at its commit stamp (#13265)
* s3: publish a recovered PUT's event at the stored entry's commit stamp A PUT whose create committed but lost its answer, and that recovery then found stored, published its event at the gateway's clock. A later write to the same key that carries its filer stamp could then sort before it. Both recovery paths now take the stamp the committing filer gave the stored entry, as recovered multipart completions do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: return the context error when it ends a topic configure A start whose context ended during ConfigureTopic on the last broker answered with the RPC's text, so errors.Is(err, context.Canceled) did not hold for it as it does for a context that ends before an attempt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: name the broker whose topic configure failed doConfigureTopic built lastErr with the broker address but returned the bare RPC error, so a failed configure did not say which broker refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2b157f2ef1 |
test: clear the codespell hits left after #13290 (#13264)
* test: use a codespell-clean non-ASCII key in TestEncodeKey Codespell reads caf%C3%A9 as the misspelling caf. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * topictable: reword want's in the CheckSchema comment Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ab6b1598b9 |
mq/offset: fix a flaky partial-listing test (#13288)
mq/offset: fail the test lookup the way a filer store does TestListConsumerGroupPositionsReturnsWhatItReadOnAFailure flaked (about 1 in 60 runs): its fake filer failed the unreadable position with codes.Unavailable and no details, which pb treats as a dead channel. The shared ClientConn was closed and the concurrent loads of the other partitions failed with it, so the listing returned one position, not two. A real filer answers a store read error with a plain error (codes.Unknown), which keeps the channel. The fake now does the same. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
51d2b2b712 |
mq: read a table-backed topic's history from its Iceberg table (#13260)
* mq: read a topic table's data files back as log entries A view of a topic's table holds the current snapshot's offset map and, per _partition, its data files with the _offset and _ts_ns bounds from the manifests. A partition's rows are read by offset or by time, skipping files and then row groups whose bounds miss the read, and come back as the log entries they were copied from: key, timestamp, offset, and the message as _value or as the record re-encoded from its columns. Views are cached per topic, rechecked every few seconds, rebuilt only when the metadata location moves, reuse already-parsed manifests, and are evicted past a bound on the data files they hold. A table that is gone or replaced by another UUID reads as empty; one with delete files is refused. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a table-backed partition below its table's high-water mark from the table The merged reader takes the partition's table, looked up on every read so a table attached later is seen. An offset read below the mark reads the table up to the mark and continues into the log files and compacted parquet from the mark; a time read takes the table's rows after the time and then the files' entries at or above the mark. Log files left below the mark by a crash between the writer's commit and its delete are never read. The broker hands its partitions' disk reads to the table through the topic's cached view; a topic without a table, or whose topic.conf is gone, reads its files as before. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: start a table-backed partition's offsets at its table A partition whose log files below the table's high-water mark were deleted would reload with a high-water mark and log start taken from the files that are left. Loading it now continues its offsets no lower than the table's mark and starts its log at the table's lowest offset, or, when the table holds nothing of it, at the first file offset at or above the mark. A retired range of a repartitioned topic is read and bounded the same way, and a retention purge raises the log start likewise, so purging hot log files never makes the table's offsets out of range. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: keep a flushed data source's finished flag atomic The streaming goroutine sets finished while the merge loop reads it through HasMore, which the race detector reports on any scan that reads flushed data. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: scan a table-backed topic's history from its table The hybrid scanner hands each partition's merged read the topic's table, so a scan reads the table's data files below the partition's high-water mark, pruned by _partition, _offset and _ts_ns, and log files from the mark on, skipping any a crash left below it. Aggregations no longer answer such a topic from parquet statistics and log counts, which hold none of its table's rows; they scan instead. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a schematized row's raw _value back as its message A schematized topic's table can keep a message that is not a record, a tombstone or an undecodable value, as raw bytes in an optional _value with the record columns null. Such a row now reads back as those bytes; a row whose _value is null reads back as its record, and a schemaless topic's row as its _value as before. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: delete log files a topic table already holds A log file or compacted parquet whose every offset is below a partition's table high-water mark is never read again, so it can go. The mark used is that of the newest snapshot at least a minute old: a reader's view of the table is at most a few seconds old, so it already reads those offsets from the table and never from a file being deleted. Files without an offset range and the file holding the partition's highest offset are always kept. DeleteCoveredLogFiles is for the topic's writer after its commit; a leader also deletes them under its fence on load and on each retention pass, covering a writer that crashed between its commit and its delete. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: report a topic table's rows as parquet_archive A table-backed topic's scan labelled every row live_log, its table's included. The flushed data source now records the high-water mark of the table its merged read was handed and reports the rows below it, which come only from the table's parquet data files, as parquet_archive. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: delete the log files a topic table holds after each run Every mq_topic_table run now ends by deleting, in each partition, the log files wholly below the offsets of the newest snapshot at least LogDeleteGrace old, never the leader's newest file. A commit is never old enough on the run that makes it, so each run deletes what earlier ones copied; the partition's leader deletes the same files when no run follows. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a time read's position when nothing on disk follows it A time read that found nothing after its position returned a position at time zero: the parquet reader reports the newest time it delivered, which is none. A loop over an empty memory buffer then read the whole partition from the start, came back to the same empty read, and started over, so a query asking a broker for its unflushed messages streamed the partition forever. The merged and the table-tiered readers now keep the position when they deliver nothing past it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: publish a topic table view under the lock eviction reads it with A loaded view was stored under its entry's loading lock while eviction, run by another topic's load, read every entry's view under the cache's lock, so two topics refreshing at once raced. A view is now stored holding both locks: a load reads it under the first, eviction under the second. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep no topic table view larger than the whole view cache Eviction never dropped the view just loaded, so one topic whose table had more data files than the cache's bound stayed cached past it, and evicted every other topic's view on the way. Such a view is now answered and not kept; the others stay. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: look up a topic table's mark again where a read leaves the table A read kept the table mark it started with. One slow over the table's rows could outlast the grace: the writer commits past that mark, the logs below the new mark are deleted, and the read then lists the logs from its old mark and passes over the deleted offsets without a word. The read now asks for the table again each time it leaves it and reads on in the table up to the mark it finds, until the mark stops moving; a time read takes the rows between the marks by offset. A gap where the logs begin is checked against the table once more, and read from the table if it took it meanwhile. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a topic table's timestamps back without going through nanoseconds A timestamp or time column was turned into micros by way of nanoseconds, which overflow for dates before 1678 or after 2261, so a year 1 or year 9999 value came back as another date. Each unit now converts to micros directly. The table fixture wrote every topic's rows whole into _value once every table had that column, so the record columns these reads take went untested; it now writes a schematized topic's rows as columns. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * iceberg: order a compaction bin by the first sort field that varies in it A topic table sorts by _partition, then _offset, and is partitioned by _partition, so every file of a bin holds one _partition. Ordering the bin by it kept the files in manifest order, and a merged file's offsets came out of order for the topic table reader, which delivers a data file's rows as offsets in order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: list a retired range from its table's lowest offset A topic lookup lists each retired range with the bounds of its own files, so once the table held a range's history and its log files went, the range was listed from its newest file on, while its reader serves the table's offsets below it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * iceberg: never merge compaction inputs across a file left out of the merge A file already at the target size takes no part in compaction, yet small files on both sides of it in sort order went into one bin, so the merged file's bounds spanned it. For a topic table that is a data file whose _offset range overlaps another's, which a reader finishing one file before the next cannot read in order. An ordered bin is now cut wherever a file left out of the merge falls between two of its files, so every merged file covers a range no file outside its run lies in. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: merge a topic table's overlapping data files by offset when reading A partition's data files were read one after another by their lowest offset, which only reads in offset order while no two ranges overlap. A rewrite by another engine can leave a file spanning another one, and then a read from inside the overlap delivered the spanning file's later rows first, and a read that stopped early left the rows in between behind. Files whose offset ranges overlap are now read together, their rows merged by offset and an offset held twice delivered once. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: open a topic table's data files only as a read reaches them A merged read opened every file of an overlapping group before it delivered a row, and a file the manifest records no offset bounds for overlaps every other one, so a short fetch held a reader for each file of the partition's history. The files of a read now wait in a heap keyed by the lowest offset each can hold, and a file is opened only once nothing before that offset is left to deliver; a file without bounds is opened where the read starts, and its row groups' statistics skip what they rule out. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: retire no log file a topic's table does not hold yet Retention deleted a table-backed topic's log files by age alone, so with the table writer behind it deleted messages the table did not hold, and they were gone from both. On such a topic a file now expires only once all it holds is below the table's mark of a grace-old snapshot, the same files the leader deletes as covered; what the table holds ages out with table retention. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: bound a table-backed range's bounds by its caller's deadline The table lookup that widens a partition's bounds ran under a background context, so a retention pass or a retired-range lookup with a deadline waited on a stalled table catalog for as long as it stalled. It now runs under the caller's context. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: check a topic table's mark again when a time read reaches its files A time read caught up with the table and then read the files above the mark it last saw. A view that had moved on meanwhile, with the logs below its new mark deleted before the files were listed, left the offsets between the two marks to neither. The time read now asks for the table again at the first file entry it would deliver, or after the files if they held none, and on a moved mark reads the table up to it before reading the files again. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: bound the topic table views kept, empty ones included, and keep those in use Eviction only counted data files, so views of tables holding none, and entries a failed first load left behind, were never dropped; and it could drop an entry while a caller was loading it, so the next caller loaded the same table again alongside. A failed first load now leaves no entry, at most maxCachedTopics views are kept, and an entry a caller still holds is never evicted. The eviction test now requires exactly the one eviction that makes room. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: check a topic table afresh before deleting the logs below its mark A leader's covered-log delete and log retention took the table's mark from the cached view, up to a few seconds old, so a table rolled back to a lower mark meanwhile had its logs above that mark deleted although it no longer held them. Both now check the table before acting: the cache takes a maximum age, a read passes ViewRefresh and a delete zero. A cached view is also reused only for the same table state, since a commit that rewrote the metadata in place keeps its location. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * iceberg: leave a sort field holding nulls to order a compaction bin A sort field whose bounds are one value in every file was taken as constant and the bin ordered by the next field, yet bounds leave nulls and NaNs out, so a column holding them besides its one value is not constant. A field is now skipped only when the files also record no null in it, and no NaN for a floating point one. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: delete a topic's covered logs only while it still names the table A run's log cleanup used the table metadata the run started with, so after the topic left the table, or the run lost its lock, it still deleted the logs below that table's marks. The cleanup now checks, when it runs, that it still holds the topic's lock and that topic.conf still names the table with its recorded UUID, and reads the marks from the table as it is then. It still runs after a run that failed otherwise. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: check a topic table again before each covered log it deletes The leader read the table's mark once, listed the files below it, then deleted them one by one, so a rollback or a detach landing in between went unseen and files the table no longer held were deleted. The delete now holds the table writer's lock, so the topic cannot leave the table meanwhile, and before each file reads topic.conf and the table afresh, stopping at the first file not below the mark it finds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: let a caller waiting on a topic table's load give up at its deadline A caller wanting the view a stalled load of the same table was making waited on a mutex, past its own deadline, for as long as the load stalled. The entry is now held by a one-token channel a waiter selects on with its context, so it returns at its deadline and lets go of the entry. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: give up a scan's table lookup when the query is cancelled The table a scan reads below each partition's mark was looked up under a background context, and the flushed data source waited on its channels alone, so a cancelled query stayed blocked on a stalled table catalog. The scan's context now reaches the topic.conf read and the table lookup, and the data source returns once it is done. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: take a topic table's lock only when a covered log is left to delete The leader's covered-log pass took the table writer's lock for every table-backed partition it leads once the table had a mark, every five minutes, even with nothing to delete. While a copy run held the lock, each such partition waited out the lock wait and logged a failure, holding up the rest of the retention tick. List the covered files first and take the lock only when there are some; the per-file checks under the lock stay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drop a topic table view only with the last caller holding it An oversized view was removed while other callers still held it, so the next caller loaded it again alongside; an entry no load filled was removed only by a failing load that was its sole holder, so one whose callers failed or gave up in another order stayed; and eviction that found every candidate held left the cache above its bounds with nothing to evict again. Callers now let go through one release: the last one removes an entry no load filled or one marked to drop, as an oversized view is, and each release runs eviction again. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * worker: check a topic's table again before each covered log the cleanup deletes The cleanup checked the lock, topic.conf and the table once, then deleted every file below the marks it read, so a detach, a dropped or replaced table, or a lapsed lease landing during the deletes went unseen. The deletes now check all three again before each file, with the mark of the table as it is then, and stop at the first file not below it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: let a flushed data source's producer close its own channels Next can return on the query's cancellation while the producer is still sending, and the merge then closes the source, which closed the result and error channels under that send. The producer now owns them: Close only signals it to stop, every send also selects on that signal, and the producer closes the result channel when it exits, after sending its one error if it has one. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: fail a scan whose data source fails after its first row The merge only logged an error from a source past its first row, the query's cancellation included, and returned the rows read so far, so a cancelled or timed-out COUNT or SUM answered with a wrong number. It now closes its sources and returns the error, and the scan wraps it, so a caller can tell the context's error from others. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: check a topic table again before each group retention deletes Retention read a table-backed partition's deletable mark once, chose its expired groups, then deleted them with no further look, as the covered-log delete did before it rechecked; a rollback in between left groups deleted that the table no longer held. The live and retired purges and the covered-log delete now share one guard: it holds the table writer's lock and, before each group or file, reads topic.conf and the table afresh, stopping at the first one not below the mark it finds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: bound a partition load's reads of what it already stores Loading a partition reads its files' offset range and, for a table-backed topic, the table's, while holding accessLock, under a background context, so a stalled filer or table catalog held every other partition operation for as long as it stalled. The reads now get the bound a load's fence take has; past it the load fails, as it does when the stored offsets cannot be read, and the caller retries. Falling back to the log files' bounds would start the log above the table's offsets with no later refresh to lower it, so consumers resetting to the earliest offset would skip the table's history. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: count a flushed source's pending error as more to read The merge asks HasMore before reading a source again, and HasMore looked only at buffered rows and whether the producer finished, so a producer that failed after its last row and finished before the merge asked had its error never read, and the scan returned the rows so far as its answer. An error waiting counts as more to read now, so Next returns it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: keep the table's files of a topic that left it before the delete A topic that left its table between the listing of what the table held and the guard the delete takes got no guard, which let every listed file go, though readers take those offsets from the logs again. Files chosen by the table's rules, the covered logs and the groups retention trimmed to the table's mark, are now kept when no table remains; files of a topic that had no table when the pass began still expire as before. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query: order the pending-error merge test's row before its error The test's producer could send its error before the first Next took the row, and Next then picked either one, so on some runs the error came through the first read and the test passed without exercising HasMore. The producer now holds its error until the first Next has the row, and the merge asks again only after the producer has finished, so the test fails every time without the pending-error fix. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: read a topic table's chunk-backed files under the caller's context A manifest or manifest list stored in chunks was read through a stream reader built without a context, and the stream reader looked up and fetched each chunk under a background context even when built with one, so a stalled volume server held a partition load past its bound while it held accessLock. A chunk stream reader now looks up and fetches its chunks under the context it was built with, and a table's chunk-backed files are read with the caller's. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: keep the expiredLogFiles doc comment on expiredLogFiles Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: let the table catalog read chunk-backed table metadata The broker's table catalog reached its filers through a client with no way to look up chunk locations, so a table whose catalog record holds only the location of its metadata, as one whose metadata outgrew a request does, failed to load once that file was stored in chunks: the topic's history could not be read. The client now resolves chunks the way the broker's own filer client does. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * iceberg: read chunk-backed table metadata under the caller's context A catalog record holding only a metadata location had its chunk-backed file read by StreamContent, whose lookups and fetches run under a background context, so a stalled volume server held a table load past its caller's deadline: a broker loading a table-backed partition under accessLock past its bound. The read now streams under the read's own context, which already bounds its other filer calls. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * filer: give up a LookupFn volume lookup's retries at its caller's deadline LookupFn retried a failed volume lookup through util.Retry, which sleeps its backoff without looking at the caller's context, so a lookup failing near a deadline outlived it by up to the whole backoff; a table load under a broker's accessLock held it that long. The lookup now retries through util.RetryWithBackoff with the same transient-error rule and about the same total wait, which stops when the context is done. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
284d491587 |
s3: forward notification topics to webhook targets (#13245)
* util: move the guarded dialer out of the volume server The deny list and the dialer that re-checks every resolved address at connect time move into weed/util/netguard, with the allow-private knob as a policy, so other outbound clients can dial through the same guard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: fence consumer group position saves by generation A position saved with a generation is written only while the stored one carries no newer generation, or the same generation from another writer: the save reads the stored position and writes on the condition that it is unchanged, routed to the entry's owner filer, and re-reads when another writer got there first. A single consumer that elects itself can then store its offsets without a deposed predecessor overwriting them. Saves without a generation keep overwriting as before. Loading a missing position now reports ErrNotFound instead of trying every filer and marking each one failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: post bucket event batches to a webhook target A webhook destination renders a batch of records as one {"Records":[...]} body, posts it with the target's bearer token, and takes any 2xx as delivered. The renderer is a function the destination holds, a stand-in that refuses until the record renderer lands. It dials through the guarded dialer under a new Local policy, which refuses metadata-service, link-local and unspecified addresses at connect time but lets an operator point a target at a private host or a sidecar on loopback. Redirects are followed only to the endpoint's own host and never down from https. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: forward each target's topic to its destination A Forwarder runs beside the Publisher on every gateway. Each enabled target with a destination gets a lock, s3.notify.<target>, held through LockClient.StartLongLivedLock, so one gateway forwards a target and targets spread across gateways; a topic target has none. The holder runs one loop per partition of the target's topic: fetch from the stored offset at the partition's leader, decode the records, deliver them as one batch, store the next offset. A fetch that stops short at a segment boundary just continues from its next offset. A failed send, a rejected one included, blocks the partition and is retried with capped backoff, and the offset is stored only after the destination took the batch. An offset that retention removed skips to the earliest one and counts the gap. Offsets go to the consumer group offset storage under group forwarder, fenced by the lock generation. On taking the lock a forwarder stores each partition's offset back under its generation, so an older holder's saves are refused and it stops. A stored generation at or above its own means the lock was lost, unless the forwarder has since held the lock through a full renewal, which happens only when the lock server's counter restarted; it then fences above the stored generation. Metrics per target: records delivered, send retries, retention gaps, and lag from the forwarding gateway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: run notification forwarders beside the publisher Every gateway with filers starts a Forwarder with the publisher. It elects itself per target through the gateway's object-write lock client, stores offsets in the filer, reads through the same brokers the publisher uses, follows the target registry as the publisher does, and releases its locks on shutdown. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: post a test event to a webhook on its own The renderer refuses an s3:TestEvent that shares a body with other records, so a webhook splits a batch around each one and posts them in order, the test event as its own body. The test is a stand-in until the renderer's lands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: skip a bucket event record that can never be delivered A record that does not decode, or that the renderer refuses, used to be retried like a failed send and would block its partition for good. The webhook now renders a whole batch before posting any of it and names the records that cannot render; the forwarder drops those, counts them per target and reason in notification_skipped_records_total, logs each offset once, and sends the rest. Only transport and HTTP failures are retried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: read a fenced position save at the filer that applies it The fenced save read the stored position from whichever filer answered and then sent its conditional write to the key's owner, so with filers that keep their own stores the condition could be checked against an entry other than the one read, failing until replication caught up or judging a stale copy. The storage now takes the ring's owner lookup, the one route-by-key writes already use, and sends both the read and the write to that filer. The gateway hands its object-write lock client's PrimaryForKey to the forwarder offsets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: follow a repartitioned notification topic A forwarder listed its topic's partitions once, when it took the lock, so a repartition left the new partitions unforwarded until the lock moved. It now lists them again every 30 seconds, starts a loop for each new partition, and marks the loops of partitions no longer listed as replaced; such a loop keeps delivering what its partition holds and ends once it has caught up. A failed fetch now looks up the leader of that exact partition, not of any partition with the same range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: let the first forwarder take the lock before the second asks The election test synced both gateways at once, and each forwarder asks for its lock from its own goroutine, so the second could ask first and store the offsets the test expected from the first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: warn when a partition returns nothing below its high-water mark A fetch that returned no records and kept its next offset below the high-water mark looked like an idle partition, so the forwarder waited without a word while its lag stayed up. It still waits, since skipping would lose the records, but now warns at most once a minute with the topic, partition, offset and high-water mark, so the lag has an explanation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: render webhook bodies with the bucket event renderer The webhook now renders through Render and posts each s3:TestEvent alone by IsTestEvent, replacing the stand-ins it held until the renderer landed. The tests send real records and read the object keys and test request ids back out of the bodies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * netguard: refuse the IPv6 and Alibaba metadata service addresses AWS's IPv6 metadata address fd00:ec2::254 is unique-local and Alibaba's 100.100.100.200 sits in the CGNAT range, so the Private and Local policies let a webhook or remote endpoint reach them. Refuse both under every policy, like 169.254.169.254. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * grafana: chart the notification forwarder metrics Add an S3 Notifications row with delivered records, lag, send retries, and records skipped or lost to retention per target. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: follow only webhook redirects that keep the POST On a 301, 302 or 303 Go resends the request as a GET without a body, so an endpoint that redirected and then answered 2xx counted as delivered while it received no records. Only 307 and 308, which keep the method and resend the body, are followed now; any other redirect fails the send and is retried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep webhook endpoint secrets out of errors and logs The guarded dialer names its endpoint in every refusal, and the forwarder logs that error, so a webhook endpoint carrying credentials in its userinfo or a token in its query had them written to the log. The dialer now gets the endpoint as scheme, host and path only, and the parse and request errors no longer echo the URL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: load a consumer group position from its owner filer A forwarder taking over read its start offset from whichever filer answered, while its fenced saves read and write at the key's owner. With filers that keep their own stores, a replica still holding an older offset handed the new holder that offset, which it then stored under its higher generation at the owner, replaying everything delivered since. Loads now go to the owner too when the storage knows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound consumer group position loads and saves by the caller LoadConsumerGroupPosition and SaveConsumerGroupPosition ran their filer calls under context.Background(), so a filer whose store stalled held a forwarder's save forever: ending the lead waited on it, the lock was never released, and Close hung while the lock kept renewing. Both now take the caller's context; the forwarder gives each call its RPC deadline under the lead's context, so stopping returns and the lock is released. The offset wrappers the broker uses keep their signatures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: list a consumer group's positions across partition generations ListConsumerGroupPositions walks every generation and range directory of a topic and returns the group's stored position in each, keyed by partition directory, so a consumer can tell which ranges it holds offsets for that the topic no longer lists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: stop forwarding ranges a repartition removed A repartition drops the old assignments, and the broker serves only assigned ranges, so the loop draining a removed range retried a refused fetch forever, and after a restart nothing looked at it at all. Reading a removed range's flushed data would need a read-only path in the broker. Until then a removed range's loop delivers the batch it holds and ends, and the forwarder logs an error naming each range it stops and, when it takes the lock, each partition directory holding a stored offset the topic no longer lists. The fake broker now refuses unassigned ranges as the real one does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: deliver what a repartition left in the retired ranges The lookup now offers the sealed ranges a repartition retired, and any broker serves them from their files, so the forwarder no longer drops them. On taking the lock and on each re-list it asks for the retired ranges too and runs a loop for each, from its stored offset up to its high-water mark, after which the loop ends; a range it was forwarding as current and that is now retired gets the same end. A read below a retired range's log start counts as a retention gap, as for a live one. A key's records in a retired range precede its records in the ranges that replaced it, and loops running side by side would not keep that order. So the retired ranges go first, one generation at a time, oldest first, and the current ranges start only once none is left. A range listed neither as assigned nor as retired, as while a drained range is not sealed yet, pauses until it is offered again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: match a retired range to its forwarding loop by directory The broker lists a retired range at the second its generation directory is named for, while the assignment the forwarder started its loop from carried nanoseconds. After a repartition the retired entry missed the running loop, so a second loop started on the same stored offset and delivered the batch the first was still retrying. Key the loops by partition directory; the fake broker now lists retired ranges and the fake positions store offsets at that resolution, like the real ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: replace a paused forwarding loop only once it ended A range drained but not sealed yet is listed neither as assigned nor as retired, so its loop is paused and dropped from the lead's loops while it may still be retrying a batch. Once the range was offered as retired a new loop started at the stored offset and sent that batch again. Keep a paused loop until it ends, and start the range again only then. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: hold the new ranges while a drained one is not sealed yet A repartition saves the new ranges before it drains and seals the old ones, so for a while an old range is offered neither as assigned nor as retired, and the forwarder started the new ranges at once: a key's new records could go out before its records still waiting in the old range. On each look at the topic the forwarder now lists the directories holding a stored offset that the topic does not offer, and probes each at its offset; one that may still hold records past it, refused because it is not sealed, holds the new ranges until it is offered as retired and drained. One that answers with nothing past the stored offset is settled, sealed and empty or already delivered, and stays so for the lead. While holding, the forwarder logs at most once a minute and keeps looking even with no loop running. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: have the fake broker serve only the generation a fetch names The broker now refuses a fetch naming a generation other than the one it assigns for the range, unless that generation is sealed and read as retired. The forwarder tests' fake broker matched an assigned range by its range alone, so it served the live generation to a fetch for an older, unsealed one; it now matches the generation too, as the broker does. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold the current ranges until the stored offsets can be listed A lead whose first look at the stored offsets failed took that as no old range left unsettled and started the current ranges, delivering a key's newer records ahead of the ones still in a drained range that is not sealed yet. A failed look now holds the current ranges as an unsettled range does, and is retried with backoff and on each partition refresh; the current ranges start only after a look succeeds. Retired ranges and loops already running carry on meanwhile. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3api: leave forwarding off on an unusable broker TLS config The forwarder loaded the grpc.msg_broker client TLS config with LoadClientTLS, which exits the process on a bad one, and every gateway with filers builds a forwarder whether or not it has webhook targets. It now loads it as the publisher does: an unusable config is logged and leaves forwarding off while the gateway keeps serving. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold the new ranges for an unsealed old range with no stored offset The check for old ranges still unsealed looked only at ranges holding a forwarder offset. A forwarder starting for the first time while a drained range was not sealed yet had stored none in it, so it started the new ranges and delivered a key's newer records ahead of its older ones. The consumer group listing now names every partition directory of the topic, with no position where the group stored none, and such a range is probed from offset 0. A range with nothing left past that offset, including one whose records retention already removed, is settled. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: check the load in the fenced save race test The test read the stored position back ignoring the load's error, so a failed load panicked on a nil position instead of reporting the error. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: take a partition over at the offset its last holder committed A new forwarder generation claimed a partition by writing the offset it had loaded. When the old generation committed again in between, the claim rewound the stored offset and the new lead replayed what had been delivered since. A fenced save that takes over from an older generation now keeps the offset that generation committed last, rereading it on a conditional write miss, and hands it back in the position, and the forwarder starts from it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: wait for a position's owner filer instead of asking another A position store routed by owner fell back to any filer while the owner of a key was not known yet, as before the lock ring is learned. That filer's not-found ended the load there, though it may only not have caught up, and a claim on it would start the partition over. Loads and fenced saves now fail until the owner is known, and the forwarder retries them; a store without an owner routing still uses any filer. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: wait for the last checkpoint before a forwarder handoff in tests The resume, repartition and election tests stopped the first forwarder once its records were delivered but possibly before their offsets were stored, so they could pass on a replay rather than on a committed handoff. They now wait for the final offsets first. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: have Close wait for removed targets to release their locks A target removed from the registry had its forwarder cancelled and dropped from the targets, so a Close soon after did not wait for it and returned with that target's lock possibly still held. Removed forwarders are now kept until they are done, and Close waits for them as well. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold newer retired generations behind an unsealed older one A range of an old generation still unsealed held back only the current ranges. A generation retired after it was offered and delivered right away, ahead of the older generation's records of the same keys. The unsealed range's generation now counts as the oldest one left, so only that generation's own sealed ranges are forwarded until it is sealed. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: check the forwarder lock right before each send A lead checked its lock at the top of each fetch and after a failed send's backoff, so a lead that lost the lock while it fetched a batch still sent it, and the next holder sent it again. The lock is now checked right before each send. Delivery stays at-least-once: a lock lost during a send cancels that send once the lead notices, which may be after the endpoint took the batch. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: read a retired range past a broker that answers with an error Any broker serves a retired range from its files, but a fetch took the first broker's answer even when it was a storage error, and each retry asked that broker first again, so one broker that could not read the files held the range up for good. A retired fetch answered with an error other than an offset out of range now goes on to the next broker, and returns the error only when none could read it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: count ranges held back behind an older generation in the lag The lag gauge summed what each running loop reported, so the current ranges held back while an older generation was still unsealed, and the retired generations waiting their turn, showed no lag however much piled up in them. On each partition refresh the lead now reports their lag from the stored offset to the high-water mark, read from the range's leader or the retired listing, and drops the lag of ranges it no longer has. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold retired generations too while stored offsets cannot be listed A lead whose look at the stored offsets failed held only the current ranges and went on forwarding retired generations, though an older generation it could not see might still be unsealed and hold earlier records of the same keys. A failed look now holds every range not yet running until a look succeeds; loops already running carry on. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: read stored offsets only of the ranges a lead does not know yet The check for unsettled ranges listed every partition directory and read every stored offset in it one by one under one deadline, before dropping the ranges the topic offers and those already found settled. A topic with many past generations could take longer than the deadline on every refresh and hold a new lead for good. The listing now takes the directories to skip and reads only the remaining offsets, a few at a time, and the lead skips the offered ranges and those it found settled. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: test the failed-listing hold with no unsealed range The failed-listing test also had an older generation unsealed, which holds the newer ranges on its own once a listing succeeds, so it did not show the listing guard by itself. A second case has no unsealed range: nothing goes out while the listing fails, and both the retired and the current range do once it succeeds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: stop the lead before marking a failed loop ended A forwarding loop that failed, as on being deposed, was marked ended before it cancelled its lead. A partition refresh in between saw a retired range's loop ended, took the range as delivered, and started the next generation's ranges on the lead that was about to stop. The lead is now cancelled first, so no refresh acts on the failed loop. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: count no retention gap below an offset only claimed A lead claiming a partition with no stored offset wrote offset 0 to fence it before reading anything. A lead that stopped there left 0 behind, and the next one, finding the log start past it, counted those offsets as lost though no forwarder had ever been at them. A claim made before any read is now marked as such, a takeover keeps the marker of the entry it replaces, and only an offset a lead read from counts a gap. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: retry a takeover save at the offset it kept A claim's save that took a partition over from an older generation kept that generation's last offset, but when its reply was lost the retry went out with the offset the claim had loaded. The stored entry was by then the claim's own, so the retry kept nothing and rewound the partition, replaying what had been delivered since. A failed save now retries with the offset and marker the attempt settled on. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: store an offset as read from once the first fetch succeeds A claimed offset lost its claimed marker only when a later save moved it, so a lead that read an empty partition and stopped left it marked as never read. Records published and then removed by retention while no gateway forwarded the target were skipped without a gap counted or logged. The first successful fetch now stores the offset as read from, once per claim, even when it has not moved. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: wait for the stalled topic's publisher before reading it in a test The worker sets the topic publisher up on its own goroutine, which on a loaded host can start after Publish has stopped waiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep what a timed-out offset check settled for the next one A check for unsettled ranges that could not read every stored offset within its deadline returned nothing, so each retry read the same ranges again and a long enough history kept the new ranges held for good. The listing now returns the positions it read along with the error and goes on past one that fails, and the check probes those and keeps the ranges it finds settled before reporting the failure, so the next check reads only the rest. The ranges stay held until a check covers them all. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: say which records the notification lag counts The lag gauge's help, and the dashboard panel with none, read as every undelivered record, but the records of an old range still being sealed after a repartition cannot be read and are not counted. Both now say the gauge covers the current ranges, the ranges held back behind an older generation, and the sealed retired ranges. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
960230f86d |
mq: keep keyless and valueless messages in compacted parquet (#13258)
* mq: keep keyless and valueless messages in compacted parquet mq.topic.compact treated every message without a key, every message without a value, and every value that happened to parse as a DataMessage with a Ctrl as a control entry, and left it out of the parquet it wrote. Kafka records with a null key and tombstones were gone once retention removed their logs, and so was a JSON string value whose bytes parse that way. The only control entry a log holds is a publisher's close marker, which the broker logged without its Ctrl, as an entry with neither key nor value. That is now the whole rule, for compaction and for reading parquet back. A schematized topic's message without a value is still left out, since its row has no column to hold one. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: ack a publisher's close marker without logging it The marker a publisher sends when it finishes was appended to the partition log like a message, minus its Ctrl, so it took an offset and sat in the log as an entry with neither key nor value that every reader had to recognize and skip. The broker now acks it and moves on. Every message the publisher sent before it on the stream was acked first, so the publisher's wait for its last ack is unchanged. Logs written before still hold markers, which readers keep skipping. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq broker: log a Ctrl message that carries a key or value The close-marker branch dropped every DataMessage with a Ctrl, though one carrying a key or value was published before. Only a bare marker, a Ctrl with neither, is acked without an offset now; anything else is stored at its offset as it was. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * query engine: skip only close markers, as compaction does Compaction now keeps keyless messages and values that happen to parse as a DataMessage with a Ctrl, but the SQL engine still dropped both from log scans and live-log counts, while COUNT(*) took parquet row counts from file stats. After compaction COUNT(*) included messages SELECT did not show. Scans and counts now use the same rule as compaction and parquet reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * query engine: leave out a schematized message without a value, as compaction does Compaction writes no row for a schematized message without a value, so a live log count that included one dropped by one once its log was compacted. Scans and live-log counts now skip what compaction skips. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * query engine: count only rows among broker-buffered messages The COUNT(*) fast path added every unflushed broker message, so a close marker or a schematized message without a value counted until its flush, when the live-log count left it out. Unflushed messages now count by the same row rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * query engine: test the broker-buffered count against the scan COUNT(*) adds the broker's unflushed messages by the row rule a scan of them uses, but nothing tested it. The count moves into countRows, and the scan test checks it gives the number of rows the scan returns for a schemaless and a schematized topic, so close markers and schematized messages without a value stay out of both. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6a9fe874d7 |
mq: keep a time read's position when nothing on disk follows it (#13259)
A time read that found nothing after its position returned a position at time zero, since the parquet reader reports the newest time it delivered. A loop over an empty memory buffer then read the partition again from the start. The broker's unflushed-message query does exactly that, so once a partition's buffer was flushed and empty it streamed every flushed message as unflushed, and weed sql counted each row twice. The merged reader now keeps the position when it delivers nothing past it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 |
||
|
|
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> |
||
|
|
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> |
||
|
|
2cde975c25 |
mq: read, list and purge the ranges a repartition retires (#13249)
* mq: seal a partition's fence when a repartition drains it Draining a partition shut it down and answered at once: its last window was still being flushed, and its fence was left unsealed. A publisher still holding the old assignment could then load the range again on its leader at the same epoch and append to a range the topic no longer lists, so nothing could treat a removed range as complete. The drain now waits for the last flush, waiting out a retirement already pending too, and seals the fence before it answers; a drained range its leader does not have loaded has its stored fence sealed as found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: serve a sealed range a repartition removed from its files A repartition drops the old ranges from the topic, and a fetch for one was answered partition not found, so whatever a consumer had not read from it was out of reach. A fetch naming a generation and range the topic no longer assigns, whose fence is sealed, is now served read-only by any broker: a stopped log buffer over the range's files, with its log start and high-water mark read from them, answers through the same stateless read as a live partition, out-of-range included. A reader is reused for 30 seconds, so a purge elsewhere shows soon. An unassigned range whose fence is not sealed may still take writes and keeps the old answer. The test filer can now keep what is uploaded to it, so flushed windows read back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: list a topic's retired ranges in the partition lookup LookupTopicBrokers takes include_retired and then also answers retired_partitions: each sealed range of an earlier generation the topic no longer assigns that still holds data, with its log start and high-water mark, read from the range's files. A consumer can find what a repartition left behind and fetch it. Unsealed ranges are left out, since they may still take writes. The test filer lists the directories an entry's path implies, as the filer does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: purge retired ranges past retention The retention pass hands each partition with expired files to its leader, but it walked only the topic's current assignments, so a range a repartition retired kept its files forever. The balancer now purges each sealed retired range itself, deleting its expired files under the sealed fence as read. As for a live partition the newest file stays, so the range keeps its high-water mark and a read below the raised log start is out of range. The purging broker drops its cached reader of the range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: the offset scan of a partition's files stops with its caller Retired fetches and listings, the retention pass and a follower take-over now pass their context to the filer scan, so a cancelled lookup or a broker shutting down does not wait on a filer that stops sending entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drain a repartition's old ranges only after saving the new topic.conf A repartition drained the old ranges before saving the topic.conf that replaces them, and a drain now seals them. When that save failed, the ranges topic.conf still assigned were sealed: their leader could not take their fence again, and with every broker healthy nothing moved the epoch on, so the topic took no more writes. The old ranges are now drained after the save, so a failed save leaves them assigned, unsealed and writable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: leave a drained range's fence to a holder still renewing it A drained range its leader had not loaded had its stored fence sealed as found. If a follower had taken that fence over and was still storing the records it acked, the seal replaced its token, so its remaining writes failed the fence check and those records never reached the range. The drain now seals a found fence only once nobody has renewed it for fenceSealWait, the same test a new leader applies; a holder still renewing it seals it itself when done, and the drain waits for that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: seal a range drained while its broker shuts down Once a broker shutdown has started it retires every partition itself, so removing one for a drain reports false, and the drain answered success without sealing the range. It now waits for the shutdown's last flush of the partition and seals the fence like any other drain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: read retired ranges without a log buffer, dropping old readers on access Each retired range's reader was a stopped log buffer, which still allocated the buffers and windows a writer needs, and cached readers past their time were dropped only when another was created. A retired range is now read through ReadFlushedMessagesAtOffset, the stateless disk read with its chunk cache and nothing else, answering out-of-range and end of partition as a live buffer does; the disk read helpers take the read function and cache instead of a buffer. Readers past retiredReaderTTL are dropped on every lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound the retention pass over retired ranges The pass over a topic's retired ranges ran under the broker's own context, so a filer that stopped answering its listing or offset scan held the balancer's retention loop for good. Each topic's pass over its retired ranges now has generationPassTimeout, as handing expired partitions to their leaders does. The test also covers a fetch of a retired range returning with its caller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: a drain seals a stale fence only as it read it A drained range its leader had not loaded is sealed once its fence has gone fenceSealWait without a renewal. The seal required only the fence's token, which a renewal keeps, so a holder that renewed between the drain's read and its seal still had the fence sealed under it, and its remaining writes failed the fence check. The seal now requires the entry as read, as a new leader's take does, and a drain that loses that race looks again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: finish the drains a stopped balancer left behind A repartition saves the new topic.conf and then drains the old ranges. A balancer that stopped in between left them unsealed, and nothing came back to them: repair looks only at topic.conf, and retired reads, listing and retention skip unsealed ranges, so their records were out of reach. The balancer's periodic pass now also looks for range directories that topic.conf no longer names and whose fence is unsealed, and asks the broker holding the fence to drain the range, which flushes what it holds and seals it. A holder that does not answer is drained by the balancer itself, which seals the fence only once nobody has renewed it for fenceSealWait. Each topic's pass is bounded by generationPassTimeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: finish a predecessor's drains on taking the balancer lock The pass that finishes drains a stopped balancer left behind ran only with the retention loop, so after a balancer restart its old ranges could stay unsealed, and unreadable, for up to five minutes. A broker that finds itself the balancer now runs the pass once right away in the background, bounded per topic as the periodic one is, so the wait is down to the fenceSealWait rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: report a drain's error on the test goroutine Two drain tests ran the drain, which fails the test on error, in a goroutine of their own, where failing only ends that goroutine and leaves the test waiting or passing on what it saw. The drain's error now comes back over the channel the test already waits on, and the test fails there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drain a repartition's replaced ranges outside the topic.conf lock A repartition drained the replaced ranges while it still held topicConfLock, under the lock's 30-second deadline, and the drain now waits for each range's last flush and seal. A slow flush held every cache-miss read of topic.conf behind the lock, could run the shared deadline out and leave a range unsealed, and left the new ranges' assignment to a context that had already expired. The new ranges are now assigned under the lock, and the replaced ones drained after it is released, with a deadline of their own sized for a flush and a seal that may wait out fenceSealWait. A range the drain does not get to is finished by the balancer's pass over orphaned ranges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: move a retired read past offsets no stored entry holds A read of a retired range at an offset no stored entry holds, below the high-water mark, answered no records with the same next offset and no end of partition, so a consumer asked for that offset again forever. Such a stretch is a gap in the offsets or entries the log could not place. The read now looks for the lowest stored offset after it and reads from there, and when none is held up to the high-water mark it answers the end of the partition at the high-water mark. Below the log start the read is still out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: serve a client only the partition generation it names A partition is found by its range alone, so a fetch naming an older generation of a range the topic still assigns, not sealed and so not read as retired, was answered from the live partition of the newer generation: the client read records of a generation it never asked for, at offsets that mean something else there. A client that names a generation now gets only that one: one that is not the assigned generation, or not the one loaded, is refused with the partition not found a removed unsealed range gets. A client that names none still matches by range. A publisher refused this way looks the topic up again, as it does when the balancer is ahead of the cached topic.conf, and the unflushed-message query and the flush notification check the generation too. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: decide orphaned ranges under the topic.conf lock from the stored conf The pass that finishes unfinished drains took topic.conf from the cache and listed the stored ranges without the topic.conf lock. A balancer just elected with a stale cache, or a repartition saving its new generation between the read and the listing, made current ranges look orphaned, and they were drained and sealed. The pass now takes topicConfLock, reads topic.conf from the filer, lists the stored ranges and decides under it, then drains what it found once the lock is released; a repartition cannot assign a generation that is already gone, so the decision holds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: drain only the partition generation a drain names A drain found the loaded partition by its boundaries alone. A topic repartitioned 1 -> 2 -> 1 has its first range and its current one on the same boundaries, so finishing the first one's unfinished drain removed and sealed the current range instead. A drain naming a generation now takes a loaded partition only of that generation; otherwise it seals the named generation's stored fence, as for a range its leader has not loaded. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: leave an orphaned range's own drain time when its holder stalls Finishing an orphaned range's drain asks the broker holding its fence first and drains the range itself when that fails. The holder's call had the whole per-topic deadline, so a holder that took the call and never answered used it up, and the drain here then ran on an expired context and did nothing. The holder now gets half the time that is left, keeping the rest for the drain here. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: end an unflushed query a broker would redirect to itself A broker still holding an older generation of a range it now leads under a newer one refuses a query for the newer generation, looks the range up, finds itself as the leader, and redirected the query to itself, which did the same again until the caller gave up. When the lookup names this broker the query now ends with an error saying the generation is assigned here but not loaded; a lookup naming another broker is still followed. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: refuse a loaded generation the topic no longer assigns After a split the old range stays loaded on its broker until the drain unloads and seals it. A fetch naming that generation passed the generation check, since no assignment shares its range any more, and was served from a buffer that is neither assigned nor sealed. A loaded partition is now served by generation only while topic.conf assigns it; the cache is reread once before refusing, so a broker whose cache predates the assignment that loaded the partition still serves it. Once the drain unloads and seals it, the retired reader serves it from its files. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq logstore: retry a parquet reader whose topic.conf read failed The parquet reader reads topic.conf once, when it is built, and a failed read left it a reader that finds nothing, for good. A merged offset read then skipped the compacted offsets to the first log file, and a sealed partition's reader, finding nothing stored, ended the partition at its high water mark. The reader is now set up on its first read and again on each read while topic.conf cannot be read, failing those reads; a topic.conf that does not exist still means no compacted rows. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a drained range from reloading until its seal lands A drain unlisted the range once its last flush landed, before sealing its fence. A publisher whose topic.conf cache still assigned the range to this broker could load it again in between, take the fence at the same epoch, and make the seal fail, leaving the range unsealed after the repartition. The drain now holds the range as retiring until its seal returns, so a loader waits and then finds the fence sealed. A failed seal releases it, unsealed and unassigned, for the orphan pass. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: seal a drained range only once all it accepted is stored A drain sealed the fence after the partition's last flush returned, without asking whether that flush stored anything. A flush abandoned when a broker stop ran out its flush budget drops the window and breaks the follow stream so the follower stores its copy, but the seal could land first, and the follower, finding the fence sealed, gave up records the leader had acknowledged. The drain now seals only when the flushed watermark reaches the last accepted offset; otherwise it leaves the fence to the follower and fails, and a later drain or the orphan pass finds it sealed by the follower or seals it once it is stale. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d915787cf1 |
mq: a topic can name an Iceberg table in a table bucket (#13246)
* mq: add a table option to topic configuration
ConfigureTopicRequest, ConfigureTopicResponse and
GetTopicConfigurationResponse carry a TopicTable: the table bucket ARN,
namespace and name of the Iceberg table that holds the topic's compacted
history. A request without it keeps whatever the topic has; one with an
empty table bucket ARN asks to detach it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq: map a topic's record type to an Iceberg table layout
The topictable package lays out the table a topic's compacted history
goes into. Its columns are _partition, _offset, _ts_ns, _ts (a
timestamptz copy of _ts_ns to partition on) and _key, then the record's
fields, or _value for a schemaless topic. Scalars map to their Iceberg
counterparts, TIMESTAMP to timestamptz, records to structs and repeated
fields or list types to lists, with required-ness taken from the field.
A DECIMAL field has no precision or scale of its own, so it takes the
decimal(38, 18) the topic's parquet files already use.
The spec is identity(_partition) and day(_ts), the sort order _partition
then _offset, and the seaweedfs.mq.topic property names the owning topic.
CheckSchema says whether an existing table can hold a topic's rows,
matching columns by name so the ids a table assigns do not matter.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* iceberg: create and load a table in process
The create handler splits into planCreateTable, which checks the name,
authorizes the create and builds the first metadata, and
registerCreateTable, which stages the metadata file and registers the
table, with stage-create still handled between them in the handler.
Server.CreateTable runs both for a caller inside the cluster, and
Server.LoadTable answers what a load does, sharing the GetTable call and
the metadata parse with the handler. A server-side component that needs
its own table now gets the same location, metadata file, exclusive
staging and cleanup as a REST client, rather than writing metadata by
hand.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: keep a topic's table in topic.conf
ConfigureTopic stores the requested table with the rest of the topic's
configuration, so it survives restarts and moves to another balancer. A
request that does not name a table keeps the stored one, including one
that changes the partition count, and an empty table bucket ARN detaches
it. GetTopicConfiguration returns it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: create or adopt a topic's table on ConfigureTopic
When a configure names a table, or changes the schema of a topic that
has one, the balancer loads the table through the Iceberg catalog the
broker now keeps over its filers. A missing table is created through the
catalog's own create path with the topic's layout and the
seaweedfs.mq.topic property; the table bucket and namespace must already
exist. An existing table is accepted only if that property names this
topic, its location is inside its table bucket, and its columns can hold
the topic's rows, so a topic never takes over a table it did not create
and a schema change the table cannot follow is refused.
The broker creates the table with no caller identity, as trusted
cluster tooling, so the table is owned by its namespace's owner like any
other table there. Deleting a topic only removes /topics and leaves the
table.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: refuse to leave a topic table that holds data
A configure that detaches a topic from its table, or points it at
another one, first loads the current table, and is refused while that
table has any snapshot: its history would be left with no topic to read
or trim it. A table that is still empty, or that its owner has dropped,
can be left, and stays where it is with its property. Detaching a table
that holds data is left to an explicit command.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: pass the table catalog's answers through the filer accessor
The filer accessor treats any error as a failed filer: it records the
failure, asks the next filer and wraps the last error with %v. A catalog
answer such as NoSuchTable then reached ConfigureTopic as an opaque
string, so a missing table was reported instead of created. The catalog
now goes through an adapter that returns the catalog's own answers
unwrapped and leaves failover to real filer failures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: a table hidden by its policy still holds the topic's history
GetTable answers NoSuchTable both for a table that is gone and for one a
policy denies the caller, so a topic whose table carried snapshots under
a policy denying GetTable could detach as if the table had been
dropped. When the catalog says the table is missing, the broker now
looks for its record in the filer with the new s3tables.TableRegistered,
which finds what GetTable finds before policy, and refuses to leave a
table that is registered but unreadable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: fail over the table catalog's internal errors
The adapter between the table catalog and the filer accessor passed
every S3TablesError back as a successful filer call. An InternalError is
what the catalog answers when its own read of the filer fails, so a
broken filer was recorded healthy and no other filer was asked. Only
the catalog's refusals pass through now; an internal error goes back to
the accessor, which marks the filer failed and tries the next one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq: name a table's owning topic by its path under /topics
The seaweedfs.mq.topic property was <namespace>.<topic>, and topic names
may hold dots, so a.b/c and a/b.c wrote the same value and either could
adopt the other's table. The value is now <namespace>/<topic>, the
topic's directory under /topics: two topics that write the same value
already share one topic.conf, so they are the same topic.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq: reserve the day partition field's name in a topic's table layout
The spec partitions by day(_ts) under the name _ts_day, and Iceberg only
lets a partition field share a column's name when it is that column's
identity. A topic with its own _ts_day field mapped fine and then failed
the table create with an invalid partition spec. Schema now refuses the
name up front, with the system columns, saying it is reserved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: let the table catalog fail over to every discovered filer
The broker's filer accessor lists only the current filer, so the
failover the catalog adapter relies on had nowhere to go: an internal
error from the current filer failed the catalog call even with another
healthy filer discovered. The catalog now gets an accessor of its own
over every filer the broker has discovered, the current one first, read
under the lock that guards them. The broker's shared accessor stays on
the current filer, so topic.conf, offsets and the subscriber coordinator
keep reading one filer as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: a topic leaves a table that no longer names it
A table dropped and replaced under the same name by one that does not
carry the topic's property holds none of the topic's history, so its
snapshots no longer keep the topic from detaching, switching tables, or
following a schema change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* s3tables: keep tableMetadata's doc comment on tableMetadata
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: walk the table catalog's filers in order, current first
FilerClientAccessor shuffles the filers it is given, so the catalog's
create, load and registration calls each went to a random discovered
filer even while the current one answered. A filer with its own store
may not yet hold what another just wrote. Try the current filer first
and move on to the others only when it fails, as the S3 gateway does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Revert "mq broker: a topic leaves a table that no longer names it"
The property alone does not show the table was replaced: a
set-properties commit on the same table changes it and keeps the
snapshots, and the topic would then leave its history behind. Telling a
replacement apart needs the table's identity stored with the topic.
This reverts commit
|
||
|
|
52afabbf1b |
mq: avoid a deadlock when retiring a partition with a full flush queue (#13225)
* mq: let partition retirement drain a full flush queue outside broker locks * log_buffer: queue the final flush from ShutdownLogBuffer itself Every ShutdownLogBuffer caller already waits afterwards with WaitForShutdown or IsAllFlushed, so queueing the final flush in the background changes no caller's outcome and lets every caller holding a lock a flush callback needs avoid the full-queue deadlock, without a second shutdown entry point. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6a6208e42f |
mq: a leader-only partition gains a follower, and cold partitions are purged (#13232)
* mq balancer: start a new generation when a partition's follower changes EnsureAssignmentsToActiveBrokers gave a leader-only partition a follower once a second broker was live, and replaced a lost follower, but kept the epoch. A leader starts replicating only when it takes the fence, so a loaded leader never saw the new follower: its copy at the same epoch was never retired, and the partition stayed unreplicated, acking from memory, until something reloaded it. Any change of the pair now bumps the epoch, so the leader retires its copy after the last flush and reloads under the new generation with a replicator to the new follower. Re-spelling the same broker's address still keeps the epoch, so an unchanged pair is not churned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: hand a repaired assignment's new generation to its leader When the balancer repaired a topic's assignments it only saved topic.conf. A leader learned of a new generation only when a new publish or subscribe stream asked for the partition after its own cached topic.conf expired, so a loaded partition kept serving the old generation, without the follower it had just been given, for as long as its clients stayed connected. Once the repair is saved, the balancer now sends every assignment whose epoch moved to its leader, which retires the old copy after its last flush and reloads under the new fence, replicating to the new follower. The handoff runs outside topicConfLock, since the leader may wait for that flush. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: repair every topic's assignments once a broker joins The balancer repaired a topic's assignments only when a lookup missed its cached topic.conf. A partition placed while its leader was the only broker kept no follower after a second broker joined for as long as its clients stayed connected and never looked it up again. The balancer now counts brokers joining it and, once settled, repairs every stored topic after a join, handing any new generation to its leader. A sweep that fails is retried on the next tick; one that finds nothing to change saves nothing, so a reconnect does not churn partitions. A repair that saves topic.conf also drops the balancer's cached copy, which lookups would otherwise keep answering with the old pair. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: purge a partition past retention when its leader loads it Files past a topic's retention were deleted only by the periodic purge, which visits partitions that are loaded when it runs. A partition loaded for a short read or write and unloaded once idle could miss every pass, keeping its expired files. A leader now purges a partition as soon as it has loaded it, under the fence it has just taken and after seeding its offsets, so every load deletes what has expired. The purge runs once the partition is registered, outside the broker's access lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: load partitions whose files are past retention A partition that nothing publishes to or reads from is never loaded, so neither the periodic purge nor a purge on load ever reached it, and a cold topic kept its expired files indefinitely. Every purge interval the balancer now lists each topic with retention, works out per partition what a purge would delete, and hands only the partitions with something to delete to their leaders. The leader's load purges them under the fence it takes, so deletes stay fenced. A partition with nothing to delete, such as one holding only its newest file, is not loaded, so cold partitions are not churned. The planning half of purgeExpiredLogFiles moves into expiredLogFiles, which the purge and the balancer share. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: resend a new generation until its leader takes it After a repair saved a new generation, the balancer told the leader once and only logged a failure. The repair loop still counted the join as done, and later sweeps found nothing to change, so a leader whose publish stream kept its old partition went on acking without the follower it had been given. Saved generations are now kept as pending, one per partition with a newer one replacing an older, and the repair loop hands each due one to its leader, backing off after each refusal, until the leader takes it or topic.conf has moved past it. A join counts as repaired only once nothing is pending. Sending runs in the repair loop, off topicConfLock, which a save now wakes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: hand pending generations to leaders in parallel under one deadline The repair loop handed pending generations over one at a time, each with its own 30 second timeout, so a broker that stopped answering held the loop for that long per partition it led: with a hundred of them, healthy leaders and later joins waited most of an hour. A pass now reads each topic.conf once, groups the generations still current by leader and topic into one request each, and sends up to eight leaders at once under a single deadline for the whole pass. A leader that does not answer delays only its own generations, which keep their backoff, and the pass returns once the deadline passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: key a pending generation by the partition's full identity Pending generations were keyed by topic and range alone. A topic repartitioned away from a range and back gets a new partition for that range, with a new creation time and epochs starting over, so a pending generation of the old partition at a higher epoch made the new one look older and it was never queued. The key now includes the ring size and creation time, so epochs are compared only within one partition; the old entry is dropped as superseded when it next comes due. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: hand over generations a previous balancer left undelivered Pending generations live only in the balancer's memory. A balancer that saved a new generation and stopped before its leader took it lost it: the next balancer's sweep found topic.conf already repaired, recorded the join as done, and a leader whose clients kept its old copy served that generation without its new follower indefinitely. Once settled under a new lease, the balancer now queues the current generation of every partition a leader reports loaded and hands them over through the same batched delivery, so joins are not done until those are taken too. A leader already on that generation keeps its copy, as an assignment at the epoch it holds is a no-op, and an unloaded partition is skipped since it reads topic.conf when it loads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer_client: track a filer's backoff atomically Every call through one FilerClientAccessor records the filer's health, and those calls run concurrently, but the backoff deadline was a plain time.Time read and written without synchronization. The broker now reads topic.conf from background purges and repairs while serving requests through the same accessor, which the race detector caught. The deadline is now an atomic Unix-nanosecond value, and the failure time it was stored beside, which nothing read, is dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: keep generations pending when the pass ends before sending them A batch still waiting for a sender when the pass deadline passed took the cancellation branch with its error still nil, so its generations were dropped as delivered although nothing was sent, and their leaders kept serving the old generation. Such a batch now fails with the pass's deadline and keeps its backoff, like a batch whose send timed out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: give each leader one sender, not each of its topics The limit on concurrent sends applied to per-topic batches, so a stalled leader with as many due topics as there are senders took every slot and a healthy leader waited out the pass deadline. A pass now groups due generations by leader; each leader takes one sender and sends its topics in turn, so a stalled leader holds only its own slot, and its topics not reached before the deadline stay pending. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer_client: keep backing off a filer that has failed many times The backoff doubled with a shift of the failure count, which wraps once a filer has failed 64 times in a row, so its backoff dropped to nothing and it was retried on every call. The doubling now stops at 16 seconds and the backoff stays at 30 seconds after that. * mq balancer: requeue each broker's held generations once its stats arrive A new balancer requeued the generations of loaded partitions once per lease, from whatever stats it had at that moment. A leader that had connected but not yet sent its first stats looked as if it held nothing, and since the scan never ran again under that lease, a generation an earlier balancer saved but never handed over stayed undelivered. The balancer now records which brokers have reported and, on each pass, scans the brokers whose first stats arrived since the last scan under the current lease, queuing their held partitions' current generations for the same batched delivery. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: scan each broker connection, judged by the stats it reported The handoff scan took the reported brokers' addresses, then looked each one's stats up again while matching partitions, and marked the address scanned. A broker that disconnected in between was looked up as holding nothing yet still marked scanned, so when it reconnected under the same lease it was never scanned again and a generation it never took stayed undelivered. The scan now judges each broker by the stats it was listed with and records connections, not addresses, as scanned; a reconnect brings new stats and is scanned again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: register each broker connection separately AddBroker reused the stats already registered under a broker's address, and a stream's cleanup removed whatever was registered under it. A broker that reconnected before its old stream ended shared that stream's stats, and the old stream's cleanup then dropped it from the live set while the new stream kept reporting, so the balancer treated a live broker as gone, and the handoff scan, which already counted that stats object as scanned, skipped the reconnect. Each connection now registers fresh stats, and its cleanup removes the broker only while those are still the registered ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: record an assignment only on a connected broker's stats After handing a partition to its leader, the balancer recorded the assignment on the leader's stats and, when the leader had none, created and registered stats for it. A leader not connected to the balancer, as one still reconnecting or one that only answered the assignment, was thereby added to the live set without a connection whose cleanup would ever remove it, and assignments could then pick a broker the balancer could not see. The assignment is now recorded only when the leader's connection has registered it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: sweep topics from a listing that reports its failures The repair sweep, the handoff scan and the retention scan took their topics from ListTopics, which serves what it can: a failed namespace listing, a failed topic listing or a failed topic.conf lookup is only logged. A sweep could therefore see some topics, or none, and still succeed, recording a join as repaired with topics never looked at. ListTopics' filer scan is now listStoredTopics, which lists all it can and reports every failure. The repair sweep and the handoff scan fail on it, so the join stays pending until a sweep lists every topic, while an empty listing that succeeded is still complete. The retention scan purges what was listed and logs the rest. ListTopics keeps serving partial results to its gRPC callers and only logs the failure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: list every namespace and topic, not the first thousand The topic listing asked the filer for at most 1000 namespaces and at most 1000 topics per namespace and never asked again, so anything past the first thousand was missing from ListTopics, never repaired after a broker joined, never handed over by a new balancer, and never purged past retention. Both listings now ask for everything, which the filer pages through itself, as the partition offset scan already does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq balancer: forget the scan record of a broker connection that ended The handoff scan remembered every broker connection it had scanned until the balancer lease changed. Each reconnect is a new connection, so a long-running balancer kept one record, holding that connection's stats, for every reconnect of every broker. Each pass now drops the records of connections no longer reported; a broker that reconnects brings new stats and is scanned again either way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: give the stored-topic listing a deadline The shared topic listing ran under the broker's long-lived context, so a filer that accepted a listing and stopped answering held the repair loop and the retention sweep indefinitely; ListTopics used to give its scan two seconds. Each listing now gives up after 30 seconds and returns the error, so the scan is retried on a later pass. * mq balancer: give a retention hand-over a deadline A leader that took the hand-over of a partition past retention and never answered held the balancer's retention loop on it, so later topics and the next tick never ran. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
42a39099e0 |
mq broker: keep one request id across filers for a topic.conf save (#13237)
A save that applied but lost its answer was retried on the next filer under a new request id, refused as changed by its own write, and redone from the saved topic.conf: a balance move then found the target already leading and failed after saving. The same id lets the owner replay the recorded outcome. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3363f4a318 |
mq: disk and parquet reads stop when asked, resume inside earlier files, and order new stamps after stored ones (#13230)
* mq logstore: stop a disk read when the callback is done GenLogOnDiskReadFunc ignored the isDone the per-entry callback returned, so it kept fetching and delivering every later entry, chunk and file, and the merged read then went on into the parquet files. The chunked offset read and the query scanner's close path both return true and expect the read to stop. The reader now stops at that entry, skips the remaining chunks and files, and returns done with a position just past the entry: the next offset for an offset read, its time for a timestamp read. The merged read returns there instead of reading parquet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: stop a parquet read when the callback is done The parquet reader also ignored the callback's isDone and delivered every remaining row of every compacted file, and the merged read cleared any done it reported. It now stops at that row and skips the remaining files, which it lists before reading instead of reading inside the listing. Its done now means only that the callback asked to stop, so the merged read passes it on; the no-op readers and a file starting at or after stopTsNs no longer report done, which the merged read used to clear anyway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read parquet files named before a timestamp resume A parquet file is named after its first source log, and that log can start seconds before rows the file holds, so listing parquet files from the resume second skipped a file named earlier that still held later rows. The reader now keeps the same sparse logFileIndex the log reader uses and lists from the last mark before which every file ends before the resume time, deciding each file by its ts_max. Rows are not in time order once windows flushed across a reload are compacted together, so stopping at the first row past stopTsNs dropped later rows still inside it. Each row is now kept or skipped on its own, and the returned position is the latest row delivered rather than the last row looked at. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * query: take MIN and MAX of _ts from the files' recorded time range MIN and MAX of _ts without column statistics were computed from file names, which are only the start second of a file's first source log: MIN rounded down to that second and MAX was the start of the latest file rather than its last row. Each file's stats already carry ts_min and ts_max as MinTimestampNs and MaxTimestampNs, so those are used when set, and names only for files that record no range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: stamp a loaded partition's messages after the newest stored one Within one LogBuffer timestamps only increase, but a new buffer starts LastTsNs at 0, so a leader whose clock is behind the previous leader's stamped new messages earlier than what was already stored, and a subscriber resuming by timestamp from the last stored message dropped them. OffsetRange now also records the newest ts_max of the partition's log and parquet files, and loading a partition seeds LastTsNs with it, so the buffer bumps new messages past it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read parquet rows at the stop time The log reader treats stopTsNs as inclusive, delivering an entry at it and reading a file whose first entry is at it, but the parquet reader stopped at a row equal to it and skipped a file starting at it, so the same bounded read returned that message from a log file and dropped it once compacted. Both checks are now inclusive. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: drop a debug print from the disk read A disk read bounded by stopTsNs printed the stop time and the first entry past it to stdout on every such read. It was a leftover debug line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: start an offset read of parquet files at the offset An offset read of the parquet files delivered every row from the first one on, and the stateless fetch fills a disk chunk with a callback that stops after a chunk's worth of entries outside it. Now that the reader honors that stop, a fetch at 1000 from a partition stored only in parquet stopped after rows 0-999 and returned nothing. An offset read now skips files whose recorded range ends below the offset or that record none, reads the rest in offset order, and skips rows below the offset before they reach the callback. It returns the offset after the last row delivered, not a timestamp position. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read parquet files first in a merged offset read The merged read took the live log files first and, now that it honors the callback's done, returned without reading parquet when the callback stopped. The stateless fetch stops after a chunk's worth of entries outside the chunk it fills, so with offsets 0-999 only in parquet and 1000-1999 in log files, a fetch at 0 stopped on the log files' entries and never reached parquet. Compaction turns the oldest windows into parquet, so an offset read now takes the parquet files first and the log files after: the lower offsets arrive first, and since each source skips what lies below its start, a bounded caller only stops on entries past what it wants. Compaction leaves a parquet file's source logs in place until retention removes them, so the log files are read from the offset after the last one parquet delivered, and each offset is delivered once. Timestamp reads keep their order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: serve merged offset reads from log files where they exist A merged offset read took parquet first and the log files from the offset after the last row parquet delivered. Compaction keeps a parquet file's source logs until retention removes them and drops messages with no key or no data, so that skipped those messages although their logs were still there, and delivered compacted rows in place of the messages as written. The log reader now lists its files before reading them, and an offset read finds the lowest offset the listed log files record. Parquet serves only the offsets from the requested one up to that, and the log files everything from there, so each offset is read once and from a log file whenever one holds it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read schemaless parquet rows back as their published bytes Compaction stores a schemaless message's bytes in the _value column, but the parquet reader handed out the whole row marshaled as a RecordValue, with _key, _ts_ns and _offset wrapped around it, so a consumer reading compacted offsets got different bytes than it would from the log files, and the query engine showed that wrapping as the value. A schemaless topic's rows now carry the _value bytes as Data; schematized topics keep the marshaled row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: fail a read that needs parquet when its reader cannot be set up A topic whose schema cannot be laid out as parquet left the parquet reader nil, and a merged read that reached parquet called it and panicked. Such a read now returns the setup error; skipping the parquet rows silently would hide stored messages. * mq logstore: a stopped log read returns the last delivered time A later-named log file can hold earlier messages, so the latest time a stopped read delivered can be past one it never reached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: compact a group's rows in offset order Source logs list by name, which sorts out of offset order under clock skew, so a compacted file could hold offsets 2,3,0,1. An offset read delivers a file's rows as stored and then reports a next offset past ones it never delivered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: floor a reload's stamps by the newest legacy log file name Log files record ts_max only since this release, so after an upgrade a reload saw no newest time and seeded the stamps at zero. A log file that records no times is named by its first message, so its second still bounds the newest stored time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
25b9278d60 |
mq: conditional topic.conf saves, bounded topic.conf I/O, and mq.balance moves that save their assignment (#13231)
* mq broker: give up topic.conf filer calls with the caller's context The topic.conf read and save helpers took no context, so a filer that took the call and never answered kept the balancer inside topicConfLock for good, and every ConfigureTopic, lookup repair and EndPartitionGeneration queued behind it on a plain mutex. reportGenerationEnded's per-attempt deadline could not bound any of it. The helpers now take a context, the RPC paths pass their request context, and topicConfLock is a one-slot semaphore whose wait ends with the caller's context. Calls made while holding it are also bounded by topicConfTimeout, so a caller without a deadline cannot hold it forever. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: save topic.conf only if it is still what was read Every topic.conf update is a read-modify-write on the balancer, but the save was unconditional, so a balancer whose lease ran out between its read and its save wrote its stale assignments over a successor's newer epoch. topicConfLock only orders writers within one broker. A failed read in ConfigureTopic could also recreate an existing topic from scratch. The read now returns the topic.conf entry, and the save is an ObjectTransaction requiring that entry unchanged, or the file still absent for a new topic. A refused save is redone from a fresh read a few times, so a report for an epoch a successor already ended finds it moved on, and then gives up with Unavailable for the caller to retry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: save mq.balance moves to topic.conf before assigning them A balance move only told the target to load the partition and the source to drain it. It never touched topic.conf, so lookups kept sending publishers to the source, and since partitions are fenced by epoch the target was asked to lead at epoch 0 and refused before anything moved. The balancer now runs the move itself: it saves the target as leader at the next epoch through the conditional topic.conf save, tells the source about the new epoch so it retires its copy, flushing what it holds under its own fence and sealing it, and then assigns the target, which takes the fence at the new epoch. A follower that becomes the leader swaps places with the old leader. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a retiring leader's fence renewed until it seals A leader told of a newer epoch, as a balance move's source is, retires its copy by shutting it down and waiting for its last flush before sealing the fence, but it did not renew the fence meanwhile. A flush outlasting fenceSealWait left an aged unsealed fence the new leader could take, and the pending flush then failed its fence check and dropped acknowledged messages. The fence is now renewed for as long as the flush takes. Loaders retiring the same copy at once share one renewal, which the first to return stops before any seal, so no renewal lands on a sealed fence. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: save a configure's assignment repair with its update ConfigureTopic saved the repair of assignments on dead brokers on its own, then saved the requested schema or retention change against the entry it had read before that repair. The second save was always refused, so the update went round a full reread, and a resize first drained brokers for nothing. The repair is now applied in memory and saved together with the requested change in one conditional save. A resize replaces the assignments anyway, so it no longer saves a repair first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: report a balance move the target refused assignTopicPartitionsToBrokers logged each broker that refused its assignment and returned nil, so mq.balance reported success for a move whose target never took the partition, after topic.conf had already moved and the source had retired its copy. It now returns the refusals, and BalanceTopics passes them to its caller. The saved move stands: a retry assigns the target again, and the target also loads the partition on first use. ConfigureTopic keeps logging a refused assignment of a topic it has saved, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: give up a topic.conf cache miss with the caller's context getTopicConfFromCache waited for topicConfLock and read the filer under context.Background(), so a lookup whose caller had already given up stayed queued behind whatever held the lock and then did up to topicConfTimeout of filer work for nobody. It now takes the caller's context, which LookupTopicBrokers and the retention purge pass along and the partition loaders pass as Background; cache hits are unchanged. A waiter whose context has already ended no longer takes a free lock either, since a select with both cases ready picks one at random. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: require exactly one moved partition in the balance tests The move tests took the last partition led by the target as the moved one, so a move that handed both partitions to the target would pass. They now fail unless exactly one partition moved. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3809cfe4cf |
mq: fetched messages carry their log offset (#13229)
* mq: carry the log offset on fetched messages FetchMessage answers with DataMessages that have no offset, so a client can only number them by position from its start offset. That is wrong as soon as the stored range has a hole or an entry the log cannot place. DataMessage gains an optional offset; presence tells a broker that sets it apart from one that predates it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: send each fetched message's log offset FetchMessage dropped the offset of every log entry it read, leaving clients to number the messages by position. Each DataMessage now carries its LogEntry offset, including -1 for an entry the log could not place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: number fetched records by the broker's offsets The gateway numbered the records of a fetch as start offset plus position, and moved the next fetch past them by count. A hole in the stored range, such as offsets 10, 11 and 13, put record 13 at 12 and fetched it again at 13. Records now take the offset the broker sends, the batch offset deltas and the next offset follow those offsets, and an entry the broker reports at -1 is left out rather than given a guessed offset. A broker that sends no offsets is still numbered from the start offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3beca7d956 |
mq: resume inside the file holding the resume point, and start offset reads near the offset (#13209)
* mq logstore: resume a timestamp read inside the file that holds the resume point A disk read by timestamp listed the partition from the file named after the resume second and dropped every earlier name, so the file that started before that second but still held messages after the resume point was skipped and its remaining messages were never delivered. The reader now keeps a sparse index of the partition's log file names, starts listing at the last mark before the resume second, and reads the last file starting before that second along with every later one; its entries up to the resume point are already filtered by timestamp. This covers names with and without the offset suffix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read a log file's offset range in one place The disk reader decoded offset_min and offset_max inline in three places, by string literal rather than the mq constants. A single logFileOffsets helper now reads both, so the reader and the offset index added next agree on what a file records. No behavior change: the flush writes both attributes together. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: start an offset read at the indexed file holding the offset A disk read by offset listed the whole partition directory on every call and filtered the files by their offset ranges, so a lagging consumer paid for the partition's entire history on each read. The reader's sparse index of log file names now also keeps each mark's first offset, and an offset read lists from the last mark starting at or before its offset; offsets grow with names, so no earlier file can hold it. The index is extended by every listing past the last name it has seen, so after the first read a call lists at most one stride of files before its own plus the files after it. When no mark with an offset range is at or before the offset, as with files that record none, the read still lists from the first file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: never name a log file before the newest one in its partition A log file is named by its window's start second, taken from the writing broker's clock. A new leader whose clock is behind the previous one's wrote windows whose names sorted before older files holding lower offsets, so names no longer followed offsets. An offset read listing from an indexed file then skipped the new windows, and a read starting below such a file passed over it without notice; no reader-side check can see a file that sorts before where it starts listing. The partition fence now carries the newest log file time: the leader seeds it from the listing it already pages to continue the partition's offsets, which now also reports the newest log file name, legacy names included and compacted files, the fence and directories excluded. Each flush names its window no earlier than that time and advances it. Files sharing a second still sort by their min offset suffix. Timestamp reads resuming past the old leader's names now list such windows too, though entries timestamped before the resume point are still filtered out by timestamp. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound a log file by its first message time, not its name Now that a window can be named after a later second than its messages to keep names in offset order, the disk reader's stop filter, which dropped every file whose name second was after the stop time, missed windows whose messages were inside a time-bounded read. A flush now records the window's first message timestamp on the log file as ts_min, the attribute parquet files already carry, and the stop filter compares that when present. Files without it were written before names could be moved later, so their name still bounds them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read every offset candidate, not a binary-searched suffix An offset read binary-searched its candidate files by offset range and dropped those before the hit, assuming name order matched offset order. A directory written under clock skew holds a file that sorts before files with lower offsets, and the search skipped it even on a full listing. The listing already drops files whose range ends before the offset, so in an ordered directory the search removed nothing but offset-less legacy files, which are filtered per entry anyway. The search is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: list from the start once a partition's names leave offset order An offset read lists from the indexed file starting at or before its offset, which is right only while names sort in offset order. Directories written under clock skew before log file names were kept ordered hold files sorting before files with lower offsets, and a read listing from a later mark passed over them. The index now remembers the highest offset it has seen in name order, and once a file starts below it the partition is unordered and every offset read lists from the first file, as before the index existed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: name a takeover's file no earlier than the newest one stored A follower taking over named its file by its first entry's time, so a follower whose clock is behind its lost leader's wrote a name sorting before files holding lower offsets. It now takes the newest stored name from the listing it already reads for the high-water mark and names its file no earlier, as a leader's flush does. * mq: resume a timestamp read in every earlier file holding later messages A timestamp read kept only the last file sorting before the resume second, assuming names bound message times. A window named no earlier than the newest stored file can sort after a file it does not follow in time: a slow leader's window of older messages took that last place and the file before it, still holding messages after the resume point, was never read. A flush, and a follower's takeover write, now also record the window's last message time as ts_max, the attribute parquet files carry. Of the files sorting before the resume second, every one whose last message is at or after the resume time is read; files without it were named by their first message and keep the old rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: return the latest time a timestamp read delivered A timestamp read returned the last processed file's last message time as its position, and each chunk's result replaced the file's. Files are read in name order, and a slow leader's window can sort after a file holding later messages, so the position went back and the next read delivered those later messages again; a trailing chunk that delivered nothing also reset a file's time to zero. The position is now the highest time delivered across chunks and files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: deliver an offset read's files in offset order An offset read processed its candidate files in name order. In a partition written under clock skew a file sorts before files with lower offsets, so its entries were delivered first, and a reader taking only the first few entries, as the chunked offset read does, got the wrong ones. The files that record an offset range are now read in order of their first offset, each in a place one of them held, so files without a range keep their position. In an ordered partition this changes nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: list a timestamp resume from the start once a name was clamped A timestamp resume listed from the index's last mark before the resume second. Once a window is named later than its first message to keep names in offset order, many such windows can share one clamped second, and the marks among them sorted after an earlier file still holding messages past the resume point, so that file was never listed and never reached the check of its last message time. The index now notes a file whose name is later than its first message, and from then on a timestamp resume lists from the first file. Partitions without such a name keep using the index. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: start a timestamp resume at a mark bounded by message times A timestamp resume listed from the index's last mark sorting before the resume second, falling back to the first file once a clamped name was seen. That still assumed names bound earlier files' messages: windows whose messages overlap within one second, none of them clamped, could push a mark past an earlier file holding messages after the resume point, and the resume skipped it. Each mark now records the latest message time of every file sorting before it, from ts_max, or for a file without it the end of the next file's start second, since such files were named by their first message and ended before the next began. A resume starts at the last mark whose earlier files all end before the resume time, so the files it skips hold nothing it still has to deliver, whatever the names or clocks. The clamped-name flag is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: leave an older file unbounded when the next name was clamped A file without a recorded last message time was bounded by the end of the next file's start second, on the reasoning that it ended before the next began. When the next file is a slower leader's window clamped into that second, its name says nothing about when its messages, or the older file's, end; the older file was bounded too early, a later mark qualified, and a resume past it skipped its remaining messages. The next file now bounds it only when its name is not later than its first message; otherwise the older file stays unbounded, no mark after it qualifies, and a resume lists from before it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: fetch by offset through the log buffer over out-of-order names The out-of-order name tests drove the disk reader directly. A fetch goes through the log buffer's disk chunk on top of it, so this reads a few offsets at a time through ReadMessagesAtOffset over a partition whose names sort out of offset order, and checks each fetch returns its own offsets. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
746cae3895 |
mq: enforce topic retention (#13210)
* log_buffer: find a fetched offset in a disk chunk by its offset A stateless read caches disk reads in chunks aligned to 1000 offsets and picked the requested message by its distance from the aligned start. A chunk read from disk begins at the first offset stored at or above that start, so once the partition's oldest files are gone the chunk begins later and the read returned messages from further on, under the requested offsets. The message is now found by its offset, and the next offset follows the last message returned. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: start a loaded partition's log at its earliest stored offset A loaded partition reported its earliest offset as 0 and its log start as the start of its memory, so neither said where the stored data begins. The log buffer now keeps the earliest offset still stored: a leader seeds it from the offset ranges on its files when it loads, it only moves up, and the partition's offset info and log start report it. A stateless read below it fails with ErrOffsetOutOfRange instead of being answered from a later file under the requested offsets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: purge a partition's files past its topic's retention A topic's retention was stored but never applied, so a topic that is not re-partitioned kept every flushed file. Every five minutes the broker now purges each partition it leads whose topic has retention enabled. It deletes the oldest run of files whose newest message is older than the retention, stopping at the first file still retained so the stored offsets stay contiguous, and always keeps the file with the highest offset, which a later load continues offsets from. A log file is judged by when it was flushed and a parquet file by its newest row; a parquet file is deleted together with its source log files. The partition's log start is raised before the deletes, and each delete is a transaction conditioned on the partition's fence token, so a leader that lost its fence deletes nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: map an unknown broker error to UNKNOWN_SERVER_ERROR (-1) The gateway's error table gave UNKNOWN_SERVER_ERROR the code 1, which Kafka uses for OFFSET_OUT_OF_RANGE, and the broker's table carried the same value for its unknown and publisher-not-found errors. Today the mapped code only reaches error text, but a fetch path that answers OFFSET_OUT_OF_RANGE by its Kafka code would make every unknown broker failure reset a consumer. The code is now -1. The gateway only tests these codes against 0 and against specific codes, and the cached assignment is still dropped on the broker's own code 1, so nothing treated 1 as success or depended on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: answer a fetch below retention with OFFSET_OUT_OF_RANGE A read below the earliest retained offset failed like any other read, so FetchMessage reported a storage error and the gateway answered KAFKA_STORAGE_ERROR, which a consumer retries at the same offset forever once retention has purged it. FetchMessage now answers ErrOffsetOutOfRange with its own broker code, the earliest retained offset as LogStartOffset, and the requested offset as NextOffset. The gateway carries it as ErrOffsetOutOfRange and answers the partition with OFFSET_OUT_OF_RANGE, so the consumer applies auto.offset.reset; a reset to earliest asks ListOffsets, which reports the retained start through the leader's range info. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: keep a disk chunk's entries in offset order A disk read filled its 1000-offset chunk with the first 1000 entries in the order the files listed, and the lookup searches the chunk by offset. Files whose names sort out of offset order deliver entries out of order, so the chunk held the wrong offsets and was cached that way. It now keeps only the chunk's offsets, wherever they come, and sorts them before caching. * mq broker: purge a partition's files in offset order The purge walked a partition's files in name order and stopped at the first one still retained. Names sort by the start of a window, which can be earlier than older files' after a reload, so a file holding higher offsets could be purged ahead of a retained one below it, leaving a hole. The walk now goes by each file's first offset, taking a parquet file that records none from its first source, and by name among equals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: round a log file's flush time up to bound its messages A log file without a recorded newest timestamp is judged by its Mtime, which the filer keeps in whole seconds, so a file flushed later in the cutoff's second looked older than messages it may hold. The purge now takes the end of that second as the bound. A recorded newest timestamp is still used as is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: keep one entry per offset in a disk chunk A disk read goes through a partition's log files and then its parquet files, and a parquet file holds the same offsets as the log files it was compacted from, so a chunk could take an offset twice and a fetch returned the duplicate as the next message. The chunk now keeps the first entry for each offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * log_buffer: reread a cached disk chunk that lacks the fetched offset A disk chunk can be cached while its later offsets are still in memory. Once those are flushed and memory moves on, a fetch past the cached part hit the cache, found nothing, and returned no messages until the chunk was evicted. A cached chunk that does not hold the fetched offset is now dropped and read from disk again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: record a parquet file's offset range from its sources The compactor took a parquet file's offset range from its entries' offsets above 0 and recorded it only when the lowest was above 0, so a file compacted from a partition's first window recorded no range, and one whose entries started at 0 would have claimed to start at 1. The range now comes from the source log files' recorded ranges, including one that starts at offset 0, and is left out unless every source records one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: keep the earliest offset at or below files that record no range The earliest stored offset was the lowest offset any file records, so a file that records none, such as a parquet file compacted from a partition's first window or a log file flushed without a range, was left out. A reload or a purge could then start the log above offsets a read can still return, and ListOffsets for the earliest offset left them out. OffsetRange now takes the whole entry and keeps the earliest offset at 0 while a log or parquet file records no range, except a parquet file whose listed sources are all present, as their ranges cover it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a partition whose files cannot all be placed by offset The purge ordered a data file that records no offsets, and whose sources give none, as if it held the lowest, so an expired one could be deleted while a retained file below its offsets stayed, leaving a hole. A partition holding such a file is now left alone; only files written before offsets were recorded lack them. * mq broker: purge a parquet file only when each of its sources has expired The purge deleted every source of an expired parquet file along with it, judging the whole group by the parquet file's newest timestamp. Message timestamps are not ordered across reloads, so a parquet file can hold an expired source next to one still retained, and the retained one went early. A parquet group is now purged only when the parquet file and each source in it are past the cutoff on their own; otherwise the walk stops there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: record a parquet file's lowest and highest timestamps The compactor recorded a parquet file's timestamp range from its first and last rows. Message timestamps are not ordered across reloads, so the last row need not be the newest, and the recorded ts_max could sit below messages the file holds, making it look older to the retention purge and to readers that skip files by time. It now records the lowest and highest timestamps over all rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: keep each compacted row's offset in the _offset column The compaction schema had no _offset column, so a schematized row's offset was dropped and a schemaless row never carried one, while the parquet reader expects the column and a fetch places rows by offset. The compactor now adds the column when the schema lacks it and fills it for every row, schemaless ones included, when the source files record their offsets; otherwise it is left null. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: read a parquet file by its own columns and mark unknown offsets The parquet reader always expected an _offset column and read rows by column position, so a file compacted before the column existed was read out of alignment and panicked with an index out of range. A row with no real offset also read back as offset 0, so a disk chunk, which keeps one entry per offset, collapsed such rows into one. The reader now uses the _offset column only when the file has it, trusts it only when the file records its offset range, and reports any other row with offset -1, which keeps it out of reads by offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a purge group that reaches past the first retained offset A parquet file is purged with its sources as one group, and the sources need not be contiguous: an expired parquet file could list expired files on both sides of a retained one, so purging the group left a hole above the retained file. A group now goes only when every offset it and its sources cover lies below the first offset left behind; the walk keeps the first group that does not, and the ones after it. A log file whose offsets a retained parquet file also starts at now stays until that parquet file goes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: give compaction test fixtures file ids no other fixture uses The parquet reader caches chunks in a package-wide cache keyed by file id, and each compaction fixture numbered its file ids from 1, so one fixture could read another's cached bytes; with -count=3 a test read a parquet file from an earlier run and failed. File ids are now numbered across all fixtures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/logstore: compact legacy log files apart from ones that record offsets A compaction group could hold a legacy log file without an offset range next to files that record one, and a parquet file keeps its rows' offsets only when every source records them, so the ranged rows lost their offsets and could no longer be fetched by offset. Groups now split where a file's having an offset range differs from the group's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: treat a parquet file's end as unknown when a source is gone A parquet file that records no offset range took its last offset from the sources still present, so one whose later source was already gone looked as if it ended below a retained file and was purged, though it may hold that source's offsets above the retained one. A gone or unranged source now leaves the end unknown, and the group stays. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d63c225d78 |
mq: replicate each partition to a follower and hand it to a new pair when one is lost (#13203)
* mq: carry offsets, epoch and heartbeats on the follow stream The follow stream sent the publisher's raw message, so the follower could not keep the leader's offsets, and nothing named the generation or told a quiet leader from a dead one. The stream now carries log entries with their offsets, the epoch and leader in its init, heartbeats, and the flushed offset; acks report the follower's offset. EndPartitionGeneration lets a broker of a broken pair report it to the balancer. * mq broker: hand a partition's fence between generations A fence could only be taken by the next leader, at once. A pair that breaks needs more: the survivor must keep persisting what it holds before a new leader writes, and a follower must be able to take the fence from a leader it lost. The holder can now renew the fence, which tells a new leader it is still persisting, and seal it when it is done; a new leader takes an earlier generation's fence once it is sealed or left unrenewed for 30 seconds. Within one generation the fence moves only from the leader to its follower, and a sealed one stays sealed. Sealing writes a new token, so a follower that read the fence before the seal cannot take it over after; a plain renewal keeps the token, so flushes under way still match. A stale leader that reloads seals its old fence once its last flush lands, so the reload does not wait. * mq broker: ack a publish once the follower holds it The leader acked a publish as soon as it was in its own memory, sent the follower the raw message without its offset, learned its follower only from the publisher's init message (which the Kafka gateway never sets), and wrote to one follower stream from every publisher at once. The leader now takes its follower from the partition's assignment when it loads the partition and streams each entry, with its offset, from one sender goroutine in offset order; a publish is acked once the follower acks that offset. Heartbeats and a 5 second silence limit tell a lost follower from a quiet one, and a broken pair answers the publisher GENERATION_ENDED. The follower holds the entries the leader has not stored yet, drops them as flush notices arrive, and the leader closes the stream gracefully once it has stored everything, when the partition unloads. A partition with no follower acks from memory as before. * mq: give a partition whose pair broke a new pair Nothing reassigned a partition whose leader or follower was lost while the other half lived on: the balancer only replaced brokers that had left its broker set, and only on its own schedule. A broker of a broken pair now reports the epoch with EndPartitionGeneration, and the balancer assigns a new pair and the next epoch, preferring brokers outside the old pair. A report for an epoch that already moved on is ignored, so both halves can report, and reassignments are serialized. * mq broker: a leader that loses its follower stores what it holds and ends the generation When the follower stream broke, the leader kept serving alone, acking from memory again. A broken pair now ends the generation on the leader: it stops taking publishes, renews its fence so a new leader waits, stores everything it holds under that fence, seals it, and reports the epoch so the balancer assigns a new pair. A follower that cannot be reached when the partition loads ends the generation the same way. * mq broker: a follower takes over from a leader it lost When the follow stream broke, the follower dropped what it held, so entries the leader had acked but not stored were gone with it. The follower now moves the fence from the lost leader to itself, unless the leader sealed it first, reads what is already stored, stores the entries above that, seals the fence and reports the generation ended. The leader acks only what the follower holds, so every acked entry is stored once, and a leader still writing is fenced out. * mq broker: reload topic.conf when the balancer names this broker leader A broker made leader by a reassignment could still hold the previous topic.conf in its 30 second cache, so it either found no assignment for itself or tried to take the fence with the old epoch, and refused publishes until the cache expired. A publish that finds either now drops the cached config and loads the partition again. * mq broker: stop routing subscriptions through the follower A subscription dialed the follower named in its init and advanced its committed position only while that follower stream existed, so a partition without a follower never saved a consumer position, and a dead follower failed every subscription. The leader now tracks the position itself and saves it when the subscriber leaves. * mq broker: tell a partition's leader its follower when assigning it The balancer created a topic's partitions on their leaders with only the partition and epoch, so a partition made that way never knew its follower and acked from memory. It now sends the whole assignment. Only the named leader creates the partition; the follower learns of it from the leader's follow stream, so the old forward of the leader's request to the follower, which would have made the follower take the fence too, is gone. * mq broker: report an ended generation until a settled balancer takes it A broker reported a broken pair once. When the lost broker was also the balancer, the report failed and the partition stayed at a sealed epoch nobody would serve. The report is now retried with backoff until a balancer takes it, and a balancer takes reports only after its settle window, so the new pair is picked from every live broker rather than the few that reconnected first. * mq: describe the replicated pair in the failover notes * mq broker: break a pair whose follower stopped reading The follower's silence was checked in the loop that sends to it, so once a send blocked on a follower that stopped reading but kept its connection, nothing checked again and publishers waited on acks that never came. The check now runs on its own and cancels the stream. * mq broker: a follower that cannot ack its leader takes over An ack that failed to send ended the follow stream with an error and dropped the follower's entries, though they may include messages the leader had already acked to publishers. A failed ack now takes over the partition, as a broken receive does. * mq broker: retry a takeover through filer errors A follower taking over gave up on the first failed fence or offset read, dropping the entries its lost leader had not stored, which may be the only copy left. It now retries until the fence has moved on or the broker stops. * mq broker: keep the fence renewed while a survivor persists A leader that lost its follower renewed its fence once before storing what it held, and a follower taking over not at all after moving the fence, so a store that ran past 30 seconds let a new leader take the unsealed fence, refusing the survivor's write and dropping what it held. Both now renew every 10 seconds until they seal. * mq broker: leave the follower its copy when a retiring leader dropped a flush A retiring leader closed its follow stream gracefully once its buffer shut down, which tells the follower everything is stored, but a flush that failed until shutdown is dropped. With the filer unavailable both copies of acked messages went. The stream is now closed only when the flushed offset reached the last one assigned; otherwise it is broken, so the follower takes over and stores its copy. * mq broker: order every topic.conf read-modify-write on the balancer Only the generation handoff held a lock around its read and save of topic.conf, so a concurrent ConfigureTopic or assignment refresh that read the old assignments could save them back over the new pair, after the reporter had been told the generation was taken. All of them now take the same lock. * mq broker: stamp a fence write when it lands, not when it was first tried A fence write took its mtime before retrying, so a renewal that landed after a long run of store errors was already older than the seal wait, and a new leader could take the fence from a survivor still persisting. Each attempt now stamps the time it is sent. * mq broker: watch a leader's follower only once its partition is listed The lost-follower watch started before the partition was registered, so a pair that broke in that gap ended its generation while the partition could not be removed, and the partition was then registered and served after its fence was sealed. Both load paths now start the watch after registering it. * mq/kafka: answer a produce on an ended generation with NOT_LEADER_OR_FOLLOWER A partition whose pair broke answers publishes with GenerationEnded while the balancer hands it to a new pair, which the gateway mapped to UNKNOWN_SERVER_ERROR: it kept the session and Kafka clients did not refresh their metadata. It now maps to NOT_LEADER_OR_FOLLOWER, so the gateway drops the session and clients look the leader up again. * mq broker: take a stale fence only if its holder has not renewed it since A new leader judged an earlier generation's unsealed fence stale by its mtime, then wrote under the token alone. A renewal keeps the token and moves only the mtime, so a holder that renewed in between, still persisting what it held, lost the fence and the write that followed. Taking a fence judged stale now requires the entry as it was read. * mq broker: bound the seal when a leader cannot reach its follower A leader whose replica failed to start sealed its fence and reported the generation under the broker's access lock with no deadline, and a fence write retries until it lands, so a filer that kept failing held every partition operation on the broker. The seal now gives up after the fence take timeout and the generation is reported regardless. * mq broker: bound each report of an ended generation A generation report called the balancer with no deadline, so a balancer that accepted the call and stopped answering held the retry loop and the partition stayed unassigned. Each attempt now gives up after 30 seconds and is retried; a repeat after a save that landed finds the epoch moved on and returns without writing. |
||
|
|
5c5e282787 |
mq: a failed fetch keeps the requested offset (#13208)
* mq broker: keep the fetch offset when a read fails FetchMessage answered any read error with NextOffset set to the log buffer's start offset and error code 2, which the broker error table defines as topic-not-found. That start offset is the earliest offset still in memory, or 0 before the buffer has taken a message, so a client that followed NextOffset either rewound to the start of the partition or skipped every offset that lives on disk. A failed read is now reported as a storage error, mapped to Kafka's retriable KAFKA_STORAGE_ERROR, with NextOffset left at the requested offset. Offsets below the buffer are served from disk, so a read error is never out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: retry a failed broker fetch at the same offset FetchMessagesStateless treated a broker error with code 2 as "offset too old" whenever the fetch offset was below the response's LogStartOffset, and silently refetched from LogStartOffset. Brokers sent code 2 for every read error, and LogStartOffset is only the earliest offset in the broker's memory, so a failed disk read made the gateway skip everything stored on disk. The skipped records were then handed to the fetch path as if they started at the requested offset. Any broker error is now returned, and the fetch path retries at the offset it asked for. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep the fetch offset when the partition cannot be loaded FetchMessage answered a partition it could not load with an empty NextOffset, which reads as offset 0, so a client following NextOffset after a failed lookup or a topic.conf miss would rewind to the start of the partition. The response now carries the requested offset, as the read error path does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: answer unreadable records with KAFKA_STORAGE_ERROR A broker storage error reached the Kafka fetch path as a plain error. FetchMultipleBatches dropped it, readRecords dropped the fallback's error too, and the partition was answered with no records and error code 0, which a consumer cannot tell from having caught up. The broker code now travels as ErrKafkaStorageError through FetchMessagesStateless and GetStoredRecords, FetchMultipleBatches returns an error that comes before any batch, readRecords returns the error when it found no records, and the partition is answered with KAFKA_STORAGE_ERROR so the client retries at the same offset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: require the fetch read-error test to reach the broker TestFetchMessagesStatelessReadErrorKeepsOffset only checked that no fetch went to another offset, so it also passed when the request failed before reaching FetchMessage. It now requires exactly one fetch at offset 10 and an error carrying the broker's read failure, a storage error for code 56. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: keep a storage error when the fallback read also fails When the batch read failed with a storage error and the fallback read then failed another way, readRecords returned only the fallback's error, which maps to no error code, so the fetch answered an empty success instead of KAFKA_STORAGE_ERROR. Both errors are now kept. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
29c9e9df04 |
mq: fix races and a deadlock in the subscriber market (#13200)
* mq: fix races and a deadlock in the subscriber market The balance loop reads consumerInstances, partition slots and each consumer's AssignedPartitions without m.mu, while subscriber gRPC streams mutate them under that mutex: a concurrent map read and map write that the Go runtime turns into a fatal error, killing the broker. balanceRequestChan is unbuffered and sent to under m.mu; when the balance loop finishes a pass and calls Status() (which takes m.mu), the sender and the loop deadlock and the consumer group freezes. adjustBusyConsumers indexes AssignedPartitions with a count derived from a load that includes inflight assigns, which can exceed the slice length and panic. Take m.mu around doBalanceLoad, coalesce balance requests through a buffered non-blocking send, cap the unassign count at the assigned slice length, update MaxPartitionCount under the lock, and wait for the balance loop to exit before closing AdjustmentChan. Add market_concurrent_test.go: consumer churn across balance ticks with concurrent adjustment confirms, and a minimal repro of the index-out-of-range panic. Verified with go test -race. * mq: send market adjustments outside the lock Address review of the subscriber market concurrency fix. doBalanceLoad now collects adjustments under m.mu and the balance loop sends them after releasing it, selecting on stopChan so shutdown can interrupt a send blocked on a full AdjustmentChan. Holding m.mu across the blocking send could freeze the group: a stalled subscriber fills AdjustmentChan, and RemoveSubscriber cannot take m.mu to remove it. AddSubscriber registers the instance before applying the incoming MaxPartitionCount, so the setter no longer no-ops for overlapping joins that reuse an instance not yet in the market. Add TestMarketBalanceDoesNotHoldLockWhileSending: fill AdjustmentChan with no reader and check RemoveConsumerInstance still completes while the loop is blocked sending. * mq: apply consumer limit atomically and stamp adjustments at send Address re-review of the subscriber market concurrency fix. Register the instance and apply the incoming MaxPartitionCount in one operation under m.mu (AddConsumerInstanceWithLimit), so overlapping joins that reuse an instance id keep the latest limit on the instance the market tracks. The previous add-then-set pair left a window where the limit could land on an untracked or stale instance. Stamp each adjustment when it is published, not when it is created. The loop sends after releasing m.mu, so a send blocked on a full AdjustmentChan could otherwise age the unsent tail past the inflight TTL; the next pass would expire it and reassign its partition. Make TestMarketUnassignWithInflightAssigns deterministic: receive the first pass's six assigns, stop the loop, then call adjustBusyConsumers directly and assert it unassigns nothing from a consumer that holds no confirmed partition. * mq: rebalance after raising a tracked consumer's limit Address re-review of the subscriber market concurrency fix. When a join reuses an already-tracked instance id, AddConsumerInstanceWithLimit updates that instance's MaxPartitionCount but returned without requesting a balance. The ticker only acts on a pending request, and the previous one may have already drained, so a rejoin that raises the limit left the extra capacity idle until some other event happened to request balancing. Request a balance in that branch too, so raising a tracked consumer's limit takes effect on the next pass. * mq: reconsider capacity on expiry and guard unassign by owner Address re-review of the subscriber market concurrency fix. Expire inflight adjustments on every tick, not only when a balance pass is pending. A confirmed adjustment can linger in inflight until its TTL and double-count a consumer's load, so a pass triggered by a raised limit could see the consumer as full and assign nothing. When expiry frees that capacity, request a pass so the freed or raised capacity is reconsidered instead of staying idle. Guard the unassign confirmation by owner. ConfirmAdjustment now passes the acknowledging consumer into unassignPartitionSlot, which releases the partition only when it is still assigned to that consumer. A late or duplicate unassign ack can no longer clear a partition that was reassigned to a new owner. * mq: drop confirmed adjustments from inflight load accounting A confirmed adjustment stayed in inflightAdjustments until its TTL, so a partition already in AssignedPartitions was counted twice in the load. An expiry-triggered pass then saw a healthy consumer as over the average and unassigned its partitions, restarting subscribers that were already fine. Remove an adjustment from inflight as soon as it is acknowledged, under m.mu, and take m.mu for the TTL sweep so the two cannot race. Expiry now only retries genuinely unconfirmed adjustments. Also skip unassigning from a busy consumer when no peer has room to accept the freed partition. * mq: scope the market fix back to races and the deadlock The expiry-triggered rebalance and the confirmed-adjustment removal added in the last two commits chased a pre-existing load-accounting behavior: a confirmed adjustment lingers in inflight until its TTL and is counted twice. That is upstream behavior outside this PR's scope, and triggering passes on it churned healthy partitions. Restore the focused fix: the balance-loop data race, the balance-request send deadlock, the inflight unassign panic, the limit write under the lock, and the shutdown close-versus-send race. Load accounting is left as upstream has it. * mq: fold AddConsumerInstanceWithLimit into AddConsumerInstance AddConsumerInstance now takes the partition limit and applies it under m.mu, updating the tracked instance when the id is already registered. The broker was its only production caller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: wait for the adjustment buffer to fill before the lock test A fixed sleep let RemoveConsumerInstance run before the balance loop blocked on a full AdjustmentChan, so the test could pass without exercising a blocked send. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
43556b3a3c |
mq: publishers re-look up and resend when a partition's leader changes (#13195)
* mq client: dial brokers with the publisher's dial option The publisher dialed every broker with insecure credentials, and the per-partition connection added the configured option on top of them, so a publisher could not reach a broker that requires TLS. That connection was also never closed. PublisherConfiguration now takes the dial option, insecure only when none is given, the agent passes its own, and the partition connection is closed when its publish job ends. * mq client: resend unacked messages when a partition's publish stream fails A publisher sent each message once and kept no record of it. Acks were only logged, a broker error on the stream was written to a field nobody read, and the scheduler's wait loop broke out of its select instead of the loop, so after the first stream failure it never looked the partitions up again. Losing a partition leader silently dropped every unacked message and stopped that partition for good. Each partition now keeps its queue and the messages it sent but has not had acked across streams. When a stream fails, or the broker answers with an error or error code, the job ends, the scheduler looks the topic up again with a short backoff, and the replacement stream resends the unacked messages in order before draining the queue. Acks remove messages up to the acked timestamp, so timestamps are made strictly increasing per publisher. A partition holds at most 1024 queued or unacked messages, and Publish blocks beyond that instead of growing without bound. FinishPublish and Shutdown stop the input, Publish then fails, and Shutdown returns once everything queued is acked. * mq client: bound how long a closed publisher keeps resending Once its input is closed, a publisher kept retrying a partition until every message was acked, so Shutdown never returned while no broker could take the partition, and a publisher that was only finished kept looking the topic up forever. Resending now stops a minute after FinishPublish or Shutdown, the open streams are cancelled, and Shutdown reports how many messages were left unacknowledged. * mq/kafka: replace a publish session whose call failed or was cancelled PublishRecord ran Send and Recv in goroutines and returned when the request context ended, leaving them on the stream. A leftover Recv then took the ack meant for the next call on that partition, so acks and offsets drifted apart, and a session whose stream had failed or whose broker answered with an error stayed cached until the topic was deleted. A call that fails, is cancelled, or gets an error response now drops its session and cancels the stream, so the next call opens a fresh one. PublishRecordValue shares the same path. * mq/kafka: publish to the partition's current leader The gateway opened every publish stream on the one broker it was configured with, and a broker answers a publish for a partition it does not lead with not-leader, so with more than one broker most partitions could not be produced to, and none could after its leader moved. The gateway now opens the stream on the leader named by the partition lookup it already caches. A not-leader or connection failure drops the session and the cached lookup and comes back as ErrNotLeaderOrFollower, so the next attempt finds the new leader. * mq/kafka: answer a produce that lost its partition leader with NOT_LEADER_OR_FOLLOWER Every failed produce went back to the client as UNKNOWN_SERVER_ERROR, which Kafka clients do not retry, so a partition leader change surfaced as failed sends. A publish that failed because the leader moved or could not be reached now answers NOT_LEADER_OR_FOLLOWER, and the client refreshes its metadata and sends again. * mq client: let the flush timeout cancel a stalled partition lookup A lookup after a stream failure used context.Background, so a broker that accepted LookupTopicBrokers and never answered kept the scheduler inside it after the flush timeout, and Shutdown never returned. Lookups now run under a context cancelled when the publisher stops, and each broker attempt is bounded so a stalled one does not hold up the next. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq client: stop each test publisher and release held acks on cancel A test that never shut its publisher down left the scheduler retrying lookups against the stopped fake broker for the rest of the package run, and a fake ack worker held on the gate could not exit when its stream was cancelled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq client: do not restart a partition whose stream finished during the switch A re-lookup that moved a partition's leader cancelled its stream and waited for it, then started a new one. If that stream had just finished cleanly, the replacement ran for a job already counted as done, and the scheduler could exit with it still running. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq client: count only data messages as unacknowledged at Shutdown The count added the in-flight list and the queue length, so the close marker FinishPublish queues counted as a lost message: an empty publisher whose marker went unacked reported one unacknowledged message. Every data message holds a slot until it is acked, so the slots are the count. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: let a produce's deadline bound opening its publish stream Opening a session ran under the gateway's own context and waited for the leader's hello, so a leader that took the init and never answered held the produce, and every produce to that partition queued on the creation lock, past their deadlines. Setup now also ends when the caller's context does, without invalidating the assignment for a caller timeout, and the stream outlives the call once open. A call whose context ended while it waited for a dropped session no longer opens another one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: cancel the held publish only once the broker holds its data The test cancelled on a 200 ms timer. A slow session setup let that deadline pass before the data went out, leaving the first stream open for the next call, which then waited on the held ack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: fetch and read offsets from the partition's leader Produces go to the leader, but fetches and the high water mark and log start offset reads still went to the gateway's own broker, which answers partition not found for a partition it does not lead. Reads now use the leader the assignment lookup returns, as the publish path does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq agent: report unacknowledged messages when a publish session closes ClosePublishSession returned success right after FinishPublish, which only queues the close marker, so a message the brokers never acked was lost without an error. The close now waits for Shutdown, which returns once everything is acked or reports what was not after the flush timeout, and no longer holds the session map lock while it waits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: look the leader up again after a read it cannot serve Reads used the cached assignment until its TTL, so after a leader died or gave the partition up, every fetch for the next 30 seconds went to it. A connection failure or a partition-not-found answer from the leader now drops the cached assignment, unless the caller's own context ended. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq client: leave a Publish still waiting to enqueue out of the Shutdown count Publish takes a slot before it checks that the input is open, so a Publish paused between the two still held its slot when Shutdown counted, and Shutdown reported a message the caller was then told was rejected. Each job now counts the data messages it accepted and has not had acked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq/kafka: cancel the silent-leader publish once its hello is withheld The test cancelled on a 200 ms timer, which could fire before the call opened a stream; the retry then opened the withheld stream with no deadline and hung the suite. It now cancels once the fixture holds the hello and bounds the retry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: retain the original publisher payload for replay * mq agent: flush accepted records when the publish stream closes * mq client: isolate bootstrap RPCs by publisher credentials * mq/kafka: honor publish cancellation during lookup and partition waits * mq/kafka: read a partition's offset range from its leader GetHighWaterMark and GetEarliestOffset asked the gateway's configured broker, which answers from its own log buffer. Publishes now go to the partition's leader, so a non-leader gateway broker reported a high water mark that missed the leader's unflushed records. Send the range query to the leader and drop the cached assignment when that broker fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq agent client: bound the wait for the agent to finish a session CloseSession waited in Recv until the agent answered EOF. An agent blocked enqueueing to a partition whose broker stopped acknowledging never reads the close, so it never starts its bounded flush and the close hung. After two minutes, cancel the stream: the agent then stops accepting and flushes, and the close reports the timeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq agent: wait for both closers to reach the flush in the close test The duplicate-close test slept 100 ms to let the second close start. A late goroutine then found the session already removed and the test failed. Wait until both closers are inside finishPublisher instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: answer a partition's offset range only from its leader A broker answered GetPartitionRangeInfo from its offset manager even after the partition moved away, so the gateway kept reading the old leader's range until its assignment cache expired. The broker now checks ownership the way FetchMessage does, and the gateway drops the cached assignment when the range request fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
24951dbfe7 |
mq: one offset assigner per partition, continued from disk (#13191)
* mq: assign publish offsets inside the partition's log buffer A publish took its offset from the offset manager under one lock and appended it to the log buffer under another, so two publishers on one partition could append offsets out of order. The buffer now assigns the offset under its own lock when the entry asks for one, and an entry that already carries an offset moves the buffer's next offset past it instead of bumping it by one. * mq: give the entry that rolls a window over to the new window Both append paths widened the window's offset range before checking for a rollover. The sealed window then claimed the entry that started the next one, and the new window's range started without it, so a window holding only that entry was flushed as offsets 0..0 and readers skipped it. The range is now widened after the rollover. * mq: seed a partition's offsets from all of its own files A loading partition continued its offsets from the highest offset recorded on disk, but the scan listed without a limit, so the filer returned only its default page (1000 entries under weed server and mini) and offsets below the real maximum were handed out again. It also read the newest version directory rather than the partition's own, and a filer error left the partition counting from 0. The broker and the Kafka gateway now share mq.ReadOffsetRange, which lists every file, the broker reads the partition's own directory, and a partition whose stored offsets cannot be read is not loaded, so the publish fails and is retried. * mq: reload a partition only after its retired copy has flushed Idle cleanup and a drain retire a partition and return while its last flush is still queued. A publish right behind them created a new copy, which read the stored offsets before that flush landed and handed out its offsets again. Loading a partition now waits for a retired copy of the same range, outside the broker's access lock that the flush takes. * mq broker: report a partition's high water mark from its buffer The range reported to the Kafka gateway took the larger of the offset manager's count and the buffer's, so it followed the manager's checkpoint rather than what the partition had assigned. It now comes from the loaded partition's buffer, which assigns the offsets, or from the ranges stored on disk when this broker has not loaded the partition. * mq: drop the offset manager's assignment, checkpoint and subscription code Publish offsets now come from each partition's log buffer and its high water mark from that buffer or the stored ranges, so the separate assigner, its checkpoint.offset writer and the offset subscription layer built on it have no callers left. Only consumer-group positions remain in BrokerOffsetManager. Existing checkpoint.offset files are left alone; readers already skip them. * mq broker: recheck a retiring partition under the lock when assigning AssignTopicPartitions waited for a retiring copy before taking the access lock, so a drain in between could retire the partition and the assignment then seeded a replacement before that flush landed. The check now runs under the lock, which is released only to wait. * mq topic: mark a partition retiring before it leaves the list RemoveLocalPartition took the partition out of the active list before recording it as retiring, so a replacement loaded in between saw neither and read the stored offsets before the last flush landed. The partition is now recorded as retiring first. * mq topic: gate the retired-flush test on a channel instead of a sleep The test relied on a 200ms flush delay to observe the partition as pending, which a paused test goroutine could outlast. * mq topic: remove a partition by its instance under one lock RemoveLocalPartition looked the partition up, marked it retiring and then removed by range in separate steps. A second remover of the same copy could take out a replacement loaded in between, leaving it neither listed nor retiring, and a removal that found nothing still left a stale retiring entry. Callers now pass the copy they hold; it is marked retiring and taken out of the list under the partition lock, and only if it is still listed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: look a partition up once per assignment pass The retirement wait checked one lookup and the load used a second one, so idle cleanup retiring the partition between them let the assignment load a replacement from stored offsets before the retired copy's last flush landed. The wait and the load now use the same lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: let a cancelled assignment leave the retirement wait AssignTopicPartitions waited for a retired copy's last flush without watching its request, so while that flush kept failing a cancelled call still held its handler. WaitRetired now takes a context and returns its error, leaving the retirement pending; the publish and subscribe loader keeps waiting as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq topic: share one flush signal per retirement A cancelled WaitRetired left its goroutine blocked on the retired buffer's flush, so repeated cancelled assignments piled up goroutines until that flush finished. The retirement now owns one channel, closed after its last flush, and every waiter selects on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: load the assigned generation for any request of its range Subscribe and fetch pass the partition from the request, and the loader built the local partition from it after matching only the range. A stale or zero generation then scanned a directory the broker was not assigned, found no offsets, and registered a partition that restarted at zero over stored data. The loader now takes the assignment's partition. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
9cea13b9fc |
mq broker: fenced flushes, one file per window (#13192)
* mq: number partition leaderships with an epoch A partition assignment named its leader but nothing told one leadership from the next, so a broker that lost a partition could not be told apart from the one that replaced it. BrokerPartitionAssignment now carries an epoch that the balancer bumps whenever it picks a different leader, including the first leader of a new partition, so a fresh allocation starts at epoch 1. Follower changes and re-spelled addresses of the same leader keep the epoch. * mq broker: take a partition fence before leading a partition Nothing stopped a broker that had lost a partition from writing to it, so two brokers flushing one partition overwrote each other's files. Each partition directory now holds a .fence entry naming its writer and the assignment epoch. A broker generating a partition as leader reads the fence and rewrites it with one filer ObjectTransaction, routed to the fence's owner filer and conditioned on the fence being absent or unchanged since the read, before it reads the partition's existing offsets. A fence stored at a higher epoch or sealed is refused, and the partition is not served when the fence cannot be taken. The broker keeps the fence entry as stored so later writes can present it. Topic configuration now passes each assignment's epoch to the broker it assigns. * mq broker: flush each window to its own fenced file A flush uploaded a chunk on every attempt and appended it to the chunk list of the file named by the window's start second with an unconditional CreateEntry. A lost response duplicated the window, every retry orphaned the previous chunk, and two brokers writing one partition overwrote each other's chunk lists. Each window now becomes a new file named by its start second and its first offset, uploaded once and written with one filer ObjectTransaction conditioned on the partition fence the broker holds. Only the transaction is retried, under a single request id, so a replay cannot apply twice. buffer_start now records the window's first offset instead of the next-offset counter. A failed fence condition means another broker took the partition: the window is dropped, later windows drop without an upload, and the publish path answers not-leader so publishers move on. The follower's stream-end write of its leftover windows now goes through the same fenced writer, which refuses it because a follower holds no fence. That write only ever produced offset-less duplicates of what the leader flushed, so the follower now drops those windows. * mq: read flushed windows named with an offset suffix Flushed windows are now named by start second and first offset, which the readers did not expect. The disk reader dropped every file whose name sorted after the stop second, which a window starting in that very second now does, and log compaction parsed the whole name as a time and skipped the new files. Both now look only at the start-second part, so files with either naming are read. The partition fence that sorts first in a listing is skipped by the disk reader and the query engine's live-log scans, and topic truncation keeps it. * mq broker: retry a recorded flush failure under a new request id The filer records a failed mutation under its request id and replays it for two minutes, so retrying the same id stalled the partition's flush. Putting the same window entry again is harmless, so a recorded failure now retries under a fresh id; a lost response still retries under the same one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: hold the partition fence by a token, not a read-back entry Taking the fence read the written entry back through the broker's filer, which may lag the fence's owner filer; a successful take then looked lost and the new leader did not load. The fence entry now carries a fresh token as its etag, and later writes require that etag on the owner, so nothing is read back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: bound the fence take's filer calls A partition is loaded under accessLock, and the fence take's lookups and transaction had no deadline, so a filer that accepted a call and never answered held every partition operation on the broker. A take that runs out of time leaves the partition unserved for a later attempt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: name compacted files and skip compacted windows by their source logs Now that several windows can start in one second, compaction named every output after its first message's second, so groups starting in the same second overwrote each other, and it skipped any window whose start second was not after the newest compacted row, so a later window in that second was never compacted. A parquet file is now named after its first source log, which is unique, and a window is skipped when a parquet file lists it as a source; the start-second rule remains only for windows named by their second alone. * mq broker: reload a partition whose fence another broker took A partition that lost its fence stayed registered until its last client left, and both partition load paths reused it, so a broker made leader again at a newer epoch kept answering not-leader, or wrote until its next flush was refused. A fenced partition is now dropped and the partition loaded again under the current assignment's epoch. * mq broker: reload a partition held under an older epoch A copy whose fence was taken is reloaded only once a refused flush marks it lost. Until then a broker made leader again at a newer epoch kept the copy and accepted publishes that the next flush dropped against the other broker's fence. A copy whose fence epoch is older than the assignment's is now reloaded too. Its last flush lands under its own fence before the reload reads the stored offsets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: start a new compaction group only after the current one has a file A first log file larger than the group size left an empty first group, and naming a parquet file after its group's first log then indexed past the end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: remove a partition by its instance, not its range A publisher or subscriber of a copy that was replaced removed the partition by range on its way out, which shut down the replacement instead. Removal now takes the copy itself and leaves a copy that has replaced it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: keep a stale copy registered until its last flush lands A reload removed the stale copy and then waited for its last flush without accessLock. A concurrent lookup or assignment found no copy, took the new fence first, and the pending flush was refused and its window dropped. The copy is now shut down where it is registered, so every loader finds it and waits for the same flush, and it is removed only afterwards. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: refuse an assignment once a reload waited out a shutdown start The stopping check ran before the stale-copy reload, which releases accessLock while the copy flushes. A Shutdown starting then left the retired copy in place and the assignment reported success for it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: bound the concurrent reload test's waits Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: describe fenced writes and the follower loss window in the failover notes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: release the upload gate when the reload test times out A first upload starting just after the deadline check stayed blocked on the gate, so the test server's Close waited on it and cleanup hung. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
501cf6b760 |
mq: read a recorded offset range that ends at offset 0 (#13190)
The broker and the Kafka gateway each scanned a partition's files for the high water mark and counted a maximum only when it was above 0, so a partition holding one message still read as empty. Both now share mq.OffsetRange, which tracks whether a range was found apart from its value. |
||
|
|
81b83b155f |
fix(mq): copy flush buffers before queuing follower data (#13183)
* fix(mq): copy flush buffers before queuing follower data * fix(buffered_queue): release references after dequeue |
||
|
|
10381075f3 |
mq: record the offset range of a partition's first window (#13180)
The flush wrote offset_min/offset_max only when minOffset > 0, using 0 as "no range given". A partition's first window starts at offset 0, so its file never got a range. A restarted broker derives the high water mark from those ranges, so a partition whose data was all in its first file read as empty. |
||
|
|
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> |
||
|
|
fcd28031e7 |
mq/kafka: wait for a filer to register instead of panicking on an empty list (#12019)
* mq/kafka: wait for a filer to register instead of panicking on an empty list NewSeaweedMQBrokerHandler queried the masters for filers once, ~2 s after start, and handed an empty list to NewFilerClientAccessor, which panics. A fresh filer registers only after its empty-membership confirm window (10 s), so a gateway started with a fresh cluster crashed (Kafka Quick Test, kafka-gateway exit 2). Retry while the list is empty for up to 60 s, then return an error. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * mq/kafka: wait out a transient-empty broker listing too A fresh SMQ broker registers with the masters on the same announce delay as a filer, so the one-shot broker lookup could fail startup the same way. Generalize waitForFilers into waitForClusterNodes and bound both discoveries by the same window; the empty-broker check becomes unreachable and drops away. * mq/kafka: wait out the broker health check like node discovery A broker announces to the masters before it has acquired its balancer lock, so the gateway's three-attempt probe could still fail fast on a fresh cluster. Retry FindBrokerLeader for the same window the caller waits out empty listings. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: user.email <chrislusf@users.noreply.github.com> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
9a65616cd0 |
filer: announce to master only once gRPC serves, and leave before it stops (#11700)
* wdclient: gate master registration until the server is serving The first KeepConnected send registers the client into the master's cluster list, which is what routes S3 and peer traffic to it. A filer connects to the master long before its gRPC port serves (peer discovery, store bootstrap), so it announced itself while still refusing connections. announceCh defers only the registration send, letting the stream machinery connect early without joining the list; ListMasters exposes the configured masters for callers that cannot wait on the stream. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: announce to the master only once gRPC serves NewFilerServer previously registered on the master's filer list during startup, before the gRPC listener was serving — and on a fresh store before peer bootstrap finished — so a restarting filer could be routed to while refusing connections. The announce channel is closed right after grpcS.Serve starts. ListExistingPeerUpdates now iterates the configured masters directly since GetMaster would block on the gated stream. On shutdown, cancelling the master context ends the KeepConnected stream during the leave phase, so the master drops the filer node before gRPC stops accepting; fs.Shutdown cancels it as a fallback. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * wdclient: test that the announce gate delays registration Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * wdclient: unblock queries behind the announce gate The gate holds the registration send, but setting currentMaster only after the first response left GetMaster blocked for the whole gated window. Any startup path that queries the master before serving (e.g. loading a chunked filer.conf) deadlocked the constructor, so the gate never opened. Mark the master queryable once the stream is established; registration and leader redirect still wait on the gate and first response as before. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: keep the fullest peer list from any master ListExistingPeerUpdates returned the first non-nil answer, so a follower master could seed the peer list with a stale partial view before the leader replied. Keep the longest response instead. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: keep master queries usable after the shutdown disconnect Leaving the filer list early ends the KeepConnected stream, which cleared currentMaster and left the final metadata-log flush unable to reach the master during drain. Keep the last serving address queryable after a canceled disconnect, and move the Shutdown fallback cancel behind the filer's own shutdown so callers that skip LeaveLockRing flush against a live stream. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * cluster: propagate a bounded context through ListExistingPeerUpdates The helper dialed and queried masters on context.Background, so one unresponsive master could stall the whole peer scan and ignore caller cancellation. Pass ctx through, bound each master query in the filer's scan, and stop when the caller cancels. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: wait for cluster removal before draining gRPC Cancelling the KeepConnected stream only signals removal; the master drops the filer when its stream handler unwinds. Until then new requests can still route to this filer while its listener is closing. Poll the configured masters, bounded, until none still lists this filer. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * wdclient: serialize master discovery access ListMasters made peer scans a second concurrent accessor of mc.masters alongside tryAllMasters, while ServerDiscovery refreshes and reads its address list unsynchronized. Guard the refresh and every instance copy behind one lock. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * cluster, filer: prefer the leader's peer list and report lookup errors Keeping the longest answer let a stale ex-leader's list win: after a leader change the old master retains registrations until its streams end, so a fresh filer could bootstrap from an unreachable peer. Ask the masters for the raft leader and take its list; only when the leader is unreachable fall back to the fullest answer. ListExistingPeerUpdates also returned an empty slice on RPC failure, which a fresh filer read as "no peers" and skipped bootstrap, serving without the existing files. Propagate the error and retry the scan during startup, before the announce gate opens. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: bound the removal wait and retry unconfirmed masters Each master query got its own two-second timeout while the five-second deadline was only checked between scans, so three stalled queries could stretch the wait past its budget. A failed query also counted as confirmed removal, letting gRPC drain while a master still listed the filer. Derive every query context from one overall deadline, track which masters confirmed absence, and retry the rest until they answer or the budget expires. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * wdclient: run the SRV lookup outside the masters lock ListMasters and tryAllMasters held mastersLock across the DNS lookup, so a slow resolver stalled GetMasters and ListMasterSet readers past their request deadlines. Split the lookup from the list swap: resolve the SRV record unlocked, then lock only to save it. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * wdclient: bound WaitUntilConnected in the announce-gate test The wait ran on the caller context with no deadline, so a regression that left currentMaster unset hung the whole test run instead of failing the check. Give it the same three-second budget as the assertions that follow. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * wdclient: order SRV refreshes and reuse the cached list on shutdown * filer: confirm an empty leader peer list before accepting it * filer: announce only after the startup peers' replay catches up --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
b2eefb8a73 |
filer: fail the request, not the process, when chunks cannot be resolved (#11685)
* filer: fail the request, not the process, when chunks cannot be resolved CompactFileChunks and ViewFromChunks discarded the error from NonOverlappingVisibleIntervals and iterated the nil interval list it returns on failure. A CreateEntry or UpdateEntry whose context was cancelled therefore panicked in SeparateGarbageChunks and took the whole filer down, losing the metadata log it had not yet flushed. Both functions now return the error. cleanupChunks fails the request with it, the mount flush paths return it, the replication sinks and the S3 SSE range reader return it, and a ChunkStreamReader that cannot build its view fails every read with it and reports it as its SourceError instead of reading as an empty file. Fixes #11682 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * filer: propagate chunk resolution failures in scan paths NonOverlappingVisibleIntervals can fail without a cancelled context; the query engine and log-store callers discarded the error and dereferenced nil intervals. * query: propagate chunk resolution errors instead of skipping files When a manifest cannot be resolved, ReadParquetStatistics, countLiveLogRowsExcludingParquetSources, and computeLiveLogMinMax logged a warning and skipped the failed file, so queries returned understated counts and wrong min/max values. Surface the errors instead: the fast-path aggregation collector now returns a DataSourceError so the engine falls back to a full scan, and the row-count helpers return the error rather than a partial total. --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Chris Lu <chris.lu@gmail.com> |
||
|
|
a0b1272cc3 |
filer: authorize the chunk proxy and the root listing like the rest of the filer port (#11152)
* filer: require a read token for the root listing maybeCheckJwtAuthorization waved through every GET/HEAD on "/", so a filer with jwt.filer_signing.read.key set still served its root directory listing -- entry names, sizes and chunks[].file_id -- to a caller holding no token at all, and served the same listing to a token restricted by allowed_prefixes. The exemption was added for health checks before the filer had /healthz and /readyz. Both are registered on the default and read-only muxes ahead of the "/" handler and answer without a token, so drop it. Point the mTLS harness at /healthz, which is what it was probing for. * filer: keep the jwt query parameter out of a proxied chunk request The proxy stripped "jwt" from the forwarded query on reads only, on the grounds that a writer's own credential travels there. It does not: an uploader carries its AssignVolume token in the Authorization header, and the query parameter on this path holds a filer credential. Strip it for every method. A volume server has no business seeing a filer token, and because security.GetJwt reads the query before the header, relaying one would hide the writer's own token behind it. * filer: dispatch the chunk proxy after the JWT gate The ?proxyChunkId= branch returned before maybeCheckJwtAuthorization ran, so GET, PUT, POST and DELETE against any needle in the cluster were reachable on the filer's HTTP port with no filer credential, on a filer where every other request answered 401. An anonymous caller read a stored object, replaced its bytes, or deleted the needle, which the master's next vacuum makes permanent. #10434 stopped the filer from minting a volume write token for that caller, which closes the write half only where the volume server has a jwt.signing.key of its own -- not the shipped default, and not what scaffold/security.toml recommends for a filer deployment. The read half stayed open in every configuration, because the filer mints the read token itself. Move the dispatch below the gate. A file id carries no path, so a token restricted by allowed_prefixes cannot be scoped against one and is refused here; every consumer of this endpoint holds an unrestricted token. * filer: mint the volume credential for a proxied write too The proxy minted a volume token on reads and forwarded whatever the caller sent on writes. #10434 made it that way because the branch ran ahead of the JWT gate, so a token minted here would have been signed for an unauthenticated caller; the branch now runs behind the gate, and the credential the caller presents there is a filer one, which a volume server cannot validate and has no business seeing. Mint at the access level the request needs, and drop the caller's Authorization when there is no key to mint from. A proxied uploader then needs only the filer credential, instead of holding one for each hop with a single header to put them in. * mount, mq, filer.sync: send the filer credential for a proxied chunk Every in-tree consumer of ?proxyChunkId= reached the filer anonymously: mount and the broker put the AssignVolume token in the Authorization header, which is a volume credential, and filer.sync sent nothing at all. That was enough only while the branch ran ahead of the filer's JWT gate. Build the URL through one helper, and pick the credential from the URL it returns: a chunk proxied through a filer is a request to the filer, which authorizes it and attaches the volume credential itself, so the token there is a filer one at the access level the request needs. * filer: honor -exposeDirectoryData The flag was declared on all three commands that start a filer and read by none of them: FilerOption.ExposeDirectoryData was only ever assigned from filer.expose_directory_metadata in security.toml, so -exposeDirectoryData=false silently left the listing exposed. Only the TOML key had any effect. Plumb the flag through and let either switch turn the listing off. * filer: count a proxied chunk request once Moving the dispatch below the gate put it after the deferred request observation, so every proxied chunk now landed in FilerRequestHistogram twice, once under its HTTP method and once under chunkProxy. Name the deferred one after the proxy instead, the way the unsupported-method branch already does, which also gives the endpoint the status codes FilerRequestCounter records. |
||
|
|
32df246a81 |
mq: fix idle-cleanup shard deadlock that permanently wedges the broker's topic map (#11051)
mq: remove emptied topics after the cleanup iteration, not inside it cleanupIdlePartitions called manager.topics.Remove from inside manager.topics.IterCb. IterCb holds the shard's read lock while running the callback, and Remove takes the same shard's write lock, so removing an emptied topic self-deadlocked the cleanup goroutine. The pending writer then blocked every later reader of that shard, permanently hanging ListTopicsInMemory and, for shard-mates, TopicExistsInMemory. On the Kafka gateway this surfaced as flaky e2e consumer-group tests: one minute after any earlier topic went idle, the broker's first 'Removing empty topic' wedged the map, every gateway ListTopics/TopicExists RPC burned its full 5s timeout, Metadata could no longer finish inside kafka-go's 5s coordinator deadline, and consumer groups looped in PreparingRebalance until the test timed out. Collect the emptied topic keys during the iteration and remove them afterwards via RemoveCb, re-checking emptiness under the shard lock so a topic that just gained a partition is kept. Claude-Session: https://claude.ai/code/session_014yA6c8JQcY6MqPXCT13yYA |
||
|
|
9e06e1d0f9 |
Report a delete the filer rejected instead of answering success (#11003)
* s3tables: report a delete the filer rejected deleteDirectory discarded DeleteEntryResponse and checked only the transport error, so DeleteTable, DeleteNamespace, DeleteView and DeleteTableBucket answered 200 for a delete the filer refused. Call filer_pb.DoRemove, which reads resp.Error and still treats a missing entry as success. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * admin: report a delete the filer rejected The bucket delete, the file browser handlers and the topic retention purger all discarded DeleteEntryResponse, so a delete the filer refused came back as success. Call filer_pb.DoRemove, which reads resp.Error. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * credential: report a delete the filer rejected DeleteUser, DeletePolicy and the full-sync cleanup loops discarded DeleteEntryResponse, so a rejected delete answered success and left the credential file in place. The service account path in the same store already read resp.Error; the rest now do too, via filer_pb.DoRemove where not-found is already tolerated. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * shell: report a delete the filer rejected remote.configure -delete, remote.cache and the remote metadata sync discarded DeleteEntryResponse, so a rejected delete printed as removed. Call filer_pb.DoRemove, which reads resp.Error. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * mq: report a delete the filer rejected The consumer offset group purge and the coordinator assignment delete discarded DeleteEntryResponse. Call filer_pb.DoRemove, which reads resp.Error. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * iam: count only the revocation entries the filer actually deleted The expiry sweep discarded DeleteEntryResponse, so a rejected delete was counted as purged and the entry stayed. Call filer_pb.DoRemove, which reads resp.Error, matching the role and provider stores beside it. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * mount: fail rmdir when the unary fallback delete was rejected The streaming branch turns DeleteEntryResponse.Error into an error, the unary fallback dropped it, so rmdir of a non-empty directory answered OK off the stream and ENOTEMPTY on it. Surface it in both. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * s3tables: fail DeleteTableBucket when the directory delete is refused The handler only failed when both the leaf entry and the directory delete failed, so a refused bucket directory delete still answered 200 with the bucket in place. The directory is the bucket, so it decides; the leaf entry stays best-effort. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU |
||
|
|
902a12fd6f |
wdclient: bound the wait for a master leader by the caller's context (#11002)
* wdclient: bound the wait for a master leader by the caller's context WithClient waited on GetMaster with context.Background(), so a caller that arrived while no master leader was known parked in a 200ms poll loop until one appeared, whatever deadline it had already set on the RPC. Each retry above it then left another goroutine in the same wait. Take the context in WithClient and WithClientCustomGetMaster and hand it to GetMaster, and stop the retry loop once it is done. The dial keeps context.Background(): fn brings its own RPC context, so a cancellation seen here cannot be attributed to the shared connection. Call sites pass whatever they hold: the request context in the filer's CollectionList, DeleteCollection and Statistics handlers and in the credential store's propagation, the operation context in the shell's s3.bucket.delete and the kafka gateway's broker and filer discovery, and context.Background() where there is none - the shell commands, the admin dashboard wrapper, and the exclusive locker's initial lease. The locker's release keeps its own uncancelled context so a slow unlock cannot turn into a ghost lock. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * wdclient: test that WithClient gives up with the caller's context Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * wdclient: cut the master retry backoff short when the caller gives up util.Retry sleeps unconditionally between attempts, so a transient error arriving just before the caller's deadline still cost it a full backoff step. Use the context-aware util.RetryWithBackoff, the same helper the volume lookup in this file already uses. Two call sites went with it: the shell's lock-holder lookup builds its three second bound before WithClient so it also covers finding the leader, as its comment already promised, and the filer's post-delete collection cleanup goes back to an uncancelled context - the entry is already gone, so a caller that hung up must not leave the collection behind. Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU * wdclient: test that a cancel during backoff ends the retry Claude-Session: https://claude.ai/code/session_01BjDWtZsCoZY6x4pdDmGWxU |
||
|
|
47b491b53c |
mount: version open file handles by filer log position (#10403)
* filer: stamp a log position on lookup and remote-cache responses Metadata events are logged after their store write and stamped with the filer clock. Reading that clock before serving an entry therefore gives a timestamp with a causal guarantee: every event at or below it is reflected in the returned entry. Clients caching filer state can use it as the entry's version to order the response against subscription events, including events committed before the call but delivered after it. * mount: version open file handles by filer log position A subscription event refreshing an open handle did a second lookup; a transient failure left the handle pinned to its old entry with no retry, since the subscription cursor had already advanced. The deeper problem is ordering: the handle is a cache written by three unordered channels — the async invalidation worker, local mutation acks, and open-time lookups — and overwriting cached state safely requires knowing which write is newer. The filer log timestamp is that order, and it now travels with every value instead of being derived out of band. Events carry it natively; lookup and remote-cache responses carry the log position stamped before the serving read; mutation acks carry it in their returned event; and the local store pairs each read with a version cursor advanced under the same lock as the store write. Each handle records the version its entry reflects, and one rule replaces the per-site reasoning: state at or below the handle's version is old news and must not be installed. The invalidation itself applies the event's own entry — no lookup, so no transient-failure window — except under a cached parent, where the store entry is the ordered merge of the event and anything applied since, and its version outranks the event's. An uncached parent receives no store writes, so a hit there would be a stale leftover masking the event. A vacated path (delete, rename away) keeps the last entry so unlinked-but-open reads still work. Directory builds version the completed directory at the listing snapshot and re-invalidate buffered events at that version, since their mid-build refresh ran against an incomplete store. The tests replay every race this replaces machinery for: rollback of a newer local flush (queued, cached, and read-through), stale leftovers under uncached parents, the build window including abort, handles opened after an event was queued, events landing mid-lookup, and undelivered events at remote-cache time across a filer failover. * filer: serialize the log position fence with mutations, stamp mutation acks The fence stamped before an unlocked entry read could precede state the read returned: a mutation writes storage first and assigns its event timestamp only at notify time, so a lookup racing that window handed the mount an entry newer than its fence, and the event's later delivery looked like fresh news — destroying dirty pages for a change the handle already had. The mutation handlers already hold an exclusive per-path lock across read, write, and notify; the lookup and remote-cache reads now take it shared around the stamp and the read, making the fence exact: everything at or below it is in the entry, nothing above it is. A no-change update returns success without an event, leaving the mount nothing to fence with even though the response confirms current state. Create and update acks now carry a log position stamped under the same lock, and the mount falls back to it whenever the ack has no event. Also regenerate the VT marshalers, which the earlier generation missed: without them a VT round-trip silently zeroed every log position. * java: sync filer.proto * mount: scope store versions to what they vouch for; atomic handle install The store's version cursor claimed too much. Advanced by local mutation acks and directory listing snapshots, it inflated the version of store reads for unrelated paths whose events the subscription still owed, and those events were then fenced out permanently. The cursor now tracks subscription progress only — events arrive in log order, so everything at or below it has been delivered for every path — and a completed listing records its snapshot as a per-directory floor instead of a global claim. Local acks never touch it: they version their own handle directly. Buffered build events advance the cursor at delivery, since their store write may never happen (abort) while their invalidation is already queued; their read-through directory pairs no store read with it, and rename fragments are applied first. Concurrent first opens raced: a slower opener's older lookup could overwrite the newer entry a faster opener had installed, while the monotonic version kept the newer timestamp — an old entry fenced at a new version, immune to every correcting event. Entry and version are now installed as one decision under the handle map lock, and an install that does not outrank the handle's version is dropped. The remote-cache commit also escaped the fence: it wrote storage and notified without the path lock, so a lookup's shared-locked fence and read could land between the two and hand out the cached state under-versioned. The commit now re-reads and writes under the exclusive path lock, and backs off entirely when the entry changed during the download — the concurrent writer supersedes the cached content. * mount: floors gate store applies; installs respect handle users; renames join the fence A directory floor certifies the listing state as of its snapshot, but a delayed event at or below the floor was still applied to the store — rolling the content back to pre-snapshot state while the floor kept claiming the snapshot version, so the correcting events were fenced out of every future read. Events are now gated against the affected directory's floor, each half of a rename independently. Fences are lower bounds: a listing or lookup can include a mutation whose event has not been delivered yet, and that event later passes every gate carrying state the handle already holds. Such a re-delivery now advances the version without destroying dirty pages or reinstalling the entry — invalidating local writes over a no-op was the real damage in every remaining under-fence window, including the unlocked listing snapshot, which no per-path lock can serialize. The concurrent-open install moved from the map lock to the handle lock every reader, writer, and invalidation synchronizes on, and rejects what cannot improve the handle: dirty state (local writes would be lost), unversioned lookup responses (they cannot outrank anything, and two zero-version opens must not overwrite each other), and anything not strictly newer. New handles are still fully initialized before the map exposes them. Renames committed metadata and emitted events with no path lock, so a lookup could read the renamed state under a fence preceding its events. Both rename handlers now hold the source and destination locks, ordered by path, across commit and notification; descendants of a renamed directory are not individually locked and rely on the no-op re-delivery handling above. * mount: per-entry store versions replace the cursor and directory floors The store's aggregate versions — a global subscription cursor and per-directory listing floors — were versions at coarser granularity than the values they described, and every over-claiming bug in this series traced to that gap: an aggregate vouching for state its source never saw. Each store entry now carries the filer log position of the write that produced it — the event that applied it, or the listing snapshot that inserted it, recorded in the store's key-value space under the same lock as the entry write. The store becomes what the handle already is: a last-writer-wins register with one rule, install only what outranks the current claim. The cursor, the floors, their advancement rules, the pairing ordering constraint, and the floor gating all collapse into that rule. Applies are gated per entry, each half of a rename independently; an unversioned local write clears the claim its content no longer proves; version records lingering after a bulk folder wipe cannot fence a recreate, since a claim only blocks while its entry exists. Listing inserts are stamped at build completion, before the buffered replay so newer replayed events override the stamp. Filer side, the fence dance every versioned read must perform is now a single choke point, fencedFindEntry, so a future read RPC gets the lock-serialized stamp by construction rather than by convention. * mount: judge no-op re-deliveries against an immutable base, not the live entry The equal-state skip compared the incoming event to the live handle entry, but local writes mutate the live entry — size, timestamps, chunks — so a delayed event re-delivering the base the handle was opened with no longer matched, and the installer destroyed the dirty pages and rolled the entry back over nothing new. The handle now keeps an immutable snapshot of the filer state it last installed or acknowledged, refreshed at every install and mutation ack (flush acks snapshot the request entry before the id mapping mutates it), and the no-op judgment runs against that base: an event carrying the base brings nothing, whatever the live entry has diverged to since. * mount: tombstones for versioned deletes, absence floors, copy enrollment Four gaps in the per-entry version protocol, all the same shape: a versioned fact with nothing carrying its version. A deletion is a fact about a path with no entry left to hold it — clearing the record let a delayed older event resurrect the deleted path, permanently, since the deletion's own redelivery is dedup-suppressed. Versioned deletes now leave a tombstone record that fences without an entry; renames tombstone their source the same way. Plain records still only block while their entry exists, so records lingering after a bulk folder wipe cannot fence a recreate. A completed listing proves absences as well as presences: a name it omitted was deleted as of the snapshot, and a delayed create below the snapshot re-creates it. The snapshot is kept per directory strictly as an absence fence, consulted only when a path has neither an entry nor a version record — present entries carry their own versions and never touch it, which is what separates this from the over-claiming floor it replaces. A rebuild against a pre-upgrade filer returns no snapshot; stamping now clears the children's records in that case, so a reinserted entry cannot reactivate the stale claim its previous incarnation left behind and reject valid events below it. Server-side copies installed the copied entry without enrolling in the base protocol, so the copy's own event differed from the stale pre-copy base and destroyed writes made to the destination after the copy. The install now refreshes the base and takes its version from the fenced readback. * mount: deletion facts outlive the cache's knowledge of the entry A versioned delete of a path the store held no entry for recorded nothing, so a delayed older event recreated the path — permanently, with the deletion's redelivery dedup-suppressed. The tombstone is now written whenever a versioned event vacates a path: the deletion is a fact about the path, not about what this cache happened to hold. For an absent entry, the listing's absence floor now speaks whatever older record remains: a tombstone at one position does not exhaust what is known about the path when a newer snapshot has confirmed the name still absent, and an event between the two was slipping past both. A committed copy whose readback failed installed a synthesized base with local timestamps; the copy's real event legitimately differs from it, and was read as foreign state — destroying writes made to the destination after the copy. The handle now marks that its own event is en route and adopts that event's state as the base without touching the live entry or the dirty pages; the adoption is one-shot, so a genuinely foreign event still invalidates. * mount: authoritative acks cancel pending event adoption; tombstones scoped and pruned The copy-event adoption flag could outlive its purpose: a flush after the failed readback installs a newer base and advances the version, the copy's own event is then version gated without consuming the flag, and the next genuinely foreign event was silently adopted — base advanced, live entry and dirty pages untouched — leaving the mount to later overwrite that remote change. Every local acknowledgment now installs its base through one helper that also cancels any pending adoption: the ack supersedes the mutation the adoption was waiting for. Tombstones were written for every versioned delete under the mount and survived directory eviction by design, growing LevelDB with historical deletions on delete-heavy mounts. They are now scoped to directories whose cached state the fence actually protects — an uncached parent never serves from the store nor applies the resurrecting insert — and a completed listing prunes the direct-child tombstones its absence floor supersedes, leaving only those above the snapshot. The store gains a key-prefix visitor for the sweep. * mount: acked saves install their value; trailer snapshots; direct-child prune range A version must never advance without its value. saveEntry stamped any open handle with the acknowledgment's version, but a handle opened while the save was in flight holds the pre-mutation entry — stamping it fenced out the events carrying the state it lacked, permanently, with the local apply performing no invalidation and the redelivery deduplicated. The acknowledged entry is now installed together with its version, through the same guarded install the racing-open path uses: under the handle lock, only when it outranks the handle, never over dirty local writes. Empty listings return no in-band snapshot — a snapshot-only response would be read as an entry by older consumers — so directories that end empty gained no absence floor and their tombstones were never pruned. The filer now sends the snapshot in the stream trailer, which older clients ignore, and the client reads it when no in-band snapshot arrived. Empty directories get real floors, their tombstones prune, and their buffered replays gain the snapshot filter instead of the replay-all fallback. Version records now encode the parent directory and name separated by a NUL, making a directory's direct children one contiguous key range: the tombstone prune scans exactly them under the cache lock, instead of walking every descendant record — the whole store, for root. * mount: fix dirty-page loss, uid/gid base, download race, copy adopt, leak; dedup Correctness fixes from the versioned-invalidation review: - A foreign delete/rename-away of a file held open with unflushed local writes destroyed the dirty pages unconditionally. A process may keep writing to an unlinked-but-open file and those writes were already acknowledged; preserve the pages when the handle is dirty. - downloadRemoteEntry stored the handle's base with filer-side uid/gid while every candidate it is later compared against is in local form, so under a non-identity UidGidMapper an unchanged re-delivery looked foreign and force-destroyed dirty pages. Map the base to local. - downloadRemoteEntry wrote the entry/base/version triple under only the handle's shared lock, so two concurrent reads of the same remote-only file could tear it. Serialize the install with a dedicated mutex (invalidation is already excluded by the exclusive handle lock). - A committed server-side copy whose readback failed adopted the FIRST event past the version gate as its base; a foreign write delivered first was silently swallowed. Adopt only an event whose content matches the synthesized base — the copy's own event — and install any other normally. - The deferred-create path relied on AcquireFileHandle installing the passed entry on a pre-existing handle, which the version rework dropped. Restore that install in the compat wrapper; the versioned open path keeps its gated install. Growth and hot-path cost: - Per-entry version records and tombstones leaked when a directory was evicted or read-through without a rebuild. An uncached directory gates its own inserts, so its records fence nothing; clear a directory's child version records when it is wiped for eviction. - FindEntry paid for the version KvGet on every lookup/getattr cache hit and threw it away. FindEntry now reads only the entry; the hot lookupEntry cache-hit path skips the version entirely. Cleanups: - Extract ackVersionTsNs over the shared response interface, replacing the metadata-event-else-log-ts snippet copy-pasted at four ack sites. - Extract acquireRenamePathLocks, replacing the verbatim sorted two-path lock fence in both rename handlers. * mount: no resurrection on foreign delete, version no-event acks, gate downloads, tighten copy adopt Follow-ups to the review patches: - Preserving dirty pages on a foreign delete let the next flush pass the isDeleted guard and CreateEntry, resurrecting the remotely-unlinked name. Mark the handle deleted in the vacate branch: the open fd can still read its buffered writes, but a flush no longer recreates the file. - A no-event acknowledgment (log fence only) synthesized a metadata event with TsNs 0, so the cache stored the entry unversioned and an older subscriber event rolled it back. Stamp the synthesized event with the ack's log position at all four ack sites. - downloadRemoteEntry serialized its install but did not check the version, so an older response arriving last overwrote the entry/base while the monotonic version kept the newer value, fencing corrections out. Install only when the response is at least as new as the handle. - sameEntryContent compared only size and chunks, so a foreign chmod with unchanged content was adopted as the copy's own event. Compare everything except server-assigned timestamps, so a metadata-only foreign change installs instead. * mount: trim comments to the non-obvious why The versioning work accumulated multi-line comment blocks restating what the code says. Keep the constraint a reader cannot derive — why a fence is exact, why a version must not advance without its value, why an uncached parent's records fence nothing — and drop the rest. * mount: distinguish rename from delete, tighten the download and adopt gates - A rename emits a nil old-path invalidation just like an unlink, so the vacate branch marked the handle deleted and later writes through the already-open descriptor were skipped instead of persisted. Carry the delete/rename distinction on the invalidation and mark only an actual delete. - The remote-download install accepted an unversioned response regardless of the handle's version, so during a rolling upgrade a delayed response could install stale content under a newer version. Require the response to be at least as new, with one exception: a handle still lacking local chunks takes the content anyway — it cannot read without it — but does not claim the response's log position. - Copy-event adoption returned without installing, so a foreign touch arriving before the copy's own event lost its timestamps. Content is unchanged either way, so the dirty pages stay valid; a clean handle now takes the entry, while a dirty one keeps its diverged version. * mount: one directory floor instead of a record per child; agree on TTL Review feedback: - Build completion wrote one KV record per direct child inside the cache write lock, so a large directory stalled every other cache operation for O(children) store writes. The directory's listing snapshot already covers every child it saw; make that floor the version for any child without a record of its own, and a child earns a record only when a later event touches it. One map write per build replaces the per-child writes, with the same fencing. - The presence probe read the store directly and so counted a TTL-expired entry as present, judging the path by a record describing content that has logically vanished. It now applies the same expiry the read path does, and an expired path falls back to its directory floor. - Preserve ErrNotFound identity when the commit-time re-read finds the object deleted, so callers still surface a 404. - Assert the rename-away source fence timestamp in the invalidation test. Also record the tombstone ceiling: distinct deleted names in a cached directory accumulate until it is rebuilt or evicted, which prunes everything at or below the new snapshot. * mount: pin the fence's clock domain instead of letting skew decide A log-position fence is stamped by one filer's clock under that filer's in-process lock, so comparing it to an event another filer logged is comparing two unrelated clocks. The two error directions are not equally costly: applying an event the fence already covered is a re-apply the base-equality check absorbs, while skipping one it does not cover leaves the handle holding exactly the state the event was meant to correct, with the subscription cursor already past it — the unhealable staleness this whole PR exists to remove. So refuse to guess. Fences now carry the signature of the filer that stamped them, and a handle records it alongside the position. An event is only fenced out when the filer that logged it is the one that stamped the fence — the logging filer appends its own signature, so its presence identifies the clock domain. Events from any other filer are applied. Positions taken from events keep comparing as before; the subscription already delivers those in order. The invalidation callback takes a struct now: it carries the path, entry, position, delete/rename distinction, and signatures, and was about to need a fifth positional parameter. * mount: follow a foreign rename; key page invalidation on content, not equality - A rename's old-path invalidation now carries the destination, and the handle follows the file there: an open fd tracks the inode, and leaving it on the old path made its next flush recreate that name instead of updating the renamed file. - Dirty pages overlay content, so only a content change invalidates them. Keying that on exact equality meant any timestamp-only event destroyed them, which the copy-adoption marker existed to paper over — a foreign touch could consume the marker and leave the copy's own event to drop the post-copy writes. Comparing content instead makes the marker unnecessary, so it is gone: a metadata-only event keeps the overlay, and a dirty handle keeps its diverged entry unless foreign content supersedes it. - A remote download response that is merely older is now refused even when the handle still lacks chunks; only an unversioned one is taken (and claims no position), since an older response's content predates what the handle reflects. - A refused or unversioned download no longer publishes to the metadata cache, where a zero-position event would clear the entry's version and let an older subscriber event roll the cache back. * mount: page invalidation keys on content alone; unversioned writes claim no position - sameEntryContent compared everything but timestamps, so a foreign chmod, chown, or xattr change counted as a content change and destroyed the dirty-page overlay. It was strict only to serve the copy-adoption marker, which is gone; its one caller now asks the question it actually needs — did the bytes change — so metadata-only events leave the overlay alone. - A rename over an existing file destroys that file, but its open handle was left live and still pointed at the name the renamed source now occupies, so its flush could overwrite it. MovePath already reports the displaced inode; mark that handle deleted. - An acknowledgment was refused whenever its position was numerically lower, even when a different filer stamped the fence it lost to. Two known, differing signatures mean unrelated clocks, so the comparison no longer applies there; unknown signatures still compare as before. - A local write with no log position behind it now records that explicitly instead of deleting its version record. Absence means the directory listing covers the path, which is why the snapshot floor applies; local content the listing never saw must not inherit it, or the events that would correct it are fenced out. * mount: widen the existing lookup functions instead of forking WithVersion twins The versioning work grew a parallel function for every accessor that needed to return a log position — lookupEntryWithVersion beside lookupEntry, maybeLoadEntryWithVersion beside maybeLoadEntry, FindEntryWithVersion beside FindEntry, AcquireFileHandleWithVersion beside AcquireFileHandle, advanceEntryVersion beside advanceEntryVersionTsNs, plus a getPbEntryWithVersion wrapper and an InsertListedEntriesForTest hook. Two names for one operation is two places to keep in step, and the split let callers pick the one that happened to compile. Each pair is now the single original name carrying the position, with callers that do not want it discarding it. filer_pb.GetEntry returns the fence its response already carried rather than a mount-side wrapper re-issuing the lookup, and InsertEntry takes the position its content reflects rather than a test-only twin that inserted without one. The one behavioural knot the merge exposed: AcquireFileHandle had been installing the entry on a pre-existing handle only in its unversioned form, which conflated 'the caller is authoritative' with 'the lookup had no version'. Deferred create is the only caller that means the former, so it now installs explicitly and the map function just acquires. |
||
|
|
490379bff3 |
Add codespell support with configuration and typo fixes (#10393)
* Add GitHub Actions workflow for codespell on master * Add rudimentary codespell config * Tune codespell config: skip generated code, ignore camelCase, whitelist domain terms Add camelCase/PascalCase regex to ignore common Go/Rust/JS identifiers like allLocations, publishErr, ReadInside, FlushInterval. Also skip templ-generated *_templ.go files, and whitelist a handful of short/domain-specific words (visibles, fo, te, ser, bject, unparseable, keep-alives, tread, anc, ue) that show up as false positives across the tree. Co-Authored-By: Claude Code 2.1.217 / Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Fix ambiguous typos and protect false positives Fixes typos that codespell reports with multiple candidate suggestions (so `codespell -w` cannot auto-apply them), plus one inline pragma and one config entry to protect legitimate identifiers. Manual fixes (single correct answer chosen from context): - pattens -> patterns (5x) in filer/upload/shell flag help strings - finded -> found (2x) in tarantool storage.lua comment - spacify -> specify (2x) in helm chart values.yaml comment - wether -> whether in skiplist.go docstring - simpe -> simple in mq schema test case name False-positive protection: - Add `//codespell:ignore` next to `source GET's` (possessive of HTTP verb) in s3api_object_handlers_copy_stream.go - Whitelist `auther` in .codespellrc — it's a local variable meaning "authenticator" in weed/security/tls.go, not a typo of "author". Co-Authored-By: Claude Code 2.1.217 / Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Extend codespell ignore list: .git-meta path and thirdparty groupId Also skip `.git-meta` (scratch dir for commit messages that may contain typo words verbatim) and whitelist `thirdparty` — it appears as the literal Maven groupId `org.apache.hadoop.thirdparty` in hdfs3 poms and cannot be renamed. Co-Authored-By: Claude Code 2.1.217 / Claude Opus 4.7 (1M context) <noreply@anthropic.com> * [DATALAD RUNCMD] Fix non-ambiguous typos with codespell -w Auto-applied fixes to the 44 remaining single-suggestion typos across docs, comments, log messages, tests, config, and one Java pom. === Do not change lines below === { "chain": [], "cmd": "uvx codespell -w", "exit": 0, "extra_inputs": [], "inputs": [], "outputs": [], "pwd": "." } ^^^ Do not change lines above ^^^ * Revert breaking codespell fixes; whitelist unknwon and atleast Two of the auto-applied `codespell -w` fixes were false positives that would break the build/tests: - go.mod: `github.com/unknwon/goconfig` is a real Go module path — the upstream author's GitHub handle is literally `unknwon`. Renaming to `unknown` would fail dependency resolution. - test/benchmark/fuse_db/bin/{sqlite_verify.py,run_mysql.sh,run_sqlite.sh}: `atleast` is a literal CLI mode value (a string constant compared and passed as a positional argument). Rewriting to `at least` splits it into two arguments and breaks the mode check. Reverted those files and whitelisted both words in .codespellrc so future runs won't re-suggest the same broken fixes. Co-Authored-By: Claude Code 2.1.217 / Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Code 2.1.217 / Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
bdcc3154ed |
refactor: centralize genUploadUrl in UploadOption (#10164)
* refactor: centralize genUploadUrl in UploadOption Replace inline genFileUrlFn closures with operation.GenUploadUrl field: - Add GenUploadUrl func(host, fileId) string to UploadOption struct - Add GenUploadUrlProxy(filerAddress string) utility function - Remove genFileUrlFn parameter from UploadWithRetry signature - Update all callers: mount, gateway, mq, filer_copy, filer_sync This matches the weed mount -filerProxy pattern exactly, factorizing the URL generation logic across all consumers. Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf) * docker release: run all platform jobs in one wave, cache rocksdb compile Drop max-parallel so the 13 per-platform builds run together instead of two waves of 8 (rocksdb was queuing behind the cap and starting ~8 min late). Keep cache-to mode=max for rocksdb: its RocksDB static_lib compile is sha-independent, so it caches across releases and stops being the ~16-min long-pole that gates the merge fan-in. go-build variants stay mode=min. Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf) * refactor: centralize genUploadUrl in UploadOption Replace inline genFileUrlFn closures with operation.GenUploadUrl field: - Add GenUploadUrl func(host, fileId) string to UploadOption struct - Add GenUploadUrlProxy(filerAddress string) utility function - Remove genFileUrlFn parameter from UploadWithRetry signature - Update all callers: mount, gateway, mq, filer_copy, filer_sync This matches the weed mount -filerProxy pattern exactly, factorizing the URL generation logic across all consumers. Co-Authored-By: Athena 🏛️ <hermes-agent@local> (custom / Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf) * Remove accidental ROCmFPX submodule reference * gofmt chunk upload option block * Preserve broker cipher and re-read proxy filer per upload attempt Chunk uploads must keep the configured Cipher, and both the mount and broker current filer can change on failover, so build the proxy upload URL inside the closure instead of capturing the address once. --------- Co-authored-by: Chris Lu <chris.lu@gmail.com> |
||
|
|
424cd164e9 |
s3: invalidate stale reader cache locations on chunk read failure (#10156)
* s3: invalidate stale reader cache locations on chunk read failure * filer: share the chunk-read self-heal across reader cache and streaming paths The reader cache retry added a third copy of the invalidate-relookup-compare-retry dance already inlined in PrepareStreamContentWithThrottler and duplicated in retryWithCacheInvalidation. Extract retryFetchWithFreshLocations and route all three through it, parameterized by the refetch primitive. * filer: drop redundant completedTimeNew store in reader cache success path startCaching already stamps completedTimeNew unconditionally before the fetchErr branch; the second store inside the success branch is dead. * filer: make NewReaderCache cache invalidator an explicit parameter The variadic ...CacheInvalidator only ever read the first element, so a caller could pass two and silently get one. Take a single explicit argument and have the non-S3 callers pass nil. * filer: inject reader cache chunk fetch as a struct field Replace the process-global readerCacheFetchChunkData test seam with a per-instance fetchChunkDataFn field defaulted in NewReaderCache, matching how lookupFileIdFn is already wired. Tests set the field on the cache instead of swapping a shared global. * filer: log the location count, not full URLs, on self-heal retry --------- Co-authored-by: Chris Lu <chris.lu@gmail.com> |
||
|
|
8701299baf |
mq(kafka): don't drop an existing topic when auto-create races (#9998)
TopicExists can return a transient false-negative for a topic that is in fact present (a broker/filer blip under load, or a just-created topic whose existence cache is still stale). The metadata and produce handlers then tried to auto-create, hit "topic already exists", treated that as a failure, and dropped the topic from the Metadata response - so the client saw a spurious UNKNOWN_TOPIC_OR_PARTITION right after the topic was created. Return a sentinel ErrTopicAlreadyExists from the create paths and add ensureTopicExists, which treats it as confirmation the topic exists. It also folds in the repeated TopicExists -> invalidate -> recheck -> create logic shared by every metadata handler (v0-v8) and both produce paths. v2+ produce now auto-creates too, matching the auto.create.topics.enable=true behavior the rest of the gateway already simulates. |
||
|
|
5a4ff2a122 |
fix(mq): don't cache topic non-existence on transient filer errors
TopicExists and getTopicConfFromCache negative-cached a topic for the full 30s TTL whenever a filer lookup failed for any reason, including timeouts. A topic created earlier then looked gone until the TTL expired, and the metadata auto-create path couldn't heal it (CreateTopic rejects an already-persisted conf), so producers saw UNKNOWN_TOPIC_OR_PARTITION. Only negative-cache on a definitive ErrNotFound; let transient errors fall through and retry against the filer. |
||
|
|
75c807b586 | chore(weed/mq/kafka/protocol): remove unused functions and variables (#9488) | ||
|
|
2212cc8a5f |
shell: expose retention flags on mq.topic.configure (#9416)
* shell: expose retention flags on mq.topic.configure
The ConfigureTopicRequest proto already carries a TopicRetention message
({retention_seconds, enabled}), and GetTopicConfigurationResponse / the
admin UI both surface it — but the `mq.topic.configure` shell command
sent Retention: nil unconditionally, leaving CLI and IaC users with no
way to set retention without going through the admin UI. Add three
flags so the shell matches the existing surface:
-retention <duration> Go duration string (e.g. 168h, 30m)
-retentionSeconds <int> raw seconds (mutually exclusive with -retention)
-retentionEnabled bool toggle for retention enforcement
Behavior:
- If none of the retention flags are set, the request omits Retention
(`nil`) — preserving the prior "leave server-side state alone"
semantics for callers that only care about partition count.
- Setting any retention flag populates TopicRetention with both fields
so existing operators keep working when only one is provided.
- -retention and -retentionSeconds together is a hard error (ambiguous);
negative values are rejected.
The new behavior is detected via flag.FlagSet.Visit so default values
of 0 / false are distinguishable from "not provided".
Help text updated with examples for both setting a TTL and disabling
retention on an existing topic. No proto / server changes needed; this
is a CLI-only patch.
* broker, shell: address review for mq.topic.configure retention
Three follow-up fixes for the review comments on the original commit:
1. Server-side: detect retention changes in the early-return path.
Previously ConfigureTopic returned without persisting when
partitionCount + schema were unchanged, even if the request supplied
a different Retention. Now the early-return branch checks both
schema and retention, persists either or both when they differ, and
logs which fields actually changed.
2. Server-side: preserve existing retention when request.Retention is
nil in the fresh-allocation path. Capture the prior resp.Retention
before overwriting `resp = &mq_pb.ConfigureTopicResponse{}`, and
only overwrite the new resp.Retention with `request.Retention` when
the request actually supplies one. Otherwise carry the previous
retention forward, so partition-count changes (or any path that
bypasses the early-return branch) don't accidentally clear retention.
3. CLI: switch the `-retention` / `-retentionSeconds` mutual-exclusion
check from value-based (`!= 0`) to flag.FlagSet.Visit-based, so an
explicit `-retention=0 -retentionSeconds=N` is also rejected.
4. CLI: when any retention flag is set, fetch the current
GetTopicConfiguration and fill in the fields the user didn't
explicitly provide. This means `-retentionEnabled` alone no longer
zeros the existing duration, and `-retention 24h` alone preserves
the existing enabled flag. When the topic doesn't exist yet, the
GetTopicConfiguration error is treated as "no current state" and
we proceed with just the user-supplied values.
Build / vet / gofmt / `go test ./weed/shell/... ./weed/mq/broker/...`
clean.
|
||
|
|
35e3fe89bc |
feat(s3/lifecycle): filer-backed cursor Persister + drop BlockerStore (#9358)
* feat(s3/lifecycle): filer-backed cursor Persister FilerPersister persists per-shard cursor maps as JSON to /etc/s3/lifecycle/cursors/shard-NN.json via filer.SaveInsideFiler. One file per shard keeps Save atomic — the filer writes the entry in a single mutation, so a crash mid-write doesn't leak partial state. Pipeline.Run loads on start; the periodic checkpoint and graceful-shutdown save go through this implementation. A small FilerStore interface wraps the SeaweedFilerClient surface the persister needs, so tests inject an in-memory fake instead of mocking the full gRPC client. * refactor(s3/lifecycle): drop BlockerStore — durable cursor IS the block A frozen cursor doesn't advance, so the durable cursor (FilerPersister) encodes the blocked state on its own. On worker restart the reader re-encounters the poison event at MinTsNs, the dispatcher walks the same retry budget to BLOCKED, and the cursor freezes at the same EventTs. Other in-flight events between freeze tsNs and prior cursor positions self-resolve via NOOP_RESOLVED (STALE_IDENTITY) since the underlying objects were already deleted on the prior pass. Removed: - BlockerStore interface + InMemoryBlockerStore + BlockerRecord - Dispatcher.Blockers + Dispatcher.ReplayBlockers - the BlockerStore.Put call in handleBlocked - Pipeline.Blockers field + the ReplayBlockers call on startup Added a TestDispatchRestartReFreezesNaturally that pins the self-recovery property: a fresh Dispatcher with a fresh Cursor, fed the same poison event, reaches the same frozen state at the same EventTs without any durable blocker store. Operator visibility: a cursor whose MinTsNs hasn't advanced is the signal — surfaced via the durable cursor file. * refactor(filer): SaveInsideFiler accepts ctx ReadInsideFiler already takes ctx; SaveInsideFiler used context.Background() internally and silently dropped the caller's ctx. Symmetric API now; cancellation/deadlines propagate through LookupEntry / CreateEntry / UpdateEntry. Mechanical update of all callers — most pass context.Background() since the existing call sites have no ctx in scope. * fix(s3/lifecycle): deterministic order in cursor save Iterating Go maps yields random order, so json.Encode produced a different byte sequence on each save even when the state hadn't changed. Sort entries by (Bucket, ActionKind, RuleHash) before encoding so the on-disk file diffs cleanly. New test pins byte-identical output across two saves of the same map. * fix(s3/lifecycle): log reason when freezing cursor in handleBlocked handleBlocked dropped the reason via _ = reason with a comment claiming the caller logged it; none of the three callers do. A frozen cursor is the only surface where the operator finds out something stuck, so the reason has to land somewhere. glog.Warningf with shard, key, eventTs, and the original reason — same shape the rest of the package uses. |
||
|
|
89b07f3e12 | chore(weed/mq/kafka/protocol): prune no-op test (#9287) | ||
|
|
02da928e25 | chore(weed/mq/kafka/protocol): prune dead code (#9288) |