mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
cd0f60a2f0858c07ea202b00ebf8df19e65a10a2
2
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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> |
||
|
|
a7fdc0d137 |
Message Queue: Add sql querying (#7185)
* feat: Phase 1 - Add SQL query engine foundation for MQ topics Implements core SQL infrastructure with metadata operations: New Components: - SQL parser integration using github.com/xwb1989/sqlparser - Query engine framework in weed/query/engine/ - Schema catalog mapping MQ topics to SQL tables - Interactive SQL CLI command 'weed sql' Supported Operations: - SHOW DATABASES (lists MQ namespaces) - SHOW TABLES (lists MQ topics) - SQL statement parsing and routing - Error handling and result formatting Key Design Decisions: - MQ namespaces ↔ SQL databases - MQ topics ↔ SQL tables - Parquet message storage ready for querying - Backward-compatible schema evolution support Testing: - Unit tests for core engine functionality - Command integration tests - Parse error handling validation Assumptions (documented in code): - All MQ messages stored in Parquet format - Schema evolution maintains backward compatibility - MySQL-compatible SQL syntax via sqlparser - Single-threaded usage per SQL session Next Phase: DDL operations (CREATE/ALTER/DROP TABLE) * feat: Phase 2 - Add DDL operations and real MQ broker integration Implements comprehensive DDL support for MQ topic management: New Components: - Real MQ broker connectivity via BrokerClient - CREATE TABLE → ConfigureTopic gRPC calls - DROP TABLE → DeleteTopic operations - DESCRIBE table → Schema introspection - SQL type mapping (SQL ↔ MQ schema types) Enhanced Features: - Live topic discovery from MQ broker - Fallback to cached/sample data when broker unavailable - MySQL-compatible DESCRIBE output - Schema validation and error handling - CREATE TABLE with column definitions Key Infrastructure: - broker_client.go: gRPC communication with MQ broker - sql_types.go: Bidirectional SQL/MQ type conversion - describe.go: Table schema introspection - Enhanced engine.go: Full DDL routing and execution Supported SQL Operations: ✅ SHOW DATABASES, SHOW TABLES (live + fallback) ✅ CREATE TABLE table_name (col1 INT, col2 VARCHAR(50), ...) ✅ DROP TABLE table_name ✅ DESCRIBE table_name / SHOW COLUMNS FROM table_name Known Limitations: - SQL parser issues with reserved keywords (e.g., 'timestamp') - Requires running MQ broker for full functionality - ALTER TABLE not yet implemented - DeleteTopic method needs broker-side implementation Architecture Decisions: - Broker discovery via filer lock mechanism (same as shell commands) - Graceful fallback when broker unavailable - ConfigureTopic for CREATE TABLE with 6 default partitions - Schema versioning ready for ALTER TABLE support Testing: - Unit tests updated with filer address parameter - Integration tests for DDL operations - Error handling for connection failures Next Phase: SELECT query execution with Parquet scanning * fix: Resolve High Priority TODOs - Real MQ Broker Integration ✅ COMPLETED HIGH PRIORITY TODOs: 🔧 **Real FilerClient Integration** (engine.go:131) - Implemented GetFilerClient() method in BrokerClient - Added filerClientImpl with full FilerClient interface compliance - Added AdjustedUrl() and GetDataCenter() methods - Real filerClient connection replaces nil fallback 🔧 **Partition Discovery via MQ Broker** (hybrid_message_scanner.go:116) - Added ListTopicPartitions() method using topic configuration - Implemented discoverTopicPartitions() in HybridMessageScanner - Reads actual partition count from BrokerPartitionAssignments - Generates proper partition ranges based on topic.PartitionCount 📋 **Technical Fixes:** - Fixed compilation errors with undefined variables - Proper error handling with filerClientErr variable - Corrected ConfigureTopicResponse field usage (BrokerPartitionAssignments vs PartitionCount) - Complete FilerClient interface implementation 🎯 **Impact:** - SQL engine now connects to real MQ broker infrastructure - Actual topic partition discovery instead of hardcoded defaults - Production-ready broker integration with graceful fallbacks - Maintains backward compatibility with sample data when broker unavailable ✅ All tests passing - High priority TODO resolution complete! Next: Schema-aware message parsing and time filter optimization. * feat: Time Filter Extraction - Complete Performance Optimization ✅ FOURTH HIGH PRIORITY TODO COMPLETED! ⏰ **Time Filter Extraction & Push-Down Optimization** (engine.go:198-199) - Replaced hardcoded StartTimeNs=0, StopTimeNs=0 with intelligent extraction - Added extractTimeFilters() with recursive WHERE clause analysis - Smart time column detection (\_timestamp_ns, created_at, timestamp, etc.) - Comprehensive time value parsing (nanoseconds, ISO dates, datetime formats) - Operator reversal handling (column op value vs value op column) 🧠 **Intelligent WHERE Clause Processing:** - AND expressions: Combine time bounds (intersection) ✅ - OR expressions: Skip extraction (safety) ✅ - Parentheses: Recursive unwrapping ✅ - Comparison operators: >, >=, <, <=, = ✅ - Multiple time formats: nanoseconds, RFC3339, date-only, datetime ✅ 🚀 **Performance Impact:** - Push-down filtering to hybrid scanner level - Reduced data scanning at source (live logs + Parquet files) - Time-based partition pruning potential - Significant performance gains for time-series queries 📊 **Comprehensive Testing (21 tests passing):** - ✅ Time filter extraction (6 test scenarios) - ✅ Time column recognition (case-insensitive) - ✅ Time value parsing (5 formats) - ✅ Full integration with SELECT queries - ✅ Backward compatibility maintained 💡 **Real-World Query Examples:** Before: Scans ALL data, filters in memory SELECT * FROM events WHERE \_timestamp_ns > 1672531200000000000; After: Scans ONLY relevant time range at source level → StartTimeNs=1672531200000000000, StopTimeNs=0 → Massive performance improvement for large datasets! 🎯 **Production Ready Features:** - Multiple time column formats supported - Graceful fallbacks for invalid dates - OR clause safety (avoids incorrect optimization) - Comprehensive error handling **ALL MEDIUM PRIORITY TODOs NOW READY FOR NEXT PHASEtest ./weed/query/engine/ -v* 🎉 * feat: Extended WHERE Operators - Complete Advanced Filtering ✅ **EXTENDED WHERE OPERATORS IMPLEMENTEDtest ./weed/query/engine/ -v | grep -E PASS * feat: Enhanced SQL CLI Experience ✅ COMPLETE ENHANCED CLI IMPLEMENTATION: 🚀 **Multiple Execution Modes:** - Interactive shell with enhanced prompts and context - Single query execution: --query 'SQL' --output format - Batch file processing: --file queries.sql --output csv - Database context switching: --database dbname 📊 **Multi-Format Output:** - Table format (ASCII) - default for interactive - JSON format - structured data for programmatic use - CSV format - spreadsheet-friendly output - Smart auto-detection based on execution mode ⚙️ **Enhanced Interactive Shell:** - Database context switching: USE database_name; - Output format switching: \format table|json|csv - Command history tracking (basic implementation) - Enhanced help with WHERE operator examples - Contextual prompts: seaweedfs:dbname> 🛠️ **Production Features:** - Comprehensive error handling (JSON + user-friendly) - Query execution timing and performance metrics - 30-second timeout protection with graceful handling - Real MQ integration with hybrid data scanning 📖 **Complete CLI Interface:** - Full flag support: --server, --interactive, --file, --output, --database, --query - Auto-detection of execution mode and output format - Structured help system with practical examples - Batch processing with multi-query file support 💡 **Advanced WHERE Integration:** All extended operators (<=, >=, !=, LIKE, IN) fully supported across all execution modes and output formats. 🎯 **Usage Examples:** - weed sql --interactive - weed sql --query 'SHOW DATABASES' --output json - weed sql --file queries.sql --output csv - weed sql --database analytics --interactive Enhanced CLI experience complete - production ready! 🚀 * Delete test_utils_test.go * fmt * integer conversion * show databases works * show tables works * Update describe.go * actual column types * Update .gitignore * scan topic messages * remove emoji * support aggregation functions * column name case insensitive, better auto column names * fmt * fix reading system fields * use parquet statistics for optimization * remove emoji * parquet file generate stats * scan all files * parquet file generation remember the sources also * fmt * sql * truncate topic * combine parquet results with live logs * explain * explain the execution plan * add tests * improve tests * skip * use mock for testing * add tests * refactor * fix after refactoring * detailed logs during explain. Fix bugs on reading live logs. * fix decoding data * save source buffer index start for log files * process buffer from brokers * filter out already flushed messages * dedup with buffer start index * explain with broker buffer * the parquet file should also remember the first buffer_start attribute from the sources * parquet file can query messages in broker memory, if log files do not exist * buffer start stored as 8 bytes * add jdbc * add postgres protocol * Revert "add jdbc" This reverts commit |