Skip to content
Draft
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
7 changes: 3 additions & 4 deletions apps/cloud/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2069,10 +2069,9 @@ export function startCloud(
);
}

// Clear one page's edit history (#56): raises the truncation floor to
// just below the head and drops the unreachable ops + snapshots. Live
// bytes are untouched; storage frees immediately; lagging clients
// re-bootstrap via the #52 410/OpsTruncated path. Irreversible.
// Clear older history below the page's truncation floor. Live bytes
// are untouched; lagging clients re-bootstrap via 410. The response
// reports what was removed and whether older checkpoints remain.
const clearMatch =
/^\/api\/documents\/([^/]+)\/pages\/([^/]+)\/clear-history$/.exec(path);
if (clearMatch && req.method === "POST") {
Expand Down
16 changes: 12 additions & 4 deletions apps/cloud/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,14 +573,15 @@ export class CloudStore {
* bytes stay identical; lagging clients re-bootstrap via 410), then every
* snapshot pinned below the floor (unreachable by stateAt, revert markers
* included) is retired in that transaction. Files are removed after commit
* and usage triggers refund the bytes. No-op for blob pages and pages with no
* history before the current operation.
* and usage triggers refund the bytes. Checkpoints at/above the floor can
* share an op seq (notably tablet text edits at seq 0). Keep them: offline
* tablets can still name an older checkpoint as the base of their edits.
*/
clearPageHistory(
user: string,
doc: string,
page: string,
): { opsDeleted: number; snapshotsDeleted: number; floor: number } {
): { opsDeleted: number; snapshotsDeleted: number; floor: number; olderCheckpointsRetained: boolean } {
return this.publishPage(user, doc, page, () => {
// After a successful clear only the head operation remains. Do not
// create another checkpoint (and revision) when there is nothing to clear.
Expand All @@ -597,7 +598,14 @@ export class CloudStore {
).all(user, doc, page, floor);
this.notePrunedPublications(user, doc, page, retired);
for (const row of retired) this.retiredPageFiles!.push(row.path);
return { opsDeleted, snapshotsDeleted: retired.length, floor };
const latest = this.db.query<{ op_seq: number }, [string, string, string]>(
`SELECT op_seq FROM page_snapshots
WHERE user_id=? AND doc=? AND page=? ORDER BY seq DESC LIMIT 2`,
).all(user, doc, page);
// A sole checkpoint is also restorable if newer ops follow it.
const olderCheckpointsRetained = latest.length > 1 ||
(latest[0] !== undefined && latest[0].op_seq < this.latestOpSeq(user, doc, page));
return { opsDeleted, snapshotsDeleted: retired.length, floor, olderCheckpointsRetained };
});
}

Expand Down
4 changes: 3 additions & 1 deletion apps/cloud/test/page-publication.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,9 @@ test.each(['ABORT', 'ROLLBACK'] as const)('a refused history clear (%s) preserve
expect(store.getSnapshotBytes(...page, seq)).toBeNull()
const cleared = store.deviceRevision(...page)
const kept = readdirSync(path + '-files/snapshots').sort()
expect(store.clearPageHistory(...page)).toEqual({ opsDeleted: 0, snapshotsDeleted: 0, floor: 2 })
expect(store.clearPageHistory(...page)).toEqual({
opsDeleted: 0, snapshotsDeleted: 0, floor: 2, olderCheckpointsRetained: true,
})
expect(store.deviceRevision(...page)).toBe(cleared)
expect(readdirSync(path + '-files/snapshots').sort()).toEqual(kept)
} finally {
Expand Down
82 changes: 80 additions & 2 deletions apps/cloud/test/truncation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { BelowFloorError, CloudStore, CheckpointUnavailableError } from "../src/store";
import { startCloud, type CloudServer } from "../src/server";
import { Pen, PenColor, RmDocument, crdtId } from "@weft/rm-format";
import { Pen, PenColor, RmDocument, crdtId, createRootText, insertText } from "@weft/rm-format";
import { polylineToPoints, type Xy } from "@weft/rm-ink/pure";
import {
applyOps,
Expand Down Expand Up @@ -497,11 +497,13 @@ test("POST /clear-history: live bytes identical, storage freed, old points gone,
opsDeleted: number;
snapshotsDeleted: number;
floor: number;
olderCheckpointsRetained: boolean;
};
// Clear history retains the head op. Usage counter updates are not ops.
expect(body.opsDeleted).toBe(opsBefore - 1);
expect(body.snapshotsDeleted).toBeGreaterThan(0); // the old checkpoints
expect(body.floor).toBeGreaterThan(0);
expect(body.olderCheckpointsRetained).toBe(true); // boundary checkpoint

// the live page is byte-identical
const liveAfter = await (
Expand Down Expand Up @@ -533,7 +535,9 @@ test("POST /clear-history: live bytes identical, storage freed, old points gone,
`${base}/api/documents/${DOC}/pages/${PAGE}/clear-history`,
{ method: "POST", headers: h() },
);
expect(((await again.json()) as { opsDeleted: number }).opsDeleted).toBe(0);
expect(await again.json()).toEqual({
opsDeleted: 0, snapshotsDeleted: 0, floor: body.floor, olderCheckpointsRetained: true,
});
// and the retained tail still streams fine from the floor
expect(
(
Expand All @@ -546,6 +550,80 @@ test("POST /clear-history: live bytes identical, storage freed, old points gone,
});


test("POST /clear-history reports retained same-cursor tablet checkpoints without changing them", async () => {
const DOC = "clear-tablet";
const PAGE = "clear-tablet";
const token = server.store.mintDeviceToken(USER, "clear history tablet");
const endpoint = `${base}/api/documents/${DOC}/pages/${PAGE}`;
const deviceHeaders = { "x-device-token": token };
const native = RmDocument.empty(WEB_AUTHOR);
const put = (revision?: string) => fetch(endpoint + "/rm", {
method: "PUT",
headers: { ...deviceHeaders, ...(revision ? { "x-base-revision": revision } : {}) },
body: native.serialize() as unknown as BodyInit,
});
const history = () => fetch(endpoint + "/history", { headers: h() });
const clear = async () => {
const response = await fetch(endpoint + "/clear-history", { method: "POST", headers: h() });
expect(response.status).toBe(200);
return response.json();
};

expect((await put()).status).toBe(200);
const seeded = await (await history()).json();
expect(seeded.points).toHaveLength(1);
expect(await clear()).toEqual({
opsDeleted: 0, snapshotsDeleted: 0, floor: 0, olderCheckpointsRetained: false,
});

const first = await fetch(endpoint + "/rm", { headers: deviceHeaders });
const tokenAtFirst = first.headers.get("x-rm-revision")!;
createRootText(native);
insertText(native, null, "tablet edit", { authorUuid: WEB_AUTHOR });
expect((await put(tokenAtFirst)).status).toBe(200);
const before = await (await history()).json();
expect(before.head).toBe(0);
expect(before.points.map(({ kind }: { kind: string }) => kind)).toEqual(["snapshot", "snapshot"]);
const bytesBefore = await (await fetch(endpoint + "/rm", { headers: deviceHeaders })).arrayBuffer();
const quotaBefore = server.store.usageBytes(USER, "created");

expect(await clear()).toEqual({
opsDeleted: 0, snapshotsDeleted: 0, floor: 0, olderCheckpointsRetained: true,
});
expect(await (await history()).json()).toEqual(before);
expect(server.store.usageBytes(USER, "created")).toBe(quotaBefore);
expect(await (await fetch(endpoint + "/rm", { headers: deviceHeaders })).arrayBuffer()).toEqual(bytesBefore);
expect(server.store.getSnapshotBytes(USER, DOC, PAGE, seeded.points[0].snapSeq)).not.toBeNull();
});

test("POST /clear-history reports a sole checkpoint older than the live head", async () => {
const doc = "clear-single-checkpoint";
const page = "page";
const endpoint = `${base}/api/documents/${doc}/pages/${page}`;
const snapSeq = server.store.putSnapshot(USER, doc, page,
encodeSnapshot(RmDocument.empty(WEB_AUTHOR).serialize(), { shapes: [] }));
server.store.appendOps(USER, doc, page, [encodeOp({
op: "delete-object", id: "removed-object", version: { ts: 1, actor: "browser" },
})], "browser");
const history = () => fetch(endpoint + "/history", { headers: h() }).then(r => r.json());
const before = await history();
expect(before.head).toBeGreaterThan(0);
expect(before.points.filter(({ kind }: { kind: string }) => kind === "snapshot")).toEqual([
expect.objectContaining({ seq: 0, snapSeq }),
]);
const response = await fetch(endpoint + "/clear-history", { method: "POST", headers: h() });
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
opsDeleted: 0, snapshotsDeleted: 0, floor: 0, olderCheckpointsRetained: true,
});
expect(await history()).toEqual(before);
const restore = await fetch(endpoint + "/revert", {
method: "POST", headers: h({ "content-type": "application/json" }),
body: JSON.stringify({ toSnapshot: snapSeq }),
});
expect(restore.status).toBe(200);
});

test("missing or corrupt history checkpoint refuses reads, reverts and trimming until restored", async () => {
const dir = mkdtempSync(join(tmpdir(), "weft-required-checkpoint-"));
const relay = startCloud({ port: 0, db: join(dir, "t.db") });
Expand Down
Loading
Loading