Skip to content

Commit 840d0b3

Browse files
margaux-faurieclaudegithub-actions[bot]
authored
feat(adapters): SQLite session store with the journal Store port (#61)
* feat(adapters): SQLite session store with the journal Store port One database per source under an injected sessions folder (ADR 0009, file-engine §2.2, §2.3): schema v1 with a schema_migration table, WAL and synchronous=FULL read back on every open, integrity_check and foreign_key_check before any write, fail closed on a damaged, foreign, newer or tampered file. Sessions, groups, members, the decision log (fold, locks and append in one transaction), plans and their status changes, and PlanStore, the core's journal Store for one plan, under the <key>.lock source lock. Adds rusqlite 0.40 with the bundled SQLite (Margaux's OK, 29 Nov 2026). Choices recorded as proposals in SPEC §10. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN * build: refresh lockfiles (generated in CI) * fix(adapters): rusqlite 0.41 for SQLite 3.54, and the file key's borrow RUSTSEC-2026-0459 affects the SQLite that libsqlite3-sys 0.38 bundles; rusqlite 0.41 bundles 3.54. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN * build: refresh lockfiles (generated in CI) * ci: rerun after the lockfile refresh Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN * fix(adapters): name the plan row type for clippy Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN * test(adapters): a cancelled plan reads back without stopping Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN * fix(adapters): store review findings: run-only appends, confirm checks, crash cuts - PlanStore appends only while the plan is applying or stopping (INV-03). - confirm requires the active session, the newest draft and the whole decision log, and supersedes the other drafts; Start fresh supersedes the archived session's drafts (INV-04). - An existing file is checked through a read-only connection first; defensive mode, trusted_schema=OFF and mmap_size=0 before the first read; the whole schema, SQL text included, compared on open; stored paths validated as Windows names; an empty file with a leftover -wal refused; plans fixed by triggers; plans loaded in one read transaction. - Tests: crash cuts at every disk call with crash images and the write-ahead check (INV-13, INV-14), a journal write failing mid-run, append-only and fixed rows (INV-16), the lock (INV-23), the live -wal refusal, the bundled SQLite version. - Docs: file-engine §2.2, §9.7, §13; SPEC §10; threat model T5, T12, T14; nfr §8; testing §4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN * test(adapters): state what the write-ahead check covers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012N2yvaknQJCM8yjc93h9jN --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 6c529e2 commit 840d0b3

17 files changed

Lines changed: 4530 additions & 12 deletions

File tree

‎CLAUDE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Culla is a Windows desktop app (Tauri 2 + Rust + React/TS) that culls Nikon JPEG+NEF photos with a swipe UI, then applies keep/reject as safe, journaled file operations. Start at `docs/SPEC.md`: it records the author's decisions and maps each topic to its owning doc (PRD, nfr, architecture, ADRs, file-engine design, threat model, testing, roadmap). `docs/research/` is historical input: where it disagrees with the spec or an ADR, the spec and ADRs win.
44

55
## Status
6-
M0 (repo and tooling) is done; M1 (core engine headless) is in progress: NEF preview reader, scan and grouping, EXIF, volume identity, the preview decode and the preview pipeline (threads, prefetch, in-memory cache) are in, with the headless `culla scan` and `culla preview` and the `culla-bench` harness for the M1 campaign. M2 (file engine) has started: the pure decision log, `plan()`, preflight, the journal executor and the apply log's rendering are in, with the dry-run `culla plan`. M3 has started on the UI, demo backend only: start screen (folder and recent folders only, ADR 0029), swipe screen, TS decision reducer (`src/decisions`). M4 has started on the same demo backend: review screen with move or copy and the destination, and confirm dialog (`src/review`, the demo's plan and preflight in `backend/demo-plan.ts`, scenarios by `?scenario=` in `backend/demo-scenarios.ts`), apply screen and report (`src/apply`, the simulated run in `backend/demo-apply.ts`, its log in `backend/demo-log.ts`), zoom to 100 % and the EXIF overlay on the swipe screen (`swipe/zoom.ts`, `ZoomLayer.tsx`, `ExifOverlay.tsx`), resume and start over (sessions kept between visits in `backend/demo-sessions.ts`). Author decisions recorded 27 to 29 Nov; what is still open is in SPEC §10 and file-engine §13.
6+
M0 (repo and tooling) is done; M1 (core engine headless) is in progress: NEF preview reader, scan and grouping, EXIF, volume identity, the preview decode and the preview pipeline (threads, prefetch, in-memory cache) are in, with the headless `culla scan` and `culla preview` and the `culla-bench` harness for the M1 campaign. M2 (file engine) has started: the pure decision log, `plan()`, preflight, the journal executor and the apply log's rendering are in, with the dry-run `culla plan`, and the SQLite session store (`culla_adapters::store`; reconcile on open and the Windows file steps are next). M3 has started on the UI, demo backend only: start screen (folder and recent folders only, ADR 0029), swipe screen, TS decision reducer (`src/decisions`). M4 has started on the same demo backend: review screen with move or copy and the destination, and confirm dialog (`src/review`, the demo's plan and preflight in `backend/demo-plan.ts`, scenarios by `?scenario=` in `backend/demo-scenarios.ts`), apply screen and report (`src/apply`, the simulated run in `backend/demo-apply.ts`, its log in `backend/demo-log.ts`), zoom to 100 % and the EXIF overlay on the swipe screen (`swipe/zoom.ts`, `ZoomLayer.tsx`, `ExifOverlay.tsx`), resume and start over (sessions kept between visits in `backend/demo-sessions.ts`). Author decisions recorded 27 to 29 Nov; what is still open is in SPEC §10 and file-engine §13.
77

88
## Commands
99
Work now:
@@ -19,7 +19,7 @@ Work now:
1919

2020
## Layout
2121
- `crates/core` (package `culla-core`) — domain, ports, pure logic (TIFF/IFD walker behind a `ReadAt` port; `grouping` and scan exclusions over plain `ScanEntry` data; `exif` parsing and capture order over plain `RawExif` data; `names`; `volume`: serial + folded relative path keys, run binding; `preview`: sizes, scale, pixel cap, orientation, working bytes; `prefetch`: window, scheduler, LRU, memory budgets; `decisions`: event log, `fold`, undo/redo, reconcile clears, text form; `plan`: decided groups to operations over a snapshot of the target roots; `preflight`: P1–P17 over a plan and a snapshot of facts; `journal`: op states, recovery table, one executor for apply and resume over `Disk`/`Store` ports; `applylog`: renders the plain-text apply log from the journal; `text`: the shared escape set for untrusted names, used by the CLI and the apply log). Property tests: seeded plain loops instead of proptest (proposed, SPEC §10), `CULLA_PROP_CASES`. No I/O, no Tauri, `#![forbid(unsafe_code)]`.
22-
- `crates/adapters` (package `culla-adapters`) — Windows file ops, the read-only folder walk (`scan`, `read_dir` only, re-checks each folder before listing it, swap window until M2, never a partial folder; moves into `winfs` in M2), file reads for NEF previews, EXIF, `preview` decode (turbojpeg builds libjpeg-turbo: needs CMake, and NASM on `PATH` for SIMD, else it silently builds slow plain C), `pipeline` (reader thread, decode workers, in-memory cache; std threads only), `facts` (read-only lookups for the dry-run plan and preflight: path facts, target snapshot, the decision log file), SQLite; `winfs` (Win32 `unsafe` only in `winfs/win32.rs`, read-only volume and time-zone lookups so far, a stub off Windows). No Tauri.
22+
- `crates/adapters` (package `culla-adapters`) — Windows file ops, the read-only folder walk (`scan`, `read_dir` only, re-checks each folder before listing it, swap window until M2, never a partial folder; moves into `winfs` in M2), file reads for NEF previews, EXIF, `preview` decode (turbojpeg builds libjpeg-turbo: needs CMake, and NASM on `PATH` for SIMD, else it silently builds slow plain C), `pipeline` (reader thread, decode workers, in-memory cache; std threads only), `facts` (read-only lookups for the dry-run plan and preflight: path facts, target snapshot, the decision log file), `store` (the SQLite session store, rusqlite with bundled SQLite: one database per source under an injected sessions folder, WAL and `synchronous=FULL` asserted on open, schema v1 with migrations, a read-only check before any write, fails closed on a damaged, foreign, newer or altered file, journal writes only while a plan runs, the `<key>.lock` source lock, the core's `Store` port as `PlanStore`); `winfs` (Win32 `unsafe` only in `winfs/win32.rs`, read-only volume and time-zone lookups so far, a stub off Windows). No Tauri.
2323
- `crates/cli` (package `culla-cli`, binary `culla`) — headless scan (in; exit codes, JSON fields and off-Windows behaviour provisional, SPEC §10), preview (in; decodes, times and reports), plan (in; dry run, exit codes 0 to 5 provisional), apply, resume. Wiring only; writes nothing but stdout and stderr.
2424
- `crates/bench` (package `culla-bench`) — benchmark harness (ADR 0020): scan, preview, swipe through the pipeline, io-baseline, report; read-only, writes nothing but stdout, std only, `--json` unstable. Campaign: docs/benchmarks.md §7.
2525
- `src-tauri` (package `culla-app`) — wiring only: commands, `culla://` image scheme, capabilities. New command: `build.rs` `AppManifest::commands` + `allow-<command>` in `capabilities/main.json`.

‎Cargo.lock‎

Lines changed: 88 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/adapters/Cargo.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ kamadak-exif = "0.6.1"
1919
turbojpeg = { version = "1", default-features = false, features = ["cmake"] }
2020
# Preview resize (ADR 0012). MIT OR Apache-2.0. Pure Rust, SIMD picked at run time.
2121
fast_image_resize = { version = "5", default-features = false }
22+
# Session store (ADR 0009, `store`). MIT, with libsqlite3-sys (MIT) building the bundled SQLite
23+
# (public domain) with `cc`: no system SQLite, the same version on every PC. 0.41 at least:
24+
# its SQLite 3.54 fixes RUSTSEC-2026-0459 (a -wal with another page size). Added with
25+
# Margaux's OK in chat (29 Nov 2026).
26+
rusqlite = { version = "0.41", features = ["bundled"] }
2227

2328
[target.'cfg(windows)'.dependencies]
2429
# Read-only Win32 lookups in `winfs` (volume identity, time zone). MIT OR Apache-2.0. Already in

‎crates/adapters/src/lib.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@
66
//! into screen previews in memory (`preview`), runs them on reader threads and decode workers
77
//! with prefetch and an in-memory cache (`pipeline`) and makes read-only Win32 lookups
88
//! (`winfs`: a folder's volume identity, the PC's UTC offset), and makes the read-only lookups
9-
//! of a dry-run plan and preflight (`facts`).
9+
//! of a dry-run plan and preflight (`facts`). The session store (`store`, SQLite) writes only
10+
//! its own databases and lock files, in the injected sessions folder on the internal disk.
1011
1112
pub mod facts;
1213
pub mod metadata;
1314
pub mod pipeline;
1415
pub mod preview;
1516
pub mod scan;
17+
pub mod store;
1618
pub mod winfs;
1719

1820
pub use culla_core::VERSION;

‎crates/adapters/src/store/key.rs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//! The file name of a source's session database and lock.
2+
3+
use culla_core::volume::SourceKey;
4+
5+
/// The `<key>` of `<key>.sqlite` and `<key>.lock`: 32 lowercase hex digits from the serial and
6+
/// the folded path (ADR 0008). Never the drive letter, so a card under another letter finds its
7+
/// session (US-09).
8+
///
9+
/// Provisional (proposed, SPEC §10): file-engine §2.2 names the first 16 bytes of
10+
/// `blake3(serial ‖ rel_key)`; BLAKE3 is not a dependency yet (it comes with the hashing of the
11+
/// copy steps), so this is FNV-1a 128 over a version tag, the serial (little endian) and the
12+
/// folded path, which has the same length. A collision cannot mix two sources: the database
13+
/// stores its source and [`super::SessionDb::open_at`] refuses another one
14+
/// ([`super::DbError::OtherSource`]). To switch to BLAKE3 before the first release, when no
15+
/// database exists yet.
16+
pub fn file_key(key: &SourceKey) -> String {
17+
const OFFSET: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
18+
const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
19+
let mut bytes = b"culla-session-v1\0".to_vec();
20+
bytes.extend_from_slice(&key.serial.to_le_bytes());
21+
bytes.extend_from_slice(key.rel_key.as_bytes());
22+
let mut h = OFFSET;
23+
for b in bytes {
24+
h ^= u128::from(b);
25+
h = h.wrapping_mul(PRIME);
26+
}
27+
format!("{h:032x}")
28+
}

‎crates/adapters/src/store/lock.rs‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
//! The source lock file `<key>.lock` next to each session database (design/file-engine.md
2+
//! §2.2): recovery and apply hold it for their whole duration, so no second process recovers or
3+
//! applies the same source.
4+
5+
use std::fmt;
6+
use std::fs::{File, OpenOptions, TryLockError};
7+
use std::io;
8+
use std::path::{Path, PathBuf};
9+
10+
use culla_core::volume::SourceKey;
11+
12+
/// A held source lock. Dropping it releases the lock; the file itself stays (Culla never
13+
/// removes it, and an unheld file means nothing).
14+
#[derive(Debug)]
15+
pub struct SourceLock {
16+
// Held for its lock: released when the handle closes.
17+
_file: File,
18+
key: SourceKey,
19+
path: PathBuf,
20+
}
21+
22+
/// Why the lock was not taken.
23+
#[derive(Debug)]
24+
pub enum LockError {
25+
/// Another holder has it (another instance applying or recovering this source): change
26+
/// nothing in its database and show the source as busy.
27+
Busy,
28+
/// The lock file could not be opened or created.
29+
Io(io::Error),
30+
}
31+
32+
impl fmt::Display for LockError {
33+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34+
match self {
35+
Self::Busy => f.write_str("the source is being applied or recovered elsewhere"),
36+
Self::Io(e) => write!(f, "the source lock could not be opened: {e}"),
37+
}
38+
}
39+
}
40+
41+
impl std::error::Error for LockError {
42+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
43+
match self {
44+
Self::Busy => None,
45+
Self::Io(e) => Some(e),
46+
}
47+
}
48+
}
49+
50+
impl SourceLock {
51+
/// The source this lock is for.
52+
pub fn key(&self) -> &SourceKey {
53+
&self.key
54+
}
55+
56+
/// The lock file.
57+
pub fn path(&self) -> &Path {
58+
&self.path
59+
}
60+
61+
/// Takes the lock at `path` for `key` without waiting: the file is created if missing
62+
/// (never truncated), opened with share mode 0 on Windows, and locked exclusively
63+
/// (`File::try_lock`) on every platform.
64+
pub(crate) fn acquire(path: PathBuf, key: SourceKey) -> Result<Self, LockError> {
65+
let file = match open(&path, true) {
66+
Ok(f) => f,
67+
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
68+
open(&path, false).map_err(busy_or_io)?
69+
}
70+
Err(e) => return Err(busy_or_io(e)),
71+
};
72+
match file.try_lock() {
73+
Ok(()) => Ok(Self {
74+
_file: file,
75+
key,
76+
path,
77+
}),
78+
Err(TryLockError::WouldBlock) => Err(LockError::Busy),
79+
Err(TryLockError::Error(e)) => Err(busy_or_io(e)),
80+
}
81+
}
82+
}
83+
84+
/// Opens the lock file for reading and writing, creating it only when `create_new` (so an
85+
/// existing file is never truncated or replaced).
86+
fn open(path: &Path, create_new: bool) -> io::Result<File> {
87+
let mut o = OpenOptions::new();
88+
o.read(true).write(true).create_new(create_new);
89+
#[cfg(windows)]
90+
{
91+
use std::os::windows::fs::OpenOptionsExt;
92+
o.share_mode(0);
93+
}
94+
o.open(path)
95+
}
96+
97+
/// `ERROR_SHARING_VIOLATION` (32) and `ERROR_LOCK_VIOLATION` (33) mean another holder.
98+
fn busy_or_io(e: io::Error) -> LockError {
99+
if cfg!(windows) && matches!(e.raw_os_error(), Some(32 | 33)) {
100+
LockError::Busy
101+
} else {
102+
LockError::Io(e)
103+
}
104+
}

0 commit comments

Comments
 (0)