8000 fix: skip checkpoint on Drop when handle made no writes (issue #226) by adityamukho · Pull Request #228 · project-minigraf/minigraf · GitHub
[go: up one dir, main page]

Skip to content
187 changes: 187 additions & 0 deletions docs/superpowers/plans/2026-05-03-drop-readonly-handle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Fix Drop on Read-Only Handle Writes to File (issue #226) Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Prevent `Drop` on a read-only (no-write) file-backed handle from modifying the `.graph` file.

**Architecture:** Add an early-return guard in `do_checkpoint` (`src/db.rs`) that skips the `force_dirty()` + `save()` path when `wal_entry_count == 0 && !pfs.is_dirty()`. A comment explains that file locking already prevents multi-process exposure in the common case; the guard closes the remaining same-process and lock-bypass edge cases.

**Tech Stack:** Rust, `cargo test`

---

### Task 1: Write the failing test

**Files:**
- Modify: `src/db.rs` — add test in the existing `#[cfg(all(test, not(target_arch = "wasm32")))]` mod at the bottom

- [ ] **Step 1: Write the failing test**

Locate the `mod tests { ... }` block near the end of `src/db.rs` (around line 1074). Add this test inside it, after the last existing test:

```rust
#[test]
fn test_readonly_handle_drop_does_not_modify_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("test.graph");

// Write a fact and checkpoint so the main file is clean and WAL is gone.
{
let db = Minigraf::open(&path).unwrap();
db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap();
db.checkpoint().unwrap();
}
// First handle is dropped here; Drop triggers checkpoint again, but wal_entry_count==0
// after the explicit checkpoint — this is already "broken" pre-fix.

// Record file metadata before the read-only handle opens.
let meta_before = std::fs::metadata(&path).unwrap();
let mtime_before = meta_before.modified().unwrap();
let len_before = meta_before.len();

// Open a second handle, do a read-only query, then drop it.
{
let db2 = Minigraf::open(&path).unwrap();
let result = db2
.execute(r#"(query [:find ?name :where [?e :person/name ?name]])"#)
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "Alice must be visible");
}
_ => panic!("expected QueryResults"),
}
// db2 dropped here — Drop must NOT write to the file
}

// File must be byte-for-byte identical (same mtime and size).
let meta_after = std::fs::metadata(&path).unwrap();
assert_eq!(
meta_after.len(),
len_before,
"file size must not change after read-only handle drop"
);
assert_eq!(
meta_after.modified().unwrap(),
mtime_before,
"file mtime must not change after read-only handle drop"
);
}
```

> **Note:** This test requires `QueryResult` to be in scope. It is already imported at the top of the `mod tests` block via `use super::*;` which brings in everything from `db.rs`; `QueryResult` is re-exported from `crate::query::datalog::executor`. Confirm it is already used in existing tests in the same block (e.g. `test_write_transaction_read_your_own_writes`) — it is, so no new import is needed.

- [ ] **Step 2: Run the test to confirm it fails**

```bash
cargo test --lib test_readonly_handle_drop_does_not_modify_file -- --nocapture 2>&1 | tail -20
```

Expected output: test **FAILS** with an assertion error about `file mtime must not change` or `file size must not change`. (The exact failure depends on filesystem mtime resolution; size is the more reliable signal — pre-fix the file grows by 4 KB.)

If the test passes already, something is wrong — do not proceed until it fails.

- [ ] **Step 3: Commit the failing test**

```bash
git add src/db.rs
git commit -m "test: add failing test for read-only handle Drop writing to file (#226)"
```

---

### Task 2: Implement the fix

**Files:**
- Modify: `src/db.rs:545–576` — `do_checkpoint` function, `WriteContext::File` arm

- [ ] **Step 1: Locate the exact lines to change**

Open `src/db.rs`. Find `fn do_checkpoint`. The `WriteContext::File` arm currently reads:

```rust
#[cfg(not(target_arch = "wasm32"))]
WriteContext::File {
pfs,
wal,
db_path,
wal_entry_count,
} => {
// Force a full save even if no new writes since last checkpoint.
pfs.force_dirty();
pfs.save()?;
```

- [ ] **Step 2: Apply the guard**

Replace the `WriteContext::File` arm body (from the opening `{` of the arm through `pfs.save()?;`) with:

```rust
#[cfg(not(target_arch = "wasm32"))]
WriteContext::File {
pfs,
wal,
db_path,
wal_entry_count,
} => {
// Skip checkpoint if nothing to flush.
//
// `wal_entry_count` is non-zero when this handle has made writes *or*
// replayed WAL entries on open (crash-recovery path). `pfs.is_dirty()`
// catches any facts marked dirty via the normal write path.
//
// File locking (`.graph.lock` sidecar, acquired by FileBackend::open)
// already prevents a second *process* from opening the file while this
// handle holds the lock, which covers the main multi-process exposure
// described in issue #226. This guard closes the remaining edge cases:
// same-process double-opens (same PID bypasses the stale-lock check)
// and environments where the advisory lock can be bypassed (e.g.
// network filesystems, manual lock deletion).
if *wal_entry_count == 0 && 10000 !pfs.is_dirty() {
return Ok(());
}
// `force_dirty` is needed for the WAL-replay case: facts were loaded
// into memory during `replay_wal` but `pfs.dirty` was not set because
// no write path was exercised. Without it `save()` would no-op and
// the replayed facts would never reach the main file.
pfs.force_dirty();
pfs.save()?;
```

Leave everything after `pfs.save()?;` (WAL deletion, `wal_entry_count = 0`) unchanged.

- [ ] **Step 3: Run the previously failing test to confirm it now passes**

```bash
cargo test --lib test_readonly_handle_drop_does_not_modify_file -- --nocapture 2>&1 | tail -20
```

Expected: **PASS**.

- [ ] **Step 4: Run the full test suite to confirm no regressions**

```bash
cargo test 2>&1 | tail -20
```

Expected: all tests pass (currently 795+). If any test fails, investigate before committing.

- [ ] **Step 5: Commit the fix**

```bash
git add src/db.rs
git commit -m "fix: skip checkpoint on Drop when handle made no writes (issue #226)

Inner::drop() called do_checkpoint() unconditionally, which called
force_dirty() + save() even for read-only handles — growing the file
by 4 KB and invalidating other open handles.

Add an early-return guard in do_checkpoint: skip when wal_entry_count
is zero and pfs is not dirty. force_dirty() is still called when the
guard passes, preserving the crash-recovery path where WAL entries are
replayed into memory on open (wal_entry_count > 0, dirty == false).

File locking already prevents multi-process exposure in the common
case; this guard closes same-process double-opens and lock-bypass
edge cases."
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Design: Fix `Drop` on Read-Only Handles Writing to File (issue #226)

**Date:** 2026-05-03
**Status:** Approved

## Problem

`Inner::drop()` unconditionally calls `do_checkpoint()`, which calls `pfs.force_dirty()` before `pfs.save()`. The `force_dirty()` call bypasses the `dirty` guard in `save()`, causing a file write (and 4 KB size increase) even when the handle never performed any mutations. This corrupts other open handles to the same file.

**Reproduction context:** A persistent MCP server holds handle A with active writes. A per-turn hook subprocess opens handle B, performs a read-only query, then exits (`__del__` fires `Drop`). Handle A subsequently fails with `Serde Deserialization Error` or `Page N out of bounds (total pages: N)`.

## Root Cause

`do_checkpoint` (`src/db.rs:545–576`) always calls `pfs.force_dirty()` then `pfs.save()`, regardless of whether any writes or WAL replays have occurred on this handle. The `force_dirty()` was introduced to handle the WAL-replay-on-open case (where `pfs.dirty == false` but in-memory facts exceed what's in the main file). However it has the side-effect of making every `Drop` write to the file.

## Design

### Change 1 — Early-return guard in `do_checkpoint` (`src/db.rs`)

In the `WriteContext::File` arm of `do_checkpoint`, add a guard before `force_dirty()` + `save()`:

```rust
if *wal_entry_count == 0 && !pfs.is_dirty() {
return Ok(());
}
// force_dirty handles the WAL-replay case:
// wal_entry_count > 0 but dirty == false (facts replayed into memory, not yet on disk)
pfs.force_dirty();
pfs.save()?;
```

**Invariant preserved:** `force_dirty()` is only reachable when `wal_entry_count > 0` (writes were made or WAL was replayed on open) or `pfs.is_dirty() == true` (facts marked dirty via write path). In both cases there is genuinely something to write.

**Scenarios:**

| Scenario | `wal_entry_count` | `pfs.is_dirty()` | Result |
|---|---|---|---|
| Read-only handle, no WAL replay | 0 | false | Early return — no file write ✓ |
| Normal write handle | > 0 | true | Checkpoint proceeds ✓ |
| Crash recovery (WAL replayed on open) | > 0 | false | `force_dirty()` called, checkpoint proceeds ✓ |
| Post-checkpoint drop | 0 | false | Early return — no file write ✓ |

This fix applies uniformly to Drop, manual `checkpoint()`, and auto-checkpoint paths.

### Change 2 — Integration test (`src/db.rs` test module)

New test `test_readonly_handle_drop_does_not_modify_file`:

1. Open a file-backed DB, write one fact, call `db.checkpoint()` explicitly (flushes to main file, deletes WAL, resets `wal_entry_count` to 0).
2. Record the file's `mtime` and `len`.
3. Open a second `Minigraf` handle to the same path, execute one read-only query, drop it.
4. Assert: file `mtime` and `len` are unchanged.

## Files Changed

- `src/db.rs` — 5-line guard in `do_checkpoint`, one new test

## File Locking Context

As of the current version, `FileBackend::open()` acquires an exclusive advisory lock (`.graph.lock` sidecar). This means a second *process* cannot open the same file while another holds the lock, which prevents the multi-process corruption path described in the issue. The bug was originally encountered on v0.22 before file locking was introduced.

The Drop guard is still applied as defense in depth — it closes the remaining exposure from same-process double-opens (same PID bypasses the stale-lock check), lock bypasses (e.g. network filesystems, manual lock deletion), or future refactors that loosen the locking model. A comment in the code will note this context.

## Non-changes

- `src/storage/persistent_facts.rs` — no changes; `force_dirty()` / `is_dirty()` / `save()` behaviour unchanged
- `src/wal.rs` — no changes
- Public API — no changes; `Minigraf::checkpoint()` signature and semantics unchanged (still a no-op when nothing to flush)
66 changes: 65 additions & 1 deletion src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,26 @@ impl Minigraf {
db_path,
wal_entry_count,
} => {
// Force a full save even if no new writes since last checkpoint.
// Skip checkpoint if nothing to flush.
//
// `wal_entry_count` is non-zero when this handle has made writes *or*
// replayed WAL entries on open (crash-recovery path). `pfs.is_dirty()`
// catches any facts marked dirty via the normal write path.
//
// File locking (`.graph.lock` sidecar, acquired by FileBackend::open)
// already prevents a second *process* from opening the file while this
// handle holds the lock, which covers the main multi-process exposure
// described in issue #226. This guard closes the remaining edge cases:
// same-process double-opens (same PID bypasses the stale-lock check)
// and environments where the advisory lock can be bypassed (e.g.
// network filesystems, manual lock deletion).
if *wal_entry_count == 0 && !pfs.is_dirty() {
return Ok(());
}
// `force_dirty` is needed for the WAL-replay case: facts were loaded
// into memory during `replay_wal` but `pfs.dirty` was not set because
// no write path was exercised. Without it `save()` would no-op and
// the replayed facts would never reach the main file.
pfs.force_dirty();
pfs.save()?;

Expand Down Expand Up @@ -1729,6 +1748,51 @@ mod tests {
let result = db_high.execute("(query [:find ?to :where (reachable :a ?to)])");
assert!(result.is_ok(), "Query should succeed with higher limit");
}

// ── read-only handle drop must not modify the file ────────────────────────

#[test]
fn test_readonly_handle_drop_does_not_modify_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("test.graph");

// Write a fact and checkpoint so the main file is clean and WAL is gone.
{
let db = Minigraf::open(&path).unwrap();
db.execute(r#"(transact [[:alice :person/name "Alice"]])"#)
.unwrap();
db.checkpoint().unwrap();
}

// db2 is opened with the standard read-write constructor — there is no
// dedicated read-only open API. The fix being tested is behavioral:
// Drop must not checkpoint when no writes were made on this handle.
let meta_before = std::fs::metadata(&path).unwrap();
let len_before = meta_before.len();

// Open a second handle, do a read-only query, then drop it.
{
let db2 = Minigraf::open(&path).unwrap();
let result = db2
.execute(r#"(query [:find ?name :where [?e :person/name ?name]])"#)
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "Alice must be visible");
}
_ => panic!("expected QueryResults"),
}
// db2 dropped here — Drop must NOT write to the file
}

// File must be byte-for-byte identical (same size).
let meta_after = std::fs::metadata(&path).unwrap();
assert_eq!(
meta_after.len(),
len_before,
"file size must not change after read-only handle drop"
);
}
}

// ─── WASI smoke test ─────────────────────────────────────────────────────────
Expand Down
21 changes: 15 additions & 6 deletions src/storage/persistent_facts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,23 @@ impl<B: StorageBackend + 'static> PersistentFactStorage<B> {
committed_fact_pages,
};

// Try to load existing data
let page_count = persistent.backend.lock().unwrap().page_count()?;
if page_count > 1 {
// Try to load existing data.
//
// The load condition combines two checks:
// - `!is_new`: FileBackend reports false when the file existed on disk
// (even with only a header page, page_count == 1). This ensures
// migrate_v5_to_v6 runs for a v5 file that has no fact pages.
// - `page_count > 1`: catches MemoryBackend, which always reports
// is_new == true; page count > 1 means facts were previously saved.
let (is_new_backend, page_count) = {
let b = persistent.backend.lock().unwrap();
(b.is_new(), b.page_count()?)
};
if !is_new_backend || page_count > 1 {
persistent.load()?;
} else {
// Initialize new database with header
persistent.save()?;
// New database: FileBackend already wrote the initial header;
// MemoryBackend starts empty. Nothing to save yet.
}

Ok(persistent)
Expand Down Expand Up @@ -947,7 +957,6 @@ impl<B: StorageBackend + 'static> PersistentFactStorage<B> {
}

/// Check if storage has unsaved changes
#[allow(dead_code)]
pub fn is_dirty(&self) -> bool {
self.dirty
}
Expand Down
Loading
0