← Back to Pull requests

objectfs: async SQLite apply with in-memory overlay and retries #159

Closed
unknown closed this pull request without merging on Oct 03, 2026 23:14 UTC
View on GitHub
unknown unknown commented on Oct 03, 2026 20:26 UTC
Author

This PR implements Phase 2 of #155 (building on #109 / #152 and the merged read cache in #157): making the stream append the single commit point for metadata operations in SQLite mode and applying to SQLite asynchronously behind an in-memory overlay with retries and backpressure.

Key Changes

1. Commit Point at Log Append:
- Every metadata mutating operation commits at the log append (at the requested durability level) and immediately records unapplied row changes in v.sqliteOverlay.
- SQLite errors never reach clients, eliminating false failures for already-committed operations.

2. Background Batch Applier, Transaction Boundaries & Coalescing:
- Dedicated sqliteApplier goroutine drains committed changes in log order in configurable batches (default 100).
- Batches only cut at transaction boundaries (never splitting changes that share a Seq), preventing mid-log position desync upon restart.
- Repeated changes to the same row/directory key within a batch coalesce into a single write before invoking sqliteDB.ApplyBatch.
- SQLite's recorded _stream_position advances atomically in the same transaction as each batch.
- Committed rows are removed from the unapplied overlay and populated as clean entries in the LRU read cache (sqliteCache).

3. In-Memory Overlay & Read Priority:
- Reads check the unapplied overlay first, then the clean LRU read cache, then SQLite.
- Range queries and directory scans (getOrLoadDirLocked, ReadDir, Rmdir, ensureInodeChunksLoadedLocked) merge unapplied overlay creations/updates and deletions with SQLite results so unapplied changes are immediately visible during apply lag.

4. Fault Tolerance, Retries, and Degraded State:
- On SQLite apply errors, the applier retries with exponential backoff and jitter without dropping batches.
- Persistent failures (>= 3 consecutive errors) mark the store degraded (IsDegraded() == true) and alert via klog, recovering automatically once SQLite writes succeed.
- Public methods and metrics exposed: ApplyLag(), ApplyFailures(), IsDegraded(), UnappliedBytes(), SetApplierFaultHook(), FlushOverlay(), SQLiteAppliedPosition().

5. Bounded Memory & Writer Backpressure:
- --metadata-overlay-max-bytes (default 64MB) limits the total byte size of unapplied overlay rows.
- If SQLite falls behind or faults, writers block on backpressure until the overlay drains below the bound.

6. Consistent Snapshots & Crash Recovery:
- FlushToBackend waits until all transactions committed before the flush started are applied (sqliteAppliedPos >= targetSeq), avoiding starvation under continuous writes.
- Crash recovery (kill -9 / ungraceful restart) recovers all acknowledged records by initializing SQLite at its last applied position and replaying the stream log from there.

7. Tests:
- TestSQLiteTransactionBoundaryBatchingAndMidLogRecovery: verifies that batch boundaries never split multi-change transactions (e.g. rename) and that crash recovery from an existing SQLite file completes consistently.
- TestSQLiteSnapshotFlushNoStarvationUnderContinuousWrites: verifies that snapshot flushing does not starve or stall when concurrent writers are constantly adding new entries.
- Additional unit and integration tests in sqlite_store_test.go covering reads during apply lag, batch coalescing, fault injection, degraded status, backpressure under lag, and snapshot overlay flushing.

---

Benchmark Measurements (from TestBenchmarkMetricsReport)

1. Directory Entry Addition Scaling


| Mode | Add to Empty Dir | Add to 10k Entry Dir |
|---|---|---|
| Legacy (Synchronous) | 1.14 ms | 3.00 ms |
| SQLite (Async Overlay) | 864.75 µs | 902.62 µs |

2. Batch Applier Scaling & WAL Footprint (100 Operations)


| Batch Size | Operation | Total Latency (avg/op) | WAL Footprint |
|---|---|---|---|
| 1 | 100 Creates | 126.37 ms (1.26 ms/op) | 4,055 KB (~1,040 pages) |
| 1 | 100 64KiB Writes | 87.89 ms (878.88 µs/op) | +4 KB WAL delta |
| 1 | 100 Renames | 99.33 ms (993.30 µs/op) | +12 KB WAL delta |
| 10 | 100 Creates | 158.12 ms (1.58 ms/op) | 4,039 KB (~1,036 pages) |
| 10 | 100 64KiB Writes | 89.49 ms (894.90 µs/op) | +0 KB WAL delta (coalesced) |
| 10 | 100 Renames | 98.89 ms (988.87 µs/op) | +32 KB WAL delta |
| 100 | 100 Creates | 153.34 ms (1.53 ms/op) | 4,039 KB (~1,036 pages) |
| 100 | 100 64KiB Writes | 90.63 ms (906.34 µs/op) | +0 KB WAL delta (coalesced) |
| 100 | 100 Renames | 98.83 ms (988.28 µs/op) | +0 KB WAL delta (coalesced) |

3. Overlay Read vs Clean Read Cache Latency


| Read Type | 1,000 Ops Total | Latency / op |
|---|---|---|
| Overlay Read (during lag) | 1.43 ms | 1.43 µs / op |
| Clean LRU Cache Read | 1.97 ms | 1.97 µs / op |

---

Follow-ups (Non-blocking)


  • Persistent SQLite Failure Rebuild: In a future PR, add an automatic recovery path for persistent SQLite errors by discarding the local SQLite DB and restoring from the latest published SQLite snapshot + log replay.

  • Read Latency Under Write Bursts: Single-connection SQLite lock contention during heavy background batch writes can be investigated with p99 metrics under concurrent workloads.
  • Fixes #158

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: justinsb Review duration: 168m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #159"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%