From 577e0295905d3cbfad9aaaea6c216d6dd66e09a5 Mon Sep 17 00:00:00 2001 From: wangliangbj01 Date: Thu, 26 Nov 2026 19:29:35 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(audit):=20=E5=B0=86=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B=E6=A0=A1=E6=AD=A3=E6=94=B9=E4=B8=BA=E5=8F=AF?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E7=9A=84=E5=90=8E=E5=8F=B0=E6=89=B9=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../flowscope-cli/backend/audit-api-spec.md | 29 +- CHANGELOG.md | 3 + crates/flowscope-cli/src/server/audit.rs | 280 +++++++++++++++--- crates/flowscope-cli/src/server/mod.rs | 8 + crates/flowscope-cli/src/server/state.rs | 4 + 5 files changed, 281 insertions(+), 43 deletions(-) diff --git a/.trellis/spec/flowscope-cli/backend/audit-api-spec.md b/.trellis/spec/flowscope-cli/backend/audit-api-spec.md index 4fb6c367..8cbc2473 100644 --- a/.trellis/spec/flowscope-cli/backend/audit-api-spec.md +++ b/.trellis/spec/flowscope-cli/backend/audit-api-spec.md @@ -195,9 +195,23 @@ unsupported or unclassified types display `—` in the page. | Meaningful statements exist | Classify using `AnalyzeResult.sql_type` and `insert_type` | | Only SET/USE/RESET, or no analyzed statements | `sql_type=null` | | INSERT variant missing | Retain generic `INSERT`; display `—` rather than guess | -| Legacy row with complete saved classification | Normalize its stored type at audit startup | +| Legacy row with complete saved classification | Normalize its stored type in resumable background batches after binding the listener | | Missing, malformed, or truncated saved JSON | Leave the legacy type unchanged; unsupported page Type is `—` | -| Audit database opened repeatedly | Normalization is idempotent and only updates changed labels | +| Audit database opened repeatedly | Resume the persisted cursor; completed backfills do not scan JSON again | + +Startup only initializes the schema and captures the legacy upper ID through the +primary-key index. Never run JSON extraction or a historical UPDATE before the +listener is bound: production audit JSON can be hundreds of gigabytes, and even +unchanged SELECT rows otherwise get parsed on every restart. A small fixture +proves classification correctness, not acceptable production startup latency. + +The audit SQL-type worker reads at most 32 rows by primary key per batch on a +separate connection. It releases the read statement before parsing only the +saved classification fields, then commits changed labels and the resume cursor +together. No audit-writer mutex is held. Lock contention retries without advancing +the cursor; shutdown stops between batches. Rows beyond the initial upper ID use +the current writer classification. Missing, invalid or truncated metadata keeps +its old label. Progress is logged while the HTTP service remains available. #### 5. Good / Base / Bad Cases @@ -211,9 +225,14 @@ unsupported or unclassified types display `—` in the page. - `audit_query_filter_by_sql_type`: actual analyze/write/list calls cover SELECT, INTO, and OVERWRITE, each with and without WITH; subtype filters return two records each, aggregate INSERT returns four, and WITH returns none. -- `startup_normalizes_legacy_sql_types_without_guessing_missing_metadata`: - reopen twice, verify corrected labels, preserve incomplete/invalid metadata, - and verify subtype filtering after correction. +- `startup_defers_sql_type_backfill_and_preserves_missing_metadata`: startup + leaves historical values untouched, explicit batches correct valid metadata, + and reopen/completion do not redo work; subtype filters use corrected labels. +- `sql_type_backfill_is_bounded_resumable_and_cancellable` and + `sql_type_backfill_retries_without_advancing_after_write_contention`: verify + the 32-row bound, persisted cursor, fixed upper ID, cancellation and atomic + retry behavior. Native serve checks must use a substantial large-JSON fixture, + verify health and new audit writes during backfill, and verify restart resume. - `AuditPage SQL types`: render `ii`, `io`, and `select`; unsupported legacy values render `—`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 63355f1e..bbe07146 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Audit startup no longer scans historical analysis JSON before listening. + Legacy SQL types are corrected in bounded, resumable background batches with + progress logs, preserving audit writes and health checks during maintenance. - Audit polling refreshes queued writes without covering the table or disabling pagination. Audit SQL types consistently show `ii`, `io`, and `select`, including CTE-prefixed writes and legacy rows with complete saved analyzer metadata. diff --git a/crates/flowscope-cli/src/server/audit.rs b/crates/flowscope-cli/src/server/audit.rs index 30a35f1f..8ac69e3c 100644 --- a/crates/flowscope-cli/src/server/audit.rs +++ b/crates/flowscope-cli/src/server/audit.rs @@ -6,10 +6,11 @@ use std::path::PathBuf; use std::sync::Arc; +use std::time::Duration; use flowscope_core::{AnalyzeResult, InsertType, NodeType, SqlType}; use sha2::{Digest, Sha256}; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, watch}; /// One row written to `audit_log`. #[derive(Debug, Clone)] @@ -302,31 +303,116 @@ const ADDITIVE_MIGRATIONS: &[&str] = &[ "ALTER TABLE audit_log ADD COLUMN target_table TEXT", ]; -/// Correct legacy statement labels using saved analyzer metadata. Never guess -/// an INSERT variant from a WITH prefix or inspect truncated JSON as valid JSON. -const NORMALIZE_SQL_TYPES_SQL: &str = r#" -WITH classified AS ( - SELECT id, sql_type, - CASE WHEN json_valid(result_json) THEN - CASE json_extract(result_json, '$.sqlType') - WHEN 'select' THEN 'SELECT' - WHEN 'insert' THEN - CASE json_extract(result_json, '$.insertType') - WHEN 'into' THEN 'INSERT INTO' - WHEN 'overwrite' THEN 'INSERT OVERWRITE' - ELSE sql_type - END - ELSE sql_type - END - ELSE sql_type END AS normalized_type - FROM audit_log - WHERE sql_type IN ('WITH', 'INSERT', 'SELECT', 'CREATE_TABLE_AS') -) -UPDATE audit_log -SET sql_type = (SELECT normalized_type FROM classified WHERE classified.id = audit_log.id) -WHERE id IN (SELECT id FROM classified WHERE sql_type IS NOT normalized_type); +// Capture a fixed legacy boundary using the primary-key index. Startup must +// never read historical result_json values or rewrite all audit rows. +const INIT_SQL_TYPE_BACKFILL: &str = r#" +CREATE TABLE IF NOT EXISTS audit_sql_type_backfill ( + id INTEGER PRIMARY KEY CHECK (id = 1), + last_id INTEGER NOT NULL, + upper_id INTEGER NOT NULL, + completed INTEGER NOT NULL DEFAULT 0 +); +INSERT OR IGNORE INTO audit_sql_type_backfill (id, last_id, upper_id, completed) +SELECT 1, 0, COALESCE(MAX(id), 0), MAX(id) IS NULL FROM audit_log; "#; +const SQL_TYPE_BACKFILL_BATCH_SIZE: i64 = 32; + +struct SqlTypeBackfillProgress { + last_id: i64, + upper_id: i64, + completed: bool, + updated: usize, +} + +/// Read a bounded page, release its read lock, parse only classification fields, +/// then commit small updates and the resume cursor together. +fn normalize_sql_type_batch(db_path: &std::path::Path) -> anyhow::Result { + let mut conn = rusqlite::Connection::open(db_path)?; + conn.busy_timeout(Duration::from_millis(200))?; + let mut progress = conn.query_row( + "SELECT last_id,upper_id,completed FROM audit_sql_type_backfill WHERE id=1", + [], + |row| { + Ok(SqlTypeBackfillProgress { + last_id: row.get(0)?, + upper_id: row.get(1)?, + completed: row.get(2)?, + updated: 0, + }) + }, + )?; + if progress.completed { + return Ok(progress); + } + let rows = { + let mut statement = conn.prepare( + "SELECT id,sql_type,CASE + WHEN sql_type IN ('WITH','INSERT','SELECT','CREATE_TABLE_AS') + AND result_truncated=0 THEN result_json ELSE NULL END + FROM audit_log WHERE id>?1 AND id<=?2 ORDER BY id LIMIT ?3", + )?; + let rows = statement.query_map( + rusqlite::params![ + progress.last_id, + progress.upper_id, + SQL_TYPE_BACKFILL_BATCH_SIZE + ], + |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, Option>(2)?, + )) + }, + )?; + rows.collect::>>()? + }; + #[derive(serde::Deserialize)] + #[serde(rename_all = "camelCase")] + struct SavedClassification { + sql_type: Option, + insert_type: Option, + } + let mut updates = Vec::new(); + for (id, old_type, saved) in &rows { + let Some(saved) = saved else { continue }; + let Ok(saved) = serde_json::from_str::(saved) else { + continue; + }; + let normalized = match ( + saved.sql_type.as_ref().and_then(serde_json::Value::as_str), + saved + .insert_type + .as_ref() + .and_then(serde_json::Value::as_str), + ) { + (Some("select"), _) => "SELECT", + (Some("insert"), Some("into")) => "INSERT INTO", + (Some("insert"), Some("overwrite")) => "INSERT OVERWRITE", + _ => continue, + }; + if old_type.as_deref() != Some(normalized) { + updates.push((*id, old_type, normalized)); + } + } + progress.last_id = rows.last().map_or(progress.upper_id, |row| row.0); + progress.completed = progress.last_id >= progress.upper_id; + let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?; + for (id, old_type, normalized) in updates { + progress.updated += tx.execute( + "UPDATE audit_log SET sql_type=?1 WHERE id=?2 AND sql_type IS ?3", + rusqlite::params![normalized, id, old_type], + )?; + } + tx.execute( + "UPDATE audit_sql_type_backfill SET last_id=MAX(last_id,?1),completed=MAX(completed,?2) WHERE id=1", + rusqlite::params![progress.last_id, progress.completed], + )?; + tx.commit()?; + Ok(progress) +} + const INSERT_SQL: &str = r#" INSERT INTO audit_log ( ts, client_ip, endpoint, dialect, file_name, source_name, target_table, @@ -380,6 +466,7 @@ pub(crate) fn insert_entry( /// blocked by SQLite I/O. pub struct AuditWriter { tx: mpsc::UnboundedSender, + db_path: PathBuf, } impl AuditWriter { @@ -418,8 +505,9 @@ impl AuditWriter { } conn.execute_batch(CREATE_INDEXES_SQL) .map_err(|e| anyhow::anyhow!("Failed to create audit indexes: {}", e))?; - conn.execute_batch(NORMALIZE_SQL_TYPES_SQL) - .map_err(|e| anyhow::anyhow!("Failed to normalize audit SQL types: {}", e))?; + conn.execute_batch(INIT_SQL_TYPE_BACKFILL).map_err(|e| { + anyhow::anyhow!("Failed to initialize audit backfill progress: {}", e) + })?; conn }; @@ -446,7 +534,52 @@ impl AuditWriter { } }); - Ok(Self { tx }) + Ok(Self { tx, db_path }) + } + + /// Started only after the listener is bound. Database contention pauses + /// maintenance rather than blocking startup or sharing the audit writer lock. + pub async fn backfill_sql_types(&self, mut stop: watch::Receiver) { + let mut batches = 0; + let mut updated = 0; + while !*stop.borrow() { + let path = self.db_path.clone(); + match tokio::task::spawn_blocking(move || normalize_sql_type_batch(&path)).await { + Ok(Ok(progress)) => { + batches += 1; + updated += progress.updated; + if batches == 1 || batches % 100 == 0 || progress.completed { + eprintln!( + "flowscope: audit SQL type backfill {}/{} (updated {}, {})", + progress.last_id, + progress.upper_id, + updated, + if progress.completed { + "complete" + } else { + "background" + } + ); + } + if progress.completed { + return; + } + } + Ok(Err(error)) => { + eprintln!("flowscope: audit SQL type backfill paused; will retry: {error}"); + } + Err(error) => { + eprintln!("flowscope: audit SQL type backfill task failed: {error}"); + return; + } + } + tokio::select! { + _ = tokio::time::sleep(Duration::from_millis(100)) => {}, + changed = stop.changed() => { + if changed.is_err() || *stop.borrow() { return; } + } + } + } } /// Queue an audit entry for writing. Fire-and-forget: errors are logged to @@ -806,7 +939,7 @@ mod tests { } #[tokio::test] - async fn startup_normalizes_legacy_sql_types_without_guessing_missing_metadata() { + async fn startup_defers_sql_type_backfill_and_preserves_missing_metadata() { let (_dir, path, conn) = fresh_db(); let cases = [ ( @@ -837,20 +970,25 @@ mod tests { } drop(conn); - for _ in 0..2 { - let writer = AuditWriter::new(path.clone()).unwrap(); - drop(writer); - let conn = rusqlite::Connection::open(&path).unwrap(); + let writer = AuditWriter::new(path.clone()).unwrap(); + drop(writer); + let types = |path: &std::path::Path| { + let conn = rusqlite::Connection::open(path).unwrap(); let mut stmt = conn .prepare("SELECT sql_type FROM audit_log ORDER BY id") .unwrap(); - let types: Vec = stmt - .query_map([], |row| row.get(0)) + stmt.query_map([], |row| row.get::<_, String>(0)) .unwrap() - .collect::>() - .unwrap(); - assert_eq!(types, cases.map(|(_, _, expected)| expected)); - } + .collect::, _>>() + .unwrap() + }; + assert_eq!(types(&path), cases.map(|(old, _, _)| old)); + let progress = normalize_sql_type_batch(&path).unwrap(); + assert!(progress.completed); + assert_eq!(types(&path), cases.map(|(_, _, expected)| expected)); + drop(AuditWriter::new(path.clone()).unwrap()); + assert_eq!(normalize_sql_type_batch(&path).unwrap().updated, 0); + assert_eq!(types(&path), cases.map(|(_, _, expected)| expected)); let page = AuditWriter::query( &path, @@ -865,6 +1003,72 @@ mod tests { assert_eq!(page.total, 2); } + #[tokio::test] + async fn sql_type_backfill_is_bounded_resumable_and_cancellable() { + let (_dir, path, conn) = fresh_db(); + let mut entry = make_entry(None, None); + entry.sql_type = Some("WITH".into()); + entry.result_json = Some(r#"{"sqlType":"select","payload":"ignored"}"#.into()); + let total = SQL_TYPE_BACKFILL_BATCH_SIZE * 2 + 3; + for _ in 0..total { + insert_direct(&conn, &entry); + } + let writer = AuditWriter::new(path.clone()).unwrap(); + let (_, stopped) = watch::channel(true); + writer.backfill_sql_types(stopped).await; + let untouched: i64 = conn + .query_row("SELECT last_id FROM audit_sql_type_backfill", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(untouched, 0); + let first = normalize_sql_type_batch(&path).unwrap(); + assert_eq!(first.last_id, SQL_TYPE_BACKFILL_BATCH_SIZE); + assert_eq!(first.updated, SQL_TYPE_BACKFILL_BATCH_SIZE as usize); + assert!(!first.completed); + drop(writer); + drop(AuditWriter::new(path.clone()).unwrap()); + // New rows are outside the fixed legacy boundary. + insert_direct(&conn, &entry); + let second = normalize_sql_type_batch(&path).unwrap(); + assert_eq!(second.last_id, SQL_TYPE_BACKFILL_BATCH_SIZE * 2); + assert_eq!(second.upper_id, total); + let last = normalize_sql_type_batch(&path).unwrap(); + assert!(last.completed); + assert_eq!(last.updated, 3); + assert_eq!(last.last_id, total); + let new_row: String = conn + .query_row( + "SELECT sql_type FROM audit_log WHERE id=?1", + [total + 1], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(new_row, "WITH"); + } + + #[tokio::test] + async fn sql_type_backfill_retries_without_advancing_after_write_contention() { + let (_dir, path, conn) = fresh_db(); + let mut entry = make_entry(None, None); + entry.sql_type = Some("WITH".into()); + entry.result_json = Some(r#"{"sqlType":"insert","insertType":"into"}"#.into()); + insert_direct(&conn, &entry); + drop(AuditWriter::new(path.clone()).unwrap()); + conn.execute_batch("BEGIN IMMEDIATE").unwrap(); + assert!(normalize_sql_type_batch(&path).is_err()); + let cursor: i64 = conn + .query_row("SELECT last_id FROM audit_sql_type_backfill", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!(cursor, 0); + conn.execute_batch("ROLLBACK").unwrap(); + let progress = normalize_sql_type_batch(&path).unwrap(); + assert!(progress.completed); + assert_eq!(progress.updated, 1); + } + #[test] fn truncate_result_json_keeps_utf8_boundary_at_byte_cap() { // Vary a preceding ASCII field until the fixed 1 MiB offset lands diff --git a/crates/flowscope-cli/src/server/mod.rs b/crates/flowscope-cli/src/server/mod.rs index 1b7d81b7..42ccb6ae 100644 --- a/crates/flowscope-cli/src/server/mod.rs +++ b/crates/flowscope-cli/src/server/mod.rs @@ -46,6 +46,11 @@ pub async fn run_server(config: ServerConfig) -> Result<()> { }); let (lineage_stop, lineage_stopped) = tokio::sync::watch::channel(false); + let audit_backfill = state.audit.as_ref().map(|audit| { + let audit = Arc::clone(audit); + let stop = lineage_stopped.clone(); + tokio::spawn(async move { audit.backfill_sql_types(stop).await }) + }); let lineage_worker = state .lineage .as_ref() @@ -74,6 +79,9 @@ pub async fn run_server(config: ServerConfig) -> Result<()> { if let Some(worker) = lineage_worker { let _ = worker.await; } + if let Some(worker) = audit_backfill { + let _ = worker.await; + } watcher_handle.abort(); let _ = watcher_handle.await; println!("\nflowscope: server stopped"); diff --git a/crates/flowscope-cli/src/server/state.rs b/crates/flowscope-cli/src/server/state.rs index 7bbdde95..5a9034e4 100644 --- a/crates/flowscope-cli/src/server/state.rs +++ b/crates/flowscope-cli/src/server/state.rs @@ -108,6 +108,10 @@ impl AppState { } // Initialise audit writer if a path was provided let audit = if let Some(ref audit_path) = config.audit_log_path { + eprintln!( + "flowscope: initializing audit schema at {}", + audit_path.display() + ); match AuditWriter::new(audit_path.clone()) { Ok(writer) => { println!("flowscope: audit logging to {}", audit_path.display()); From 754390a0accc8c3438c0b571da09e4b38c763364 Mon Sep 17 00:00:00 2001 From: wangliangbj01 Date: Thu, 26 Nov 2026 19:29:49 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs:=20=E8=AE=B0=E5=BD=95=E5=AE=A1?= =?UTF-8?q?=E8=AE=A1=E5=90=AF=E5=8A=A8=E9=98=BB=E5=A1=9E=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .trellis/workspace/wangliang/index.md | 5 ++-- .trellis/workspace/wangliang/journal-1.md | 33 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/.trellis/workspace/wangliang/index.md b/.trellis/workspace/wangliang/index.md index a0dda2c8..52283c12 100644 --- a/.trellis/workspace/wangliang/index.md +++ b/.trellis/workspace/wangliang/index.md @@ -8,7 +8,7 @@ - **Active File**: `journal-1.md` -- **Total Sessions**: 17 +- **Total Sessions**: 18 - **Last Active**: 2026-11-26 @@ -19,7 +19,7 @@ | File | Lines | Status | |------|-------|--------| -| `journal-1.md` | ~586 | Active | +| `journal-1.md` | ~619 | Active | --- @@ -29,6 +29,7 @@ | # | Date | Title | Commits | Branch | |---|------|-------|---------|--------| +| 18 | 2026-11-26 | 修复历史审计类型校正阻塞启动 | `577e0295` | `codex/fix-audit-startup-blocking` | | 17 | 2026-11-26 | 汇总全部本地分支并验证审计功能 | `fde842be`, `41af81ee` | `codex/fix-audit-table-flicker` | | 16 | 2026-11-26 | 审计入图状态展示具体原因 | `391384d4` | `codex/audit-status-reasons` | | 15 | 2026-11-26 | 审计页增加入图状态筛选 | `fc5ab52e4bd3ae41152cc7c9233c7b65b74681c8` | `codex/audit-ingestion-filter` | diff --git a/.trellis/workspace/wangliang/journal-1.md b/.trellis/workspace/wangliang/journal-1.md index edb0d539..925e74d0 100644 --- a/.trellis/workspace/wangliang/journal-1.md +++ b/.trellis/workspace/wangliang/journal-1.md @@ -584,3 +584,36 @@ Token 管理显示实际凭据,管理员可在刷新和重启后再次读取 ### Next Steps - None - task complete + + +## Session 18: 修复历史审计类型校正阻塞启动 + +**Date**: 2026-11-26 +**Task**: 修复历史审计类型校正阻塞启动 +**Branch**: `codex/fix-audit-startup-blocking` + +### Summary + +移除监听端口前的历史 JSON 全量校正,改为服务启动后每批 32 行、独立连接、原子游标和可恢复的后台任务,增加阶段与进度日志。补齐延后执行、断点续跑、取消、写锁冲突和历史边界测试;192 单测、92 接口测试、Clippy、18 SQL 回归通过。约 517 MiB 大 JSON 夹具验证健康检查在历史校正前就绪、审计新写入、重启续跑和带 lineage-config 认证访问;测试进程与端口已清理。线上 PID 长时间活跃与缺陷一致,但无 SSH 权限,尚未代替用户完成生产部署验收。 + +### Main Changes + +(Add details) + +### Git Commits + +| Hash | Message | +|------|---------| +| `577e0295` | (see git log) | + +### Testing + +- [OK] (Add test results) + +### Status + +[OK] **Completed** + +### Next Steps + +- None - task complete