Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ since the previous tag.

## [Unreleased]

### Desktop storage: a power cut loses only derived rows

The condition on D-A6's amendment (derived rows commit at
`synchronous=NORMAL`).

- **Tests:** `derive-crash-loss.test.ts` simulates a power cut after a
FULL append and a NORMAL derive, as a dropped last commit and as a torn
WAL tail. The append survives, the derived rows and `derived_seq` are
lost together, the document reads as stale, and the next derive
restores the rows. A control keeps the whole WAL and the derive.
- **Docs:** the architecture spec's D-A6 amendment records the approval
and points to the test.

**Deploy:** none.

### Desktop P2.6f: repair and rebuild the library

Repair and rebuild for the format-2 library (offline data-model revision
Expand Down
2 changes: 1 addition & 1 deletion docs/superpowers/specs/2026-11-15-desktop-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
| D-A3 | **Compaction runs in the renderer.** It sends `encodeStateAsUpdate` plus the highest `seq` that state covers. The worker upserts the snapshot and deletes `seq ≤ X` in one transaction. Main keeps a **registry of open documents**, which replaces leases. Main and the worker write content only to documents that are not open. No `rev` compare-and-set. | The renderer already holds the merged state, so compaction costs one encode. This is correct **only because a document is open in at most one window** (§5.2). The web library can't enforce one tab per document, so its compaction merges into the stored snapshot and deletes only the rows its own session applied (web library W-D3). That rule needs no invariant, and desktop can adopt it later. |
| D-A4 | **A thin `local-session`** (about 100 lines: load, apply, append, no timeouts) sits behind a `DocSession` interface, which `use-yjs-document` consumes. It and the batcher are platform-neutral (`lib/platform/local-session.ts`, `lib/platform/batcher.ts`), because the web library reuses them over IndexedDB (D3). The sandbox's `collab-session` is untouched except for the P1.1 and P1.1b fixes. The only shared editor changes: the provider becomes optional, and `document-editor.tsx` gets one stable y-protocols `Awareness`, under a byte allowance. (Live) The provider attaches on top of `local-session`. | Keeps the web path and its bundle as they are, and keeps desktop code small enough to read in one sitting. |
| D-A5 | **Local-release tables:** `meta` (with the `prefs` row), `docs`, `snapshots`, `updates` (with an `origin` column), `folders`, `tags` and `doc_tags` (D7), `doc_view` (per-document width, continue position and remote-image consent, D10), and the asset index `blobs` and `doc_blobs` (D4; the bytes are files under `<userData>/assets/`). `remotes`, `versions`, `share_blobs` and pre-wipe snapshots come in the Live release. A lineage UUID is written at creation from day one; `.tinydoc` import (P2.8) reads it to match backups. `docs.schema` stays, with a minimal migration hook that runs after hydrate and before the editor binds, as forward edits outside undo. Today's legacy-mark migrations run at **import**. | Ships only what the Local release uses, and keeps the two columns that are expensive to backfill. |
| D-A6 | **Safety core:** WAL, `synchronous=FULL`, `fullfsync` on macOS, `quick_check` after an unclean exit, the `format_version` read-only guard, `VACUUM INTO` before every migration, and a daily `VACUUM INTO` keeping 7 copies. The daily copies are the Local release's restore points ("Restore from a daily snapshot"). | One mechanism covers both restore points and protection against corruption, with no `versions` table. **Confirmed by S2:** the pragmas read back as set on all three OSes (`wal`, `synchronous` 2, and on macOS `fullfsync` and `checkpoint_fullfsync` 1); on an Apple-silicon Mac a 4 KB commit takes 4.0 ms p50 with `fullfsync` against 0.13 ms without it, so F_FULLFSYNC reaches the drive. |
| D-A6 | **Safety core:** WAL, `synchronous=FULL`, `fullfsync` on macOS, `quick_check` after an unclean exit, the `format_version` read-only guard, `VACUUM INTO` before every migration, and a daily `VACUUM INTO` keeping 7 copies. The daily copies are the Local release's restore points ("Restore from a daily snapshot"). | One mechanism covers both restore points and protection against corruption, with no `versions` table. **Confirmed by S2:** the pragmas read back as set on all three OSes (`wal`, `synchronous` 2, and on macOS `fullfsync` and `checkpoint_fullfsync` 1); on an Apple-silicon Mac a 4 KB commit takes 4.0 ms p50 with `fullfsync` against 0.13 ms without it, so F_FULLFSYNC reaches the drive. **Derived rows at `synchronous=NORMAL` (approved 2026-11-22, coordinator under the owner's delegation; the change is in #185):** derived rows are a cache written in one transaction with `derived_seq`, so a power cut loses them together and the document is derived again; content, identity and library state stay FULL. **Proven by** `tests/unit/desktop/storage/derive-crash-loss.test.ts`: a power cut after a FULL append and a NORMAL derive, simulated as a dropped last commit and as a torn WAL tail, keeps the append and loses the derived rows with their `derived_seq`; the document reads as stale and the next derive restores the rows. |
| D-A7 | **Readable backups:** changed documents are mirrored as `.tinydoc` plus `.md` into `~/TinyDocy Backups`, each written to a temp file and renamed. The renderer makes the Markdown on idle and on close with the existing Tiptap Markdown serializer and sends it to main. Retention is by count. | No DOM-free walker. Counting copies needs no clock-jump guard. |
| D-A8 | **Search matches metadata only, never document body text. No FTS5** (owner D24, plan v7). Searched: titles, tags, folder names and document properties (dates, Local/Live, template kind), on desktop and in the web library. One shared normalizer (`lib/search/normalize.ts`: diacritics, Arabic→Persian letter folding, Persian/Arabic-Indic digits → ASCII; `Intl.Segmenter` only if titles need it) makes Quick Open and list filters accent- and case-insensitive. Metadata operators: `tag:`, `in:folder`, `is:live`. Rows with `kind='template'` are skipped. Full-text body search is later and not planned. Identity stays in `localStorage` (`tinydocy-user`, validated by F2: try/catch, a 32-grapheme name, an allowlisted colour) until P4.0 moves it into `meta('identity')`. | Cuts the walker, the FTS table, the text extractor and the identity migration from v1. Metadata is already in `docs`, `folders` and `doc_tags`, so search needs no new index. |
| D-A9 | **Local-release ports:** `DocSession`, `DocStore`, `DocumentIndex`, `AppShell`, and `BlobStore` for images (D4). (Live) adds `SyncAttachment`, `ShareService` and `SecretStore`. Each port is chosen inside a composition-root component. The two roots are `app/page.tsx` and `app/page.desktop.tsx`, picked through `pageExtensions`: the desktop target lists only `desktop.tsx` and `desktop.ts`, so its routes are an allowlist and no file is moved for the export (§3.1, P2.4b). Hand-written guards run in main only. The IPC build version is checked at startup. The staged app folder holds CJS bundles made by Bun.build (S1 confirmed CJS; S3 packages it). | One literal decides the target. Neither build carries the other's import graph. The signed main bundle gets no validation dependency. |
Expand Down
164 changes: 164 additions & 0 deletions tests/unit/desktop/storage/derive-crash-loss.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/**
* The condition on D-A6's amendment (derived rows commit at
* `synchronous=NORMAL`): a power cut may lose the last derive commit while
* the content append before it, committed FULL, survives. The derived rows
* and `derived_seq` are lost together, so the document reads as stale and
* the next derive puts them back.
*
* A power cut is simulated on the files. Right after the FULL append the
* main file and the WAL are what a synced disk holds; the derive then adds
* frames that were never synced. After a crash the main file is put back
* and the WAL is cut to the append's end (the derive's commit dropped) or
* into the derive's first frame (a torn tail). Closing the connection would
* checkpoint the WAL into the main file, hence the copy taken before it.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
existsSync,
readFileSync,
rmSync,
statSync,
truncateSync,
writeFileSync,
} from "node:fs";
import { join } from "node:path";

import * as Y from "yjs";

import type { DerivedRows } from "@/desktop/storage/engine/derive";
import { LIBRARY_FILE, type Library } from "@/desktop/storage/engine/library";
import {
crash,
createClock,
createTempDir,
createTestHost,
openTestLibrary,
} from "@/tests/helpers/storage-library";

const TARGET = "ab".repeat(16);

let temp: ReturnType<typeof createTempDir>;
const open: Library[] = [];

beforeEach(() => {
temp = createTempDir();
});
afterEach(() => {
for (const library of open.splice(0)) library.shutdown();
temp.cleanUp();
});

function openLibrary(): Library {
const library = openTestLibrary(temp.dir, createTestHost(createClock()));
open.push(library);
return library;
}

const rows: DerivedRows = {
links: [
{
ord: 0,
src_toc_id: "",
target_key: TARGET,
target_toc_id: "",
text: "see",
context: "see the other one",
},
],
headings: [{ ord: 0, toc_id: "h1", level: 1, text: "Intro" }],
title: "Linked",
snippet: "snippet",
};

function textOf(library: Library, id: string): string {
const content = library.load(id, "check");
const doc = new Y.Doc();
if (content.snapshot) Y.applyUpdate(doc, content.snapshot);
for (const update of content.updates) Y.applyUpdate(doc, update);
library.close(id, "check");
return doc.getText("t").toString();
}

/**
* One document with a FULL append and a NORMAL derive after it. Returns the
* files as they stood after the append, and the WAL's length then.
*/
function appendThenDerive() {
const path = join(temp.dir, LIBRARY_FILE);
const library = openLibrary();
const { id } = library.createDoc({ title: "Linked" });
library.load(id, "w");
const doc = new Y.Doc();
doc.getText("t").insert(0, "kept");
const seq = library.append(id, "w", {
origin: "local",
update: Y.encodeStateAsUpdate(doc),
});
library.close(id, "w");
// What a synced disk holds now: the FULL append is in the WAL.
const main = readFileSync(path);
const walEnd = statSync(`${path}-wal`).size;
expect(walEnd).toBeGreaterThan(0);
expect(library.putDerived(id, seq, rows)).toBe("ok");
expect(library.backlinks(TARGET)).toHaveLength(1);
const wal = readFileSync(`${path}-wal`);
expect(wal.byteLength).toBeGreaterThan(walEnd);
crash(library);
open.splice(open.indexOf(library), 1);
return { id, seq, path, main, wal, walEnd };
}

/** Puts the "synced" files back, the WAL cut at `walLength`. */
function powerCut(
files: ReturnType<typeof appendThenDerive>,
walLength: number,
) {
writeFileSync(files.path, files.main);
writeFileSync(`${files.path}-wal`, files.wal);
truncateSync(`${files.path}-wal`, walLength);
// A cold start: the WAL index is rebuilt from the WAL itself.
if (existsSync(`${files.path}-shm`)) rmSync(`${files.path}-shm`);
}

describe("a power cut after a NORMAL derive commit (D-A6 amendment)", () => {
const cuts: [
string,
(files: ReturnType<typeof appendThenDerive>) => number,
][] = [
["the derive's commit is dropped", (files) => files.walEnd],
// 32-byte WAL header, then frames of a 24-byte header and one page.
[
"the WAL tail is torn inside the derive's first frame",
(files) => files.walEnd + 24 + 100,
],
];

for (const [name, cutAt] of cuts)
test(name, () => {
const files = appendThenDerive();
powerCut(files, cutAt(files));

const library = openLibrary();
expect(library.status.uncleanExit).toBe(true);
expect(library.status.quickCheck).toBe("ok");
expect(library.status.readOnly).toBeNull();
// The FULL append survived; the derive did not.
expect(textOf(library, files.id)).toBe("kept");
expect(library.backlinks(TARGET)).toEqual([]);
// derived_seq went with its rows: the document reads as stale.
expect(library.nextStale()).toBe(files.id);

// The derive queue puts the rows back.
expect(library.putDerived(files.id, files.seq, rows)).toBe("ok");
expect(library.backlinks(TARGET)).toHaveLength(1);
expect(library.nextStale()).toBeNull();
});

test("control: with the WAL whole, the derive survives the crash", () => {
const files = appendThenDerive();
powerCut(files, files.wal.byteLength);
const library = openLibrary();
expect(library.backlinks(TARGET)).toHaveLength(1);
expect(library.nextStale()).toBeNull();
});
});
Loading