mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
cd0f60a2f0858c07ea202b00ebf8df19e65a10a2
10
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
a963c1309c |
worker: purge the filer metadata log from a lifecycle job that keeps it past every TTL (#13101)
* worker: share the one-filer-per-store selection with other filer jobs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: add a meta_log_purge job that keeps the log past every TTL The job deletes whole metadata log days once per filer store, keeping every day that the longest filer.conf TTL, the longest S3 lifecycle rule, a registered retention floor or a running replay job's cursor still needs. A floor input that cannot be read stops the run before anything is deleted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: register meta_log_purge in the lifecycle lane Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * maintenance: stop purging the metadata log from the default scripts The meta_log_purge job now deletes old log days, keeping what TTLs, lifecycle rules and replay jobs still need. fs.log.purge stays for manual use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: let an idle filer_ttl rule's read position release the log filer_ttl no longer needs events up to read_ns, and an idle rule keeps an old ts_ns while read_ns advances, so the floor follows the later of the two. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: cap min_retention_days so a huge value cannot overflow Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: show the min_retention_days limit in the admin form Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: give a registered retention floor the store's filer client A floor that only gets a context cannot tell which cluster or store it answers for, so it cannot ask that cluster's master or read the store's own settings. Pass the filer client the job already holds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep the log an unfinished lifecycle walk will replay A cold-start or recovery walk that resumes across runs rewinds its shard cursor to the walk's start minus the longest lifecycle TTL once it completes. Until then only its walk checkpoint records that start, so a walk running for more than a day let the purge delete the creation events the rewound replay reads. A checkpoint with buckets done or partly walked now holds the floor at started_ns minus that TTL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: hold the walk start until the checkpoint goes stale A walk clears its checkpoint in finish() before each of its shards saves the rewound cursor, so a purge scan that read the old shard cursor and then the cleared checkpoint saw neither. A cleared checkpoint keeps started_ns, so every live checkpoint now holds the floor at its start minus the longest lifecycle TTL. A finished one stops holding once it has not been saved for cursorStaleAfter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: read walk checkpoints before the shard cursors they rewind A purge scan that read a shard cursor, then a checkpoint that a later walk had already replaced, saw neither the earlier walk's hold nor the rewind its shards saved. A walk replaces its checkpoint only after the previous walk's rewind is on disk, so reading the checkpoints first always sees one of the two. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lifecycle: save a fresh walk's checkpoint at its first progress A walk that progressed during its first save interval and then stalled for more than a day had no checkpoint on disk, so the metadata log purge saw nothing holding the days its completion replays. A fresh walk now saves on its first finished entry or bucket; a resumed walk already has its record on disk and keeps the interval. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lifecycle: rewrite an unchanged shard cursor so its mtime stays fresh A shard stuck on RETRY_LATER saved identical bytes each pass, and SaveInsideFiler skips identical content, so the file's mtime aged past the meta log purge's staleness cutoff while the shard still needed it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep the log day a reader from the cursor lists first Log files are named for their flush start, so a file from just before midnight holds events after a cursor just past it. The reader backs off one flush interval before choosing its first day; the purge now does too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: stop the meta log purge on an unreadable lifecycle policy LoadCompileInputs reports a bucket whose lifecycle XML does not parse separately from its error, so the purge used the shorter floors and deleted days that bucket's rules may need once the policy is fixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: read shard cursors with the replay's loader in the meta log purge A shard cursor the replay refuses, such as an empty object, decoded as a zero position and released the purge; it now stops the run instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: saturate the meta log purge's TTL plus a day A lifecycle TTL near the largest duration wrapped negative once a day was added, so the purge fell back to the shorter floors; the walk hold at started_ns minus that TTL likewise dropped below zero and was lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: leave disabled lifecycle rules out of the meta log purge floor AllActivePriorStates activates every compiled rule, so a disabled rule still held the log for its TTL, and disabling it could not release it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: compute the meta log purge floor in SafeKeepFrom Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * shell: fs.log.purge keeps the logs the meta log purge floor needs unless -force Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * shell: run the fs.log.purge floor test without a master client Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4ff3147ee5 |
worker: filer_ttl job removes expired rows from stores without native TTL (#13084)
* worker: add a filer_ttl job that walks filer.conf TTL paths A filer store without native TTL keeps the rows of expired entries until something looks them up or lists their directory. The job lists every TTL path subtree once per filer store, so the filer drops the expired rows it meets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: register the filer_ttl job in the lifecycle lane Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: re-check an expired entry under its path lock before a listing deletes it A listing deleted the expired entries it collected by path after the page was read, so a write that replaced one in between lost its new row. The delete now re-reads the row under the lock writers take, and in one conflict-checked transaction on stores that refuse a commit over another writer's change; anything but a still-expired row is kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: read each filer store's own filer.conf, chunk-backed included Filers with separate stores keep separate filer.conf files, so one filer's rules could hide another store's TTL paths. A config stored in chunks read as empty. An unreadable config now fails the detection instead of reading as no rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * command: count filer_ttl among the mini default job types Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: resume an unfinished filer_ttl walk from its checkpoint The walk position is saved in the job's filer store every 30s and at the first failure, keyed by store signature, and cleared when a pass completes. The next run skips the prefixes and subtrees already walked, unless the TTL prefix set changed or the pass is over 7 days old. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: save the filer_ttl checkpoint as soon as a walk fails The first failure froze the checkpoint but only the end of the run saved it, so a worker killed while walking later prefixes lost it. stop now saves it at once; the end of the run saves again only if that save failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep a path TTL rule from expiring the filer_ttl checkpoint A filer.conf TTL rule over /etc/ gave the checkpoint that rule's TTL, so an interrupted pass could lose its record long before checkpointMaxAge. The checkpoint is now written with its own TTL of checkpointMaxAge, which the filer keeps instead of the rule's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: remove a filer_ttl checkpoint the new pass will not resume from An overwrite keeps the stored entry's Crtime, and the checkpoint's TTL counts from it, so a pass that replaced a rejected record could lose its own record before checkpointMaxAge. load now deletes a record it rejects, and the new pass creates a fresh one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: expire filer_ttl entries from metadata events per TTL rule Each run replays every filer.conf TTL rule's metadata events from that rule's cursor up to the run start, and looks up each entry whose TTL has passed so the filer removes its row. The first entry not yet due holds the rule's cursor, so a later run replays it. A rule without a cursor, or whose TTL changed, is listed once to reach rows older than its replay window. The periodic full walk and its checkpoint are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: re-check an S3-expired entry under its path lock before a listing deletes it A listing deleted an S3-expired object by the row it had read, so an upload that replaced it after the page was read was removed. The delete now re-reads the row under the path lock and removes it only if it is still S3-expired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: remove an expired row a lookup meets in a conflict-checked transaction A lookup that met an expired row deleted it by path, so a replacement written through another filer between the read and the delete was lost, even on stores that refuse conflicting commits; a failed delete was hidden behind not found. The lookup now re-reads and deletes through deleteIfExpired and returns the delete error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep a failed filer_ttl lookup that ties a done event When the first event at a timestamp was done and the second one's lookup failed, the cursor already stood at that timestamp, so the retry subscribed after it and skipped the failed event. A failed lookup now holds the cursor below a tie, as a waiting entry does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: hold a filer_ttl event whose entry the filer still serves A lookup that returned the live entry counted as done, so when the worker's clock ran ahead of the filer's near the deadline the event was skipped and the row stayed. An entry the filer still serves with the same deadline now holds the cursor like one not yet due. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep a path TTL rule from expiring the filer_ttl cursors The cursors were written without a TTL, so a filer.conf TTL rule covering /etc/seaweedfs/filer_ttl gave them the rule's TTL and every rule was listed again once they expired. When a rule covers them they are now written with a TTL of their own, which the filer keeps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: list a filer_ttl rule again for a live entry its replay cannot reach A new rule nested under a longer one started its replay one TTL back, so a live entry the enclosing rule had stamped with its longer TTL, written before that, was in neither rule's replay: the nested rule now owns it and the enclosing rule skips it. The listing of a new rule now records the earliest deadline of such entries, and the rule is listed again then. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: hand a removed filer_ttl rule's replay to the rule enclosing it When a nested rule was removed, its entries became the enclosing rule's, but that rule's cursor could already be past their events, so they were never replayed. The enclosing rule now replays from the earlier of both cursors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: list a filer_ttl rule whose unfinished events the filer no longer keeps When fs.log.purge removed the event of an entry still waiting for its TTL, the rule's cursor matched, so the rule was never listed and the replay never met the entry again. A rule whose cursor is older than the oldest kept metadata log is now listed, and its cursor moves to that log. The cursor also records how far a replay read with nothing left waiting, so a quiet rule is not listed just because old logs were purged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: leave S3 lifecycle expiry to the s3_lifecycle job in filer_ttl An entry whose TTL an S3 lifecycle rule set carries the S3 expiry flag; s3_lifecycle evaluates and removes it. filer_ttl no longer looks such entries up, and their deadline no longer holds a TTL rule's cursor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
05d31a04b6 |
fix(s3tests): wire lifecycle worker for expiration suite (#9374)
* fix(s3tests): wire lifecycle worker for expiration suite
The upstream s3-tests `test_lifecycle_expiration` / `test_lifecyclev2_expiration`
exercise the "set rule, wait, verify deletion" path. Phase 4 (#9367) intentionally
stripped the PUT-time back-stamp, so pre-existing objects no longer pick up TtlSec
on a freshly-applied rule. The s3tests CI bare-bones `weed -s3` had nothing left
driving expiration.
Three changes that work together:
- Engine scales `Days` by `util.LifeCycleInterval`. Production keeps the 24h day;
the `s3tests` build tag shrinks it to 10s so a `Days: 1` rule completes inside
the suite's 30s polling window. Exported `DaysToDuration` so sibling-package
tests pin to the same scale.
- Scheduler/dispatcher tick defaults split into `_default` / `_s3tests` files.
Production stays 5s/30s/5m; the test build runs at 500ms/2s/2s so deletions
land within a couple ticks of becoming due.
- s3tests.yml spawns `weed shell s3.lifecycle.run-shard -shards 0-15 -events 0
-runtime 1800s` alongside the s3 server in both the basic and SQL blocks; the
shell command runs the full pipeline (reader + scheduler + dispatcher) for the
duration of the suite. `test_lifecycle_expiration_versioning_enabled` is left
out for now — versioned-bucket expiration via the worker still needs its own
pass.
Drive-by: bump `TestWorkerDefaultJobTypes` to 7 to match the registered
handler count (
|
||
|
|
1f6f473995 |
refactor(worker): co-locate plugin handlers with their task packages (#9301)
* refactor(worker): co-locate plugin handlers with their task packages
Move every per-task plugin handler from weed/plugin/worker/ into the
matching weed/worker/tasks/<name>/ package, so each task owns its
detection, scheduling, execution, and plugin handler in one place.
Step 0 (within pluginworker, no behavior change): extract shared helpers
that previously lived inside individual handler files into dedicated
files and export the ones now consumed across packages.
- activity.go: BuildExecutorActivity, BuildDetectorActivity
- config.go: ReadStringConfig/Double/Int64/Bytes/StringList, MapTaskPriority
- interval.go: ShouldSkipDetectionByInterval
- volume_state.go: VolumeState + consts, FilterMetricsByVolumeState/Location
- collection_filter.go: CollectionFilterMode + consts
- volume_metrics.go: export CollectVolumeMetricsFromMasters,
MasterAddressCandidates, FetchVolumeList
- testing_senders_test.go: shared test stubs
Phase 1: move the per-task plugin handlers (and the iceberg subpackage)
into their task packages.
weed/plugin/worker/vacuum_handler.go -> weed/worker/tasks/vacuum/plugin_handler.go
weed/plugin/worker/ec_balance_handler.go -> weed/worker/tasks/ec_balance/plugin_handler.go
weed/plugin/worker/erasure_coding_handler.go -> weed/worker/tasks/erasure_coding/plugin_handler.go
weed/plugin/worker/volume_balance_handler.go -> weed/worker/tasks/balance/plugin_handler.go
weed/plugin/worker/iceberg/ -> weed/worker/tasks/iceberg/
weed/plugin/worker/handlers/handlers.go now blank-imports all five
task subpackages so their init() registrations fire.
weed/command/mini.go and the worker tests construct the handler with
vacuum.DefaultMaxExecutionConcurrency (the constant moved with the
vacuum handler).
admin_script remains in weed/plugin/worker/ because there is no
underlying weed/worker/tasks/admin_script/ package to merge with.
* refactor(worker): update test/plugin_workers imports for moved handlers
Three handler constructors moved out of pluginworker into their task
packages — update the integration test files in test/plugin_workers/
to import from the new locations:
pluginworker.NewVacuumHandler -> vacuum.NewVacuumHandler
pluginworker.NewVolumeBalanceHandler -> balance.NewVolumeBalanceHandler
pluginworker.NewErasureCodingHandler -> erasure_coding.NewErasureCodingHandler
The pluginworker import is kept where the file still uses
pluginworker.WorkerOptions / pluginworker.JobHandler.
* refactor(worker): update test/s3tables iceberg import path
The iceberg subpackage moved from weed/plugin/worker/iceberg/ to
weed/worker/tasks/iceberg/. test/s3tables/maintenance/maintenance_integration_test.go
still imported the old path, breaking S3 Tables / RisingWave / Trino /
Spark / Iceberg-catalog / STS integration test builds.
Mirrors the OSS-side fix needed by every job in the run that
transitively imports test/s3tables/maintenance.
* chore: gofmt PR-touched files
The S3 Tables Format Check job runs `gofmt -l` over weed/s3api/s3tables
and test/s3tables, then fails if anything is unformatted. Files this
PR moved or modified had import-grouping and trailing-spacing issues
introduced by perl-based renames; reformat them with gofmt -w.
Touched files:
test/plugin_workers/erasure_coding/{detection,execution}_test.go
test/s3tables/maintenance/maintenance_integration_test.go
weed/plugin/worker/handlers/handlers.go
weed/worker/tasks/{balance,ec_balance,erasure_coding,vacuum}/plugin_handler*.go
* refactor(worker): bounds-checked int conversions for plugin config values
CodeQL flagged 18 go/incorrect-integer-conversion warnings on the moved
plugin handler files: results of pluginworker.ReadInt64Config (which
ultimately calls strconv.ParseInt with bit size 64) were being narrowed
to int32/uint32/int without an upper-bound check, so a malicious or
malformed admin/worker config value could overflow the target type.
Add three helpers in weed/plugin/worker/config.go that wrap
ReadInt64Config and clamp out-of-range values back to the caller's
fallback:
ReadInt32Config (math.MinInt32 .. math.MaxInt32)
ReadUint32Config (0 .. math.MaxUint32)
ReadIntConfig (math.MinInt32 .. math.MaxInt32, platform-portable)
Update each flagged call site in the four moved task packages to use
the bounds-checked helper. For protobuf uint32 fields (volume IDs)
the variable type also becomes uint32, removing the trailing
uint32(volumeID) casts and changing the "missing volume_id" check
from `<= 0` to `== 0`.
Touched files:
weed/plugin/worker/config.go
weed/worker/tasks/balance/plugin_handler.go
weed/worker/tasks/erasure_coding/plugin_handler.go
weed/worker/tasks/vacuum/plugin_handler.go
* refactor(worker): use ReadIntConfig for clamped derive-worker-config helpers
CodeQL still flagged three call sites where ReadInt64Config was being
narrowed to int after a value-range clamp (max_concurrent_moves <= 50,
batch_size <= 100, min_server_count >= 2). The clamp is correct but
CodeQL's flow analysis didn't recognize the bound, so it flagged them
as unbounded narrowing.
Switch to ReadIntConfig (already int32-bounded by the helper) for
those three sites, drop the now-redundant int64 intermediate variables.
Also drops the now-unused `> math.MaxInt32` clamp in
ec_balance.deriveECBalanceWorkerConfig (the helper covers it).
|
||
|
|
a838661b83 |
feat(plugin): EC shard balance handler for plugin worker (#8629)
* feat(ec_balance): add TaskTypeECBalance constant and protobuf definitions Add the ec_balance task type constant to both topology and worker type systems. Define EcBalanceTaskParams, EcShardMoveSpec, and EcBalanceTaskConfig protobuf messages for EC shard balance operations. * feat(ec_balance): add configuration for EC shard balance task Config includes imbalance threshold, min server count, collection filter, disk type, and preferred tags for tag-aware placement. * feat(ec_balance): add multi-phase EC shard balance detection algorithm Implements four detection phases adapted from the ec.balance shell command: 1. Duplicate shard detection and removal proposals 2. Cross-rack shard distribution balancing 3. Within-rack node-level shard balancing 4. Global shard count equalization across nodes Detection is side-effect-free: it builds an EC topology view from ActiveTopology and generates move proposals without executing them. * feat(ec_balance): add EC shard move task execution Implements the shard move sequence using the same VolumeEcShardsCopy, VolumeEcShardsMount, VolumeEcShardsUnmount, and VolumeEcShardsDelete RPCs as the shell ec.balance command. Supports both regular shard moves and dedup-phase deletions (unmount+delete without copy). * feat(ec_balance): add task registration and scheduling Register EC balance task definition with auto-config update support. Scheduling respects max concurrent limits and worker capabilities. * feat(ec_balance): add plugin handler for EC shard balance Implements the full plugin handler with detection, execution, admin and worker config forms, proposal building, and decision trace reporting. Supports collection/DC/disk type filtering, preferred tag placement, and configurable detection intervals. Auto-registered via init() with the handler registry. * test(ec_balance): add tests for detection algorithm and plugin handler Detection tests cover: duplicate shard detection, cross-rack imbalance, within-rack imbalance, global rebalancing, topology building, collection filtering, and edge cases. Handler tests cover: config derivation with clamping, proposal building, protobuf encode/decode round-trip, fallback parameter decoding, capability, and config policy round-trip. * fix(ec_balance): address PR review feedback and fix CI test failure - Update TestWorkerDefaultJobTypes to expect 6 handlers (was 5) - Extract threshold constants (ecBalanceMinImbalanceThreshold, etc.) to eliminate magic numbers in Descriptor and config derivation - Remove duplicate ShardIdsToUint32 helper (use erasure_coding package) - Add bounds checks for int64→int/uint32 conversions to fix CodeQL integer conversion warnings * fix(ec_balance): address code review findings storage_impact.go: - Add TaskTypeECBalance case returning shard-level reservation (ShardSlots: -1/+1) instead of falling through to default which incorrectly reserves a full volume slot on target. detection.go: - Use dc:rack composite key to avoid cross-DC rack name collisions. Only create rack entries after confirming node has matching disks. - Add exceedsImbalanceThreshold check to cross-rack, within-rack, and global phases so trivial skews below the configured threshold are ignored. Dedup phase always runs since duplicates are errors. - Reserve destination capacity after each planned move (decrement destNode.freeSlots, update rackShardCount/nodeShardCount) to prevent overbooking the same destination. - Skip nodes with freeSlots <= 0 when selecting minNode in global balance to avoid proposing moves to full nodes. - Include loop index and source/target node IDs in TaskID to guarantee uniqueness across moves with the same volumeID/shardID. ec_balance_handler.go: - Fail fast with error when shard_id is absent in fallback parameter decoding instead of silently defaulting to shard 0. ec_balance_task.go: - Delegate GetProgress() to BaseTask.GetProgress() so progress updates from ReportProgressWithStage are visible to callers. - Add fail-fast guard rejecting multiple sources/targets until batch execution is implemented. Findings verified but not changed (matches existing codebase pattern in vacuum/balance/erasure_coding handlers): - register.go globalTaskDef.Config race: same unsynchronized pattern in all 4 task packages. - CreateTask using generated ID: same fmt.Sprintf pattern in all 4 task packages. * fix(ec_balance): harden parameter decoding, progress tracking, and validation ec_balance_handler.go (decodeECBalanceTaskParams): - Validate execution-critical fields (Sources[0].Node, ShardIds, Targets[0].Node, ShardIds) after protobuf deserialization. - Require source_disk_id and target_disk_id in legacy fallback path so Targets[0].DiskId is populated for VolumeEcShardsCopyRequest. - All error messages reference decodeECBalanceTaskParams and the specific missing field (TaskParams, shard_id, Targets[0].DiskId, EcBalanceTaskParams) for debuggability. ec_balance_task.go: - Track progress in ECBalanceTask.progress field, updated via reportProgress() helper called before ReportProgressWithStage(), so GetProgress() returns real stage progress instead of stale 0. - Validate: require exactly 1 source and 1 target (mirrors Execute guard), require ShardIds on both, with error messages referencing ECBalanceTask.Validate and the specific field. * fix(ec_balance): fix dedup execution path, stale topology, collection filter, timeout, and dedupeKey detection.go: - Dedup moves now set target=source so isDedupPhase() triggers the unmount+delete-only execution path instead of attempting a copy. - Apply moves to in-memory topology between phases via applyMovesToTopology() so subsequent phases see updated shard placement and don't conflict with already-planned moves. - detectGlobalImbalance now accepts allowedVids and filters both shard counting and shard selection to respect CollectionFilter. ec_balance_task.go: - Apply EcBalanceTaskParams.TimeoutSeconds to the context via context.WithTimeout so all RPC operations respect the configured timeout instead of hanging indefinitely. ec_balance_handler.go: - Include source node ID in dedupeKey so dedup deletions from different source nodes for the same shard aren't collapsed. - Clamp minServerCountRaw and minIntervalRaw lower bounds on int64 before narrowing to int, preventing undefined overflow on 32-bit. * fix(ec_balance): log warning before cancelling on progress send failure Log the error, job ID, job type, progress percentage, and stage before calling execCancel() in the progress callback so failed progress sends are diagnosable instead of silently cancelling. |
||
|
|
587c24ec89 |
plugin worker: support job type categories (all, default, heavy) (#8547)
* plugin worker: add handler registry with job categories
Introduce a self-registration pattern for plugin worker job handlers.
Each handler can register itself via init() with a HandlerFactory that
declares its job type, category (default/heavy), CLI aliases, and a
builder function.
ResolveHandlerFactories accepts a mix of category names ("all",
"default", "heavy") and explicit job type names/aliases, returning the
matching factories. This enables workers to be configured by resource
profile rather than requiring explicit job type enumeration.
* plugin worker: register all handlers via init()
Each job handler now self-registers into the global handler registry
with its canonical job type, category, CLI aliases, and build function:
- vacuum: category=default
- volume_balance: category=default
- admin_script: category=default
- erasure_coding: category=heavy
- iceberg_maintenance: category=heavy
Adding a new job type now only requires adding the init() call in the
handler file itself — no other files need to be touched.
* plugin worker: replace hardcoded job type switch with registry
Remove buildPluginWorkerHandler, parsePluginWorkerJobTypes, and
canonicalPluginWorkerJobType from worker_runtime.go. The simplified
buildPluginWorkerHandlers now delegates to
pluginworker.ResolveHandlerFactories, which resolves category names
("all", "default", "heavy") and explicit job type names/aliases.
The default job type is changed from an explicit list to "all", so new
handlers registered via init() are automatically picked up.
Update all tests to use the new API.
* plugin worker: update CLI help text for job categories
Update the -jobType flag description and command examples to document
category support (all, default, heavy) alongside explicit job type names.
* plugin worker: address review feedback
- Add CategoryAll constant; use typed constants in tokenAsCategory
- Pre-allocate result slice in ResolveHandlerFactories
- Add vacuum aliases (vol.vacuum, volume.vacuum)
- List alias examples (ec, balance, iceberg) in -jobType flag help
- Create handlers aggregator package for subpackage blank imports so
new handler subpackages only need to be added in one place
- Make category tests relationship-based (subset/union checks) instead
of asserting exact handler counts
- Add clarifying comments to worker_test.go and mini_plugin_test.go
listing expected handler names next to count assertions
---------
Co-authored-by: Copilot <copilot@github.com>
|
||
|
|
72c2c7ef8b |
Add iceberg_maintenance plugin worker handler (Phase 1) (#8501)
* Add iceberg_maintenance plugin worker handler (Phase 1) Implement automated Iceberg table maintenance as a new plugin worker job type. The handler scans S3 table buckets for tables needing maintenance and executes operations in the correct Iceberg order: expire snapshots, remove orphan files, and rewrite manifests. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix unsafe int64→int narrowing for MaxSnapshotsToKeep Use int64(wouldKeep) instead of int(config.MaxSnapshotsToKeep) to avoid potential truncation on 32-bit platforms (CodeQL high severity). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix unsafe int64→int narrowing for MinInputFiles Use int64(len(manifests)) instead of int(config.MinInputFiles) to avoid potential truncation on 32-bit platforms (CodeQL high severity). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix unsafe int64→int narrowing for MaxCommitRetries Clamp MaxCommitRetries to [1,20] range and keep as int64 throughout the retry loop to avoid truncation on 32-bit platforms (CodeQL high severity). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Sort snapshots explicitly by timestamp in expireSnapshots The previous logic relied on implicit ordering of the snapshot list. Now explicitly sorts snapshots by timestamp descending (most recent first) and uses a simpler keep-count loop: keep the first MaxSnapshotsToKeep newest snapshots plus the current snapshot unconditionally, then expire the rest that exceed the retention window. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Handle errors properly in listFilerEntries Previously all errors from ListEntries and Recv were silently swallowed. Now: treat "not found" errors as empty directory, propagate other ListEntries errors, and check for io.EOF explicitly on Recv instead of breaking on any error. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix overly broad HasSuffix check in orphan detection The bare strings.HasSuffix(ref, entry.Name) could match files with similar suffixes (e.g. "123.avro" matching "snap-123.avro"). Replaced with exact relPath match and a "/"-prefixed suffix check to avoid false positives. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Replace fmt.Sscanf with strconv.Atoi in extractMetadataVersion strconv.Atoi is more explicit and less fragile than fmt.Sscanf for parsing a simple integer from a trimmed string. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Recursively traverse directories for orphan file detection The orphan cleanup only listed a single directory level under data/ and metadata/, skipping IsDirectory entries. Partitioned Iceberg tables store data files in nested partition directories (e.g. data/region=us-east/file.parquet) which were never evaluated. Add walkFilerEntries helper that recursively descends into subdirectories, and use it in removeOrphans so all nested files are considered for orphan checks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix manifest path drift from double time.Now() calls rewriteManifests called time.Now().UnixMilli() twice: once for the path embedded in WriteManifest and once for the filename passed to saveFilerFile. These timestamps would differ, causing the manifest's internal path reference to not match the actual saved filename. Compute the filename once and reuse it for both WriteManifest and saveFilerFile so they always reference the same path. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add TestManifestRewritePathConsistency test Verifies that WriteManifest returns a ManifestFile whose FilePath() matches the path passed in, and that path.Base() of that path matches the filename used for saveFilerFile. This validates the single- timestamp pattern used in rewriteManifests produces consistent paths. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Make parseOperations return error on unknown operations Previously parseOperations silently dropped unknown operation names and could return an empty list. Now validates inputs against the canonical set and returns a clear error if any unknown operation is specified. Updated Execute to surface the error instead of proceeding with an empty operation list. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Use gRPC status codes instead of string matching in listFilerEntries Replace brittle strings.Contains(err.Error(), "not found") check with status.Code(err) == codes.NotFound for proper gRPC error handling. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add stale-plan guard in commit closures for expireSnapshots and rewriteManifests Both operations plan outside the commit mutation using a snapshot ID captured from the initial metadata read. If the table head advances concurrently, the mutation would create a snapshot parented to the wrong head or remove snapshots based on a stale view. Add a guard inside each mutation closure that verifies currentMeta.CurrentSnapshot().SnapshotID still matches the planned snapshot ID. If it differs, return errStalePlan which propagates immediately (not retried, since the plan itself is invalid). Also fix rewriteManifests to derive SequenceNumber from the fresh metadata (cs.SequenceNumber) instead of the captured currentSnap. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add compare-and-swap to updateTableMetadataXattr updateTableMetadataXattr previously re-read the entry but did not verify the metadataVersion matched what commitWithRetry had loaded. A concurrent update could be silently clobbered. Now accepts expectedVersion parameter and compares it against the stored metadataVersion before writing. Returns errMetadataVersionConflict on mismatch, which commitWithRetry treats as retryable (deletes the staged metadata file and retries with fresh state). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Export shared plugin worker helpers for use by sub-packages Export ShouldSkipDetectionByInterval, BuildExecutorActivity, and BuildDetectorActivity so the iceberg sub-package can reuse them without duplicating logic. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Refactor iceberg maintenance handler into weed/plugin/worker/iceberg package Split the 1432-line iceberg_maintenance_handler.go into focused files in a new iceberg sub-package: handler.go, config.go, detection.go, operations.go, filer_io.go, and compact.go (Phase 2 data compaction). Key changes: - Rename types to drop stutter (IcebergMaintenanceHandler → Handler, etc.) - Fix loadFileByIcebergPath to preserve nested directory paths via normalizeIcebergPath instead of path.Base which dropped subdirectories - Check SendProgress errors instead of discarding them - Add stale-plan guard to compactDataFiles commitWithRetry closure - Add "compact" operation to parseOperations canonical order - Duplicate readStringConfig/readInt64Config helpers (~20 lines) - Update worker_runtime.go to import new iceberg sub-package Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Remove iceberg_maintenance from default plugin worker job types Iceberg maintenance is not yet ready to be enabled by default. Workers can still opt in by explicitly listing iceberg_maintenance in their job types configuration. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Clamp config values to safe minimums in ParseConfig Prevents misconfiguration by enforcing minimum values using the default constants for all config fields. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Harden filer I/O: path helpers, strict CAS guard, path traversal prevention - Use path.Dir/path.Base instead of strings.SplitN in loadCurrentMetadata - Make CAS guard error on missing or unparseable metadataVersion - Add path.Clean and traversal validation in loadFileByIcebergPath Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix compact: single snapshot ID, oversized bin splitting, ensureFilerDir - Use single newSnapID for all manifest entries in a compaction run - Add splitOversizedBin to break bins exceeding targetSize - Make ensureFilerDir only create on NotFound, propagate other errors Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Add wildcard filters, scan limit, and context cancellation to table scanning - Use wildcard matchers (*, ?) for bucket/namespace/table filters - Add limit parameter to scanTablesForMaintenance for early termination - Add ctx.Done() checks in bucket and namespace scan loops - Update filter UI descriptions and placeholders for wildcard support Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Remove dead detection interval check and validate namespace parameter - Remove ineffective ShouldSkipDetectionByInterval call with hardcoded 0 - Add namespace to required parameter validation in Execute Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Improve operations: exponential backoff, orphan matching, full file cleanup - Use exponential backoff (50ms, 100ms, 200ms, ...) in commitWithRetry - Use normalizeIcebergPath for orphan matching instead of fragile suffix check - Add collectSnapshotFiles to traverse manifest lists → manifests → data files - Delete all unreferenced files after expiring snapshots, not just manifest lists - Refactor removeOrphans to reuse collectSnapshotFiles Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * iceberg: fix ensureFilerDir to handle filer_pb.ErrNotFound sentinel filer_pb.LookupEntry converts gRPC NotFound errors to filer_pb.ErrNotFound (a plain sentinel), so status.Code() never returns codes.NotFound for that error. This caused ensureFilerDir to return an error instead of creating the directory when it didn't exist. * iceberg: clean up orphaned artifacts when compaction commit fails Track all files written during compaction (merged data files, manifest, manifest list) and delete them if the commit or any subsequent write step fails, preventing orphaned files from accumulating in the filer. * iceberg: derive tablePath from namespace/tableName when empty An empty table_path parameter would be passed to maintenance operations unchecked. Default it to path.Join(namespace, tableName) when not provided. * iceberg: make collectSnapshotFiles return error on read/parse failure Previously, errors reading manifests were logged and skipped, returning a partial reference set. This could cause incorrect delete decisions during snapshot expiration or orphan cleanup. Now the function returns an error and all callers abort when reference data is incomplete. * iceberg: include active metadata file in removeOrphans referenced set The metadataFileName returned by loadCurrentMetadata was discarded, so the active metadata file could be incorrectly treated as an orphan and deleted. Capture it and add it to the referencedFiles map. * iceberg: only retry commitWithRetry on metadata version conflicts Previously all errors from updateTableMetadataXattr triggered retries. Now only errMetadataVersionConflict causes retry; other errors (permissions, transport, malformed xattr) fail immediately. * iceberg: respect req.Limit in fakeFilerServer.ListEntries mock The mock ListEntries ignored the Limit field, so tests couldn't exercise pagination. Now it stops streaming once Limit entries have been sent. * iceberg: validate parquet schema compatibility before merging files mergeParquetFiles now compares each source file's schema against the first file's schema and aborts with a clear error if they differ, instead of blindly writing rows that could panic or produce corrupt output. * iceberg: normalize empty JobType to canonical jobType in Execute events When request.Job.JobType is empty, status events and completion messages were emitted with a blank job type. Derive a canonical value early and use it consistently in all outbound events. * iceberg: log warning on unexpected config value types in read helpers readStringConfig and readInt64Config now log a V(1) warning when they encounter an unhandled ConfigValue kind, aiding debugging of unexpected config types that silently fall back to defaults. * worker: add iceberg_maintenance to default plugin worker job types Workers using the default job types list didn't advertise the iceberg_maintenance handler despite the handler and canonical name being registered. Add it so workers pick up the handler by default. * iceberg: use defer and detached context for compaction artifact cleanup The cleanup closure used the job context which could already be canceled, and was not called on ctx.Done() early exits. Switch to a deferred cleanup with a detached context (30s timeout) so artifact deletion completes on all exit paths including context cancellation. * iceberg: use proportional jitter in commitWithRetry backoff Fixed 25ms max jitter becomes insignificant at higher retry attempts. Use 0-20% of the current backoff value instead so jitter scales with the exponential delay. * iceberg: add malformed filename cases to extractMetadataVersion test Cover edge cases like "invalid.metadata.json", "metadata.json", "", and "v.metadata.json" to ensure the function returns 0 for unparseable inputs. * iceberg: fail compaction on manifest read errors and skip delete manifests Previously, unreadable manifests were silently skipped during compaction, which could drop live files from the entry set. Now manifest read/parse errors are returned as fatal errors. Also abort compaction when delete manifests exist since the compactor does not apply deletes — carrying them through unchanged could produce incorrect results. * iceberg: use table-relative path for active metadata file in orphan scan metadataFileName was stored as a basename (e.g. "v1.metadata.json") but the orphan scanner matches against table-relative paths like "metadata/v1.metadata.json". Prefix with "metadata/" so the active metadata file is correctly recognized as referenced. * iceberg: fix MetadataBuilderFromBase location to use metadata file path The second argument to MetadataBuilderFromBase records the previous metadata file in the metadata log. Using meta.Location() (the table root) was incorrect — it must be the actual metadata file path so old metadata files can be tracked and eventually cleaned up. * iceberg: update metadataLocation and versionToken in xattr on commit updateTableMetadataXattr was only updating metadataVersion, modifiedAt, and fullMetadata but not metadataLocation or versionToken. This left catalog state inconsistent after maintenance commits — the metadataLocation still pointed to the old metadata file and the versionToken was stale. Add a newMetadataLocation parameter and regenerate the versionToken on every commit, matching the S3 Tables handler behavior. * iceberg: group manifest entries by partition spec in rewriteManifests rewriteManifests was writing all entries into a single manifest using the table's current partition spec. For spec-evolved tables where manifests reference different partition specs, this produces an invalid manifest. Group entries by the source manifest's PartitionSpecID and write one merged manifest per spec, looking up each spec from the table's PartitionSpecs list. * iceberg: remove dead code loop for non-data manifests in compaction The early abort guard at the top of compactDataFiles already ensures no delete manifests are present. The loop that copied non-data manifests into allManifests was unreachable dead code. * iceberg: use JSON encoding in partitionKey for unambiguous grouping partitionKey used fmt.Sprintf("%d=%v") joined by commas, which produces ambiguous keys when partition values contain commas or '='. Use json.Marshal for values and NUL byte as separator to eliminate collisions. * iceberg: precompute normalized reference set in removeOrphans The orphan check was O(files × refs) because it normalized each reference path inside the per-file loop. Precompute the normalized set once for O(1) lookups per candidate file. * iceberg: add artifact cleanup to rewriteManifests on commit failure rewriteManifests writes merged manifests and a manifest list to the filer before committing but did not clean them up on failure. Add the same deferred cleanup pattern used by compactDataFiles: track written artifacts and delete them if the commit does not succeed. * iceberg: pass isDeleteData=true in deleteFilerFile deleteFilerFile called DoRemove with isDeleteData=false, which only removed filer metadata and left chunk data behind on volume servers. All other data-file deletion callers in the codebase pass true. * iceberg: clean up test: remove unused snapID, simplify TestDetectWithFakeFiler Remove unused snapID variable and eliminate the unnecessary second fake filer + entry copy in TestDetectWithFakeFiler by capturing the client from the first startFakeFiler call. * fix: update TestWorkerDefaultJobTypes to expect 5 job types The test expected 4 default job types but iceberg_maintenance was added as a 5th default in a previous commit. * iceberg: document client-side CAS TOCTOU limitation in updateTableMetadataXattr Add a note explaining the race window where two workers can both pass the version check and race at UpdateEntry. The proper fix requires server-side precondition support on UpdateEntryRequest. * iceberg: remove unused sender variable in TestFullExecuteFlow * iceberg: abort compaction when multiple partition specs are present The compactor writes all entries into a single manifest using the current partition spec, which is invalid for spec-evolved tables. Detect multiple PartitionSpecIDs and skip compaction until per-spec compaction is implemented. * iceberg: validate tablePath to prevent directory traversal Sanitize the table_path parameter with path.Clean and verify it matches the expected namespace/tableName prefix to prevent path traversal attacks via crafted job parameters. * iceberg: cap retry backoff at 5s and make it context-aware The exponential backoff could grow unbounded and blocked on time.Sleep ignoring context cancellation. Cap at 5s and use a timer with select on ctx.Done so retries respect cancellation. * iceberg: write manifest list with new snapshot identity in rewriteManifests The manifest list was written with the old snapshot's ID and sequence number, but the new snapshot created afterwards used a different identity. Compute newSnapshotID and newSeqNum before writing manifests and the manifest list so all artifacts are consistent. * ec: also remove .vif file in removeEcVolumeFiles removeEcVolumeFiles cleaned up .ecx, .ecj, and shard files but not the .vif volume info file, leaving it orphaned. The .vif file lives in the data directory alongside shard files. The directory handling for index vs data files was already correct: .ecx/.ecj are removed from IdxDirectory and shard files from Directory, matching how NewEcVolume loads them. Revert "ec: also remove .vif file in removeEcVolumeFiles" This reverts commit acc82449e12a00115268a5652aef0d6c46d9f2dd. * iceberg: skip orphan entries with nil Attributes instead of defaulting to epoch When entry.Attributes is nil, mtime defaulted to Unix epoch (1970), making unknown-age entries appear ancient and eligible for deletion. Skip these entries instead to avoid deleting files whose age cannot be determined. * iceberg: use unique metadata filenames to prevent concurrent write clobbering Add timestamp nonce to metadata filenames (e.g. v3-1709766000.metadata.json) so concurrent writers stage to distinct files. Update extractMetadataVersion to strip the nonce suffix, and loadCurrentMetadata to read the actual filename from the metadataLocation xattr field. * iceberg: defer artifact tracking until data file builder succeeds Move the writtenArtifacts append to after NewDataFileBuilder succeeds, so a failed builder doesn't leave a stale entry for an already-deleted file in the cleanup list. * iceberg: use detached context for metadata file cleanup Use context.WithTimeout(context.Background(), 10s) when deleting staged metadata files after CAS failure, so cleanup runs even if the original request context is canceled. * test: update default job types count to include iceberg_maintenance * iceberg: use parquet.EqualNodes for structural schema comparison Replace String()-based schema comparison with parquet.EqualNodes which correctly compares types, repetition levels, and logical types. * iceberg: add nonce-suffixed filename cases to TestExtractMetadataVersion * test: assert iceberg_maintenance is present in default job types * iceberg: validate operations config early in Detect Call parseOperations in Detect so typos in the operations config fail fast before emitting proposals, matching the validation already done in Execute. * iceberg: detect chunked files in loadFileByIcebergPath Return an explicit error when a file has chunks but no inline content, rather than silently returning empty data. Data files uploaded via S3 are stored as chunks, so compaction would otherwise produce corrupt merged files. --------- Co-authored-by: Copilot <copilot@github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> |
||
|
|
e1e5b4a8a6 |
add admin script worker (#8491)
* admin: add plugin lock coordination
* shell: allow bypassing lock checks
* plugin worker: add admin script handler
* mini: include admin_script in plugin defaults
* admin script UI: drop name and enlarge text
* admin script: add default script
* admin_script: make run interval configurable
* plugin: gate other jobs during admin_script runs
* plugin: use last completed admin_script run
* admin: backfill plugin config defaults
* templ
Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
* comparable to default version
Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
* default to run
Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
* format
Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
* shell: respect pre-set noLock for fix.replication
* shell: add force no-lock mode for admin scripts
* volume balance worker already exists
Co-Authored-By: Copilot <223556219+Copilot@users.noreply.github.com>
* admin: expose scheduler status JSON
* shell: add sleep command
* shell: restrict sleep syntax
* Revert "shell: respect pre-set noLock for fix.replication"
This reverts commit
|
||
|
|
8ec9ff4a12 |
Refactor plugin system and migrate worker runtime (#8369)
* admin: add plugin runtime UI page and route wiring * pb: add plugin gRPC contract and generated bindings * admin/plugin: implement worker registry, runtime, monitoring, and config store * admin/dash: wire plugin runtime and expose plugin workflow APIs * command: add flags to enable plugin runtime * admin: rename remaining plugin v2 wording to plugin * admin/plugin: add detectable job type registry helper * admin/plugin: add scheduled detection and dispatch orchestration * admin/plugin: prefetch job type descriptors when workers connect * admin/plugin: add known job type discovery API and UI * admin/plugin: refresh design doc to match current implementation * admin/plugin: enforce per-worker scheduler concurrency limits * admin/plugin: use descriptor runtime defaults for scheduler policy * admin/ui: auto-load first known plugin job type on page open * admin/plugin: bootstrap persisted config from descriptor defaults * admin/plugin: dedupe scheduled proposals by dedupe key * admin/ui: add job type and state filters for plugin monitoring * admin/ui: add per-job-type plugin activity summary * admin/plugin: split descriptor read API from schema refresh * admin/ui: keep plugin summary metrics global while tables are filtered * admin/plugin: retry executor reservation before timing out * admin/plugin: expose scheduler states for monitoring * admin/ui: show per-job-type scheduler states in plugin monitor * pb/plugin: rename protobuf package to plugin * admin/plugin: rename pluginRuntime wiring to plugin * admin/plugin: remove runtime naming from plugin APIs and UI * admin/plugin: rename runtime files to plugin naming * admin/plugin: persist jobs and activities for monitor recovery * admin/plugin: lease one detector worker per job type * admin/ui: show worker load from plugin heartbeats * admin/plugin: skip stale workers for detector and executor picks * plugin/worker: add plugin worker command and stream runtime scaffold * plugin/worker: implement vacuum detect and execute handlers * admin/plugin: document external vacuum plugin worker starter * command: update plugin.worker help to reflect implemented flow * command/admin: drop legacy Plugin V2 label * plugin/worker: validate vacuum job type and respect min interval * plugin/worker: test no-op detect when min interval not elapsed * command/admin: document plugin.worker external process * plugin/worker: advertise configured concurrency in hello * command/plugin.worker: add jobType handler selection * command/plugin.worker: test handler selection by job type * command/plugin.worker: persist worker id in workingDir * admin/plugin: document plugin.worker jobType and workingDir flags * plugin/worker: support cancel request for in-flight work * plugin/worker: test cancel request acknowledgements * command/plugin.worker: document workingDir and jobType behavior * plugin/worker: emit executor activity events for monitor * plugin/worker: test executor activity builder * admin/plugin: send last successful run in detection request * admin/plugin: send cancel request when detect or execute context ends * admin/plugin: document worker cancel request responsibility * admin/handlers: expose plugin scheduler states API in no-auth mode * admin/handlers: test plugin scheduler states route registration * admin/plugin: keep worker id on worker-generated activity records * admin/plugin: test worker id propagation in monitor activities * admin/dash: always initialize plugin service * command/admin: remove plugin enable flags and default to enabled * admin/dash: drop pluginEnabled constructor parameter * admin/plugin UI: stop checking plugin enabled state * admin/plugin: remove docs for plugin enable flags * admin/dash: remove unused plugin enabled check method * admin/dash: fallback to in-memory plugin init when dataDir fails * admin/plugin API: expose worker gRPC port in status * command/plugin.worker: resolve admin gRPC port via plugin status * split plugin UI into overview/configuration/monitoring pages * Update layout_templ.go * add volume_balance plugin worker handler * wire plugin.worker CLI for volume_balance job type * add erasure_coding plugin worker handler * wire plugin.worker CLI for erasure_coding job type * support multi-job handlers in plugin worker runtime * allow plugin.worker jobType as comma-separated list * admin/plugin UI: rename to Workers and simplify config view * plugin worker: queue detection requests instead of capacity reject * Update plugin_worker.go * plugin volume_balance: remove force_move/timeout from worker config UI * plugin erasure_coding: enforce local working dir and cleanup * admin/plugin UI: rename admin settings to job scheduling * admin/plugin UI: persist and robustly render detection results * admin/plugin: record and return detection trace metadata * admin/plugin UI: show detection process and decision trace * plugin: surface detector decision trace as activities * mini: start a plugin worker by default * admin/plugin UI: split monitoring into detection and execution tabs * plugin worker: emit detection decision trace for EC and balance * admin workers UI: split monitoring into detection and execution pages * plugin scheduler: skip proposals for active assigned/running jobs * admin workers UI: add job queue tab * plugin worker: add dummy stress detector and executor job type * admin workers UI: reorder tabs to detection queue execution * admin workers UI: regenerate plugin template * plugin defaults: include dummy stress and add stress tests * plugin dummy stress: rotate detection selections across runs * plugin scheduler: remove cross-run proposal dedupe * plugin queue: track pending scheduled jobs * plugin scheduler: wait for executor capacity before dispatch * plugin scheduler: skip detection when waiting backlog is high * plugin: add disk-backed job detail API and persistence * admin ui: show plugin job detail modal from job id links * plugin: generate unique job ids instead of reusing proposal ids * plugin worker: emit heartbeats on work state changes * plugin registry: round-robin tied executor and detector picks * add temporary EC overnight stress runner * plugin job details: persist and render EC execution plans * ec volume details: color data and parity shard badges * shard labels: keep parity ids numeric and color-only distinction * admin: remove legacy maintenance UI routes and templates * admin: remove dead maintenance endpoint helpers * Update layout_templ.go * remove dummy_stress worker and command support * refactor plugin UI to job-type top tabs and sub-tabs * migrate weed worker command to plugin runtime * remove plugin.worker command and keep worker runtime with metrics * update helm worker args for jobType and execution flags * set plugin scheduling defaults to global 16 and per-worker 4 * stress: fix RPC context reuse and remove redundant variables in ec_stress_runner * admin/plugin: fix lifecycle races, safe channel operations, and terminal state constants * admin/dash: randomize job IDs and fix priority zero-value overwrite in plugin API * admin/handlers: implement buffered rendering to prevent response corruption * admin/plugin: implement debounced persistence flusher and optimize BuildJobDetail memory lookups * admin/plugin: fix priority overwrite and implement bounded wait in scheduler reserve * admin/plugin: implement atomic file writes and fix run record side effects * admin/plugin: use P prefix for parity shard labels in execution plans * admin/plugin: enable parallel execution for cancellation tests * admin: refactor time.Time fields to pointers for better JSON omitempty support * admin/plugin: implement pointer-safe time assignments and comparisons in plugin core * admin/plugin: fix time assignment and sorting logic in plugin monitor after pointer refactor * admin/plugin: update scheduler activity tracking to use time pointers * admin/plugin: fix time-based run history trimming after pointer refactor * admin/dash: fix JobSpec struct literal in plugin API after pointer refactor * admin/view: add D/P prefixes to EC shard badges for UI consistency * admin/plugin: use lifecycle-aware context for schema prefetching * Update ec_volume_details_templ.go * admin/stress: fix proposal sorting and log volume cleanup errors * stress: refine ec stress runner with math/rand and collection name - Added Collection field to VolumeEcShardsDeleteRequest for correct filename construction. - Replaced crypto/rand with seeded math/rand PRNG for bulk payloads. - Added documentation for EcMinAge zero-value behavior. - Added logging for ignored errors in volume/shard deletion. * admin: return internal server error for plugin store failures Changed error status code from 400 Bad Request to 500 Internal Server Error for failures in GetPluginJobDetail to correctly reflect server-side errors. * admin: implement safe channel sends and graceful shutdown sync - Added sync.WaitGroup to Plugin struct to manage background goroutines. - Implemented safeSendCh helper using recover() to prevent panics on closed channels. - Ensured Shutdown() waits for all background operations to complete. * admin: robustify plugin monitor with nil-safe time and record init - Standardized nil-safe assignment for *time.Time pointers (CreatedAt, UpdatedAt, CompletedAt). - Ensured persistJobDetailSnapshot initializes new records correctly if they don't exist on disk. - Fixed debounced persistence to trigger immediate write on job completion. * admin: improve scheduler shutdown behavior and logic guards - Replaced brittle error string matching with explicit r.shutdownCh selection for shutdown detection. - Removed redundant nil guard in buildScheduledJobSpec. - Standardized WaitGroup usage for schedulerLoop. * admin: implement deep copy for job parameters and atomic write fixes - Implemented deepCopyGenericValue and used it in cloneTrackedJob to prevent shared state. - Ensured atomicWriteFile creates parent directories before writing. * admin: remove unreachable branch in shard classification Removed an unreachable 'totalShards <= 0' check in classifyShardID as dataShards and parityShards are already guarded. * admin: secure UI links and use canonical shard constants - Added rel="noopener noreferrer" to external links for security. - Replaced magic number 14 with erasure_coding.TotalShardsCount. - Used renderEcShardBadge for missing shard list consistency. * admin: stabilize plugin tests and fix regressions - Composed a robust plugin_monitor_test.go to handle asynchronous persistence. - Updated all time.Time literals to use timeToPtr helper. - Added explicit Shutdown() calls in tests to synchronize with debounced writes. - Fixed syntax errors and orphaned struct literals in tests. * Potential fix for code scanning alert no. 278: Slice memory allocation with excessive size value Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> * Potential fix for code scanning alert no. 283: Uncontrolled data used in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> * admin: finalize refinements for error handling, scheduler, and race fixes - Standardized HTTP 500 status codes for store failures in plugin_api.go. - Tracked scheduled detection goroutines with sync.WaitGroup for safe shutdown. - Fixed race condition in safeSendDetectionComplete by extracting channel under lock. - Implemented deep copy for JobActivity details. - Used defaultDirPerm constant in atomicWriteFile. * test(ec): migrate admin dockertest to plugin APIs * admin/plugin_api: fix RunPluginJobTypeAPI to return 500 for server-side detection/filter errors * admin/plugin_api: fix ExecutePluginJobAPI to return 500 for job execution failures * admin/plugin_api: limit parseProtoJSONBody request body to 1MB to prevent unbounded memory usage * admin/plugin: consolidate regex to package-level validJobTypePattern; add char validation to sanitizeJobID * admin/plugin: fix racy Shutdown channel close with sync.Once * admin/plugin: track sendLoop and recv goroutines in WorkerStream with r.wg * admin/plugin: document writeProtoFiles atomicity — .pb is source of truth, .json is human-readable only * admin/plugin: extract activityLess helper to deduplicate nil-safe OccurredAt sort comparators * test/ec: check http.NewRequest errors to prevent nil req panics * test/ec: replace deprecated ioutil/math/rand, fix stale step comment 5.1→3.1 * plugin(ec): raise default detection and scheduling throughput limits * topology: include empty disks in volume list and EC capacity fallback * topology: remove hard 10-task cap for detection planning * Update ec_volume_details_templ.go * adjust default * fix tests --------- Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> |