Skip to content

Build your personal knowledge base with Trilium Notes

core/content manager: implement a space usage service

Adorian Doranf8e03c990a45
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index ff98a71750..52f31783c7 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -232,6 +232,79 @@ export interface SubtreeSizeResponse {
subTreeSize: number;
}
+/**
+ * The size components of a single note. Revisions are always reported separately so a client can
+ * include or exclude them without another request.
+ */
+export interface SpaceUsageSizes {
+ /** Size of the note's own body. */
+ ownSize: number;
+ /** Combined size of the attachments owned by the note. */
+ attachmentsSize: number;
+ /** Combined size of the note's revisions, including attachments owned by those revisions. */
+ revisionsSize: number;
+}
+
+export interface SpaceUsageOverviewNote extends SpaceUsageSizes {
+ noteId: string;
+ /**
+ * Note IDs from a top-level note down to this note, following each note's canonical placement
+ * (see the space usage service); the root itself is omitted.
+ */
+ notePath: string[];
+}
+
+/** An aggregate over notes that are not listed individually. */
+export interface SpaceUsageBucket {
+ /** Note bodies plus attachments; revisions are in {@link revisionsSize}. */
+ size: number;
+ revisionsSize: number;
+ noteCount: number;
+}
+
+/** Space still held by deleted entities whose blobs have not been erased yet. */
+export interface SpaceUsageDeletedNotes {
+ size: number;
+ /** Deleted notes whose body blob still exists; erased notes no longer count. */
+ noteCount: number;
+}
+
+export interface SpaceUsageOverviewResponse {
+ /** The largest notes first, ranked by body + attachments (+ revisions when requested). */
+ notes: SpaceUsageOverviewNote[];
+ /** The remaining notes of the visible tree, below the ranking cutoff. */
+ otherNotes: SpaceUsageBucket;
+ /** Notes reachable only through the hidden subtree, plus any note not reachable at all. */
+ hiddenNotes: SpaceUsageBucket;
+ deletedNotes: SpaceUsageDeletedNotes;
+ /** Every note of the visible tree: {@link notes} and {@link otherNotes} combined. */
+ total: SpaceUsageBucket;
+}
+
+export interface SpaceUsageChild {
+ noteId: string;
+ /** Bodies plus attachments of the child's whole canonical subtree. */
+ subtreeSize: number;
+ subtreeRevisionsSize: number;
+ subtreeNoteCount: number;
+}
+
+export interface SpaceUsageAttachment {
+ attachmentId: string;
+ title: string;
+ role: string;
+ size: number;
+}
+
+export interface SpaceUsageNoteResponse extends SpaceUsageSizes {
+ noteId: string;
+ attachments: SpaceUsageAttachment[];
+ /** Canonical children only: a cloned child is listed under its canonical parent alone. */
+ children: SpaceUsageChild[];
+ /** Only present on the root, deleted notes having no place in the tree. */
+ deletedNotes?: SpaceUsageDeletedNotes;
+}
+
export interface SimilarNote {
score: number;
notePath: string[];
diff --git a/packages/trilium-core/src/routes/api/space_usage.spec.ts b/packages/trilium-core/src/routes/api/space_usage.spec.ts
new file mode 100644
index 0000000000..1d06d2e8a6
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/space_usage.spec.ts
@@ -0,0 +1,163 @@
+import { SpaceUsageNoteResponse, SpaceUsageOverviewResponse } from "@triliumnext/commons";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { CoreApiTester } from "../../test/api_tester";
+import { createTextNote, type CreatedNote } from "../../test/api_fixtures";
+
+let api: CoreApiTester;
+let parent: CreatedNote;
+let child: CreatedNote;
+let cloneTarget: CreatedNote;
+let revisionHeavy: CreatedNote;
+
+const PARENT_CONTENT = "<p>0123456789</p>";
+const CHILD_CONTENT = `<p>${"x".repeat(5000)}</p>`;
+const ATTACHMENT_CONTENT = "0123456789";
+// Heavier than the child's body + attachment + revision combined, so that including revisions in
+// the ranking demonstrably reorders the two.
+const REVISION_HEAVY_CONTENT = `<p>${"r".repeat(12000)}</p>`;
+
+async function getOverview(query: Record<string, string | number | boolean> = {}) {
+ const res = await api.get<SpaceUsageOverviewResponse>("/api/space-usage/overview", { query });
+ expect(res.status).toBe(200);
+ return res.body;
+}
+
+async function getNoteUsage(noteId: string) {
+ const res = await api.get<SpaceUsageNoteResponse>(`/api/space-usage/note/${noteId}`);
+ expect(res.status).toBe(200);
+ return res.body;
+}
+
+describe("Space usage API (core)", () => {
+ beforeAll(async () => {
+ api = CoreApiTester.build();
+
+ parent = await createTextNote(api, { title: "Space usage parent", content: PARENT_CONTENT });
+ child = await createTextNote(api, {
+ parentNoteId: parent.noteId,
+ title: "Space usage child",
+ content: CHILD_CONTENT
+ });
+ cloneTarget = await createTextNote(api, { title: "Space usage clone target", content: "<p>tiny</p>" });
+
+ const attachmentRes = await api.post(`/api/notes/${child.noteId}/attachments`, {
+ body: { role: "file", mime: "text/plain", title: "Space usage attachment", content: ATTACHMENT_CONTENT }
+ });
+ expect(attachmentRes.status).toBe(204);
+
+ const revisionRes = await api.post(`/api/notes/${child.noteId}/revision`);
+ expect(revisionRes.status).toBe(200);
+
+ const cloneRes = await api.put(`/api/notes/${child.noteId}/clone-to-note/${cloneTarget.noteId}`, { body: {} });
+ expect(cloneRes.status).toBe(200);
+
+ // A note whose weight sits almost entirely in its revision: big content revisioned away,
+ // then replaced by a small body.
+ revisionHeavy = await createTextNote(api, { title: "Space usage revision heavy", content: REVISION_HEAVY_CONTENT });
+ const heavyRevisionRes = await api.post(`/api/notes/${revisionHeavy.noteId}/revision`);
+ expect(heavyRevisionRes.status).toBe(200);
+ const shrinkRes = await api.put(`/api/notes/${revisionHeavy.noteId}/data`, {
+ body: { content: "<p>s</p>" }
+ });
+ expect(shrinkRes.status).toBe(204);
+ });
+
+ it("lists a large note with its size components and canonical path", async () => {
+ const overview = await getOverview({ limit: 1000 });
+ const entry = overview.notes.find((note) => note.noteId === child.noteId);
+
+ expect(entry?.ownSize).toBe(CHILD_CONTENT.length);
+ expect(entry?.attachmentsSize).toBe(ATTACHMENT_CONTENT.length);
+ expect(entry?.revisionsSize).toBeGreaterThanOrEqual(CHILD_CONTENT.length);
+ // Canonical placement is the original parent, not the later clone target.
+ expect(entry?.notePath).toEqual([ parent.noteId, child.noteId ]);
+ });
+
+ it("orders by size, respects the limit and buckets the rest", async () => {
+ const overview = await getOverview({ limit: 1000 });
+ const noteIds = overview.notes.map((note) => note.noteId);
+ expect(noteIds.indexOf(child.noteId)).toBeLessThan(noteIds.indexOf(parent.noteId));
+
+ // The hidden subtree exists in every database, so it always has notes to aggregate.
+ expect(overview.hiddenNotes.noteCount).toBeGreaterThan(0);
+ expect(overview.total.noteCount).toBe(overview.notes.length + overview.otherNotes.noteCount);
+
+ const limited = await getOverview({ limit: 1 });
+ expect(limited.notes.length).toBe(1);
+ expect(limited.otherNotes.noteCount).toBe(limited.total.noteCount - 1);
+ });
+
+ it("keeps zero-sized notes out of the individual listing", async () => {
+ const empty = await createTextNote(api, { title: "Space usage empty", content: "" });
+ const overview = await getOverview({ limit: 1000 });
+
+ expect(overview.notes.some((note) => note.noteId === empty.noteId)).toBe(false);
+ });
+
+ it("moves revision weight into the ranking only when asked to", async () => {
+ const withoutRevisions = await getOverview({ limit: 1000 });
+ const heavyEntry = withoutRevisions.notes.find((note) => note.noteId === revisionHeavy.noteId);
+ expect(heavyEntry?.revisionsSize).toBeGreaterThanOrEqual(REVISION_HEAVY_CONTENT.length);
+
+ const rankWithout = withoutRevisions.notes.map((note) => note.noteId);
+ expect(rankWithout.indexOf(child.noteId)).toBeLessThan(rankWithout.indexOf(revisionHeavy.noteId));
+
+ const withRevisions = await getOverview({ limit: 1000, includeRevisions: true });
+ const rankWith = withRevisions.notes.map((note) => note.noteId);
+ expect(rankWith.indexOf(revisionHeavy.noteId)).toBeLessThan(rankWith.indexOf(child.noteId));
+ });
+
+ it("returns a note's children with whole-subtree totals", async () => {
+ const usage = await getNoteUsage(parent.noteId);
+
+ expect(usage.ownSize).toBe(PARENT_CONTENT.length);
+ expect(usage.deletedNotes).toBeUndefined();
+
+ const childEntry = usage.children.find((entry) => entry.noteId === child.noteId);
+ expect(childEntry?.subtreeSize).toBe(CHILD_CONTENT.length + ATTACHMENT_CONTENT.length);
+ expect(childEntry?.subtreeRevisionsSize).toBeGreaterThanOrEqual(CHILD_CONTENT.length);
+ expect(childEntry?.subtreeNoteCount).toBe(1);
+ });
+
+ it("counts a cloned note only under its canonical parent", async () => {
+ const usage = await getNoteUsage(cloneTarget.noteId);
+
+ expect(usage.children.some((entry) => entry.noteId === child.noteId)).toBe(false);
+ });
+
+ it("lists a note's attachments individually", async () => {
+ const usage = await getNoteUsage(child.noteId);
+ const attachment = usage.attachments.find((entry) => entry.title === "Space usage attachment");
+
+ expect(attachment?.role).toBe("file");
+ expect(attachment?.size).toBe(ATTACHMENT_CONTENT.length);
+ expect(usage.children).toEqual([]);
+ });
+
+ it("reports space held by deleted notes, at the root only", async () => {
+ const doomed = await createTextNote(api, {
+ title: "Space usage doomed",
+ content: `<p>${"space-usage-doomed-".repeat(200)}</p>`
+ });
+ const doomedSize = `<p>${"space-usage-doomed-".repeat(200)}</p>`.length;
+
+ const deleteRes = await api.delete(`/api/notes/${doomed.noteId}`, {
+ query: { taskId: "space-usage-spec", last: true }
+ });
+ expect([ 200, 204 ]).toContain(deleteRes.status);
+
+ const overview = await getOverview({ limit: 1000 });
+ expect(overview.notes.some((note) => note.noteId === doomed.noteId)).toBe(false);
+ expect(overview.deletedNotes.size).toBeGreaterThanOrEqual(doomedSize);
+ expect(overview.deletedNotes.noteCount).toBeGreaterThanOrEqual(1);
+
+ const rootUsage = await getNoteUsage("root");
+ expect(rootUsage.deletedNotes?.size).toBeGreaterThanOrEqual(doomedSize);
+ });
+
+ it("404s for a missing note", async () => {
+ const res = await api.get("/api/space-usage/note/spaceUsageMissing");
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/space_usage.ts b/packages/trilium-core/src/routes/api/space_usage.ts
new file mode 100644
index 0000000000..c188845a63
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/space_usage.ts
@@ -0,0 +1,29 @@
+import type { Request } from "express";
+
+import {
+ DEFAULT_OVERVIEW_LIMIT,
+ getNoteUsage as getNoteUsageFromService,
+ getOverview as getOverviewFromService,
+ MAX_OVERVIEW_LIMIT
+} from "../../services/space_usage.js";
+
+function getOverview(req: Request) {
+ const requested = Number.parseInt(String(req.query.limit ?? ""), 10);
+ const limit = Number.isNaN(requested)
+ ? DEFAULT_OVERVIEW_LIMIT
+ : Math.min(Math.max(requested, 1), MAX_OVERVIEW_LIMIT);
+
+ return getOverviewFromService({
+ includeRevisions: req.query.includeRevisions === "true",
+ limit
+ });
+}
+
+function getNoteUsage(req: Request<{ noteId: string }>) {
+ return getNoteUsageFromService(req.params.noteId);
+}
+
+export default {
+ getOverview,
+ getNoteUsage
+};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 9edf775393..e339ecbb9b 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -9,6 +9,7 @@ import otherRoute from "./api/others";
import branchesApiRoute from "./api/branches";
import appInfoRoute from "./api/app_info";
import statsRoute from "./api/stats";
+import spaceUsageRoute from "./api/space_usage";
import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity";
import cloningApiRoute from "./api/cloning";
import sqlRoute from "./api/sql";
@@ -201,6 +202,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
apiRoute(GET, "/api/stats/note-size/:noteId", statsRoute.getNoteSize);
apiRoute(GET, "/api/stats/subtree-size/:noteId", statsRoute.getSubtreeSize);
+ apiRoute(GET, "/api/space-usage/overview", spaceUsageRoute.getOverview);
+ apiRoute(GET, "/api/space-usage/note/:noteId", spaceUsageRoute.getNoteUsage);
+
apiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);
apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);
diff --git a/packages/trilium-core/src/services/space_usage.spec.ts b/packages/trilium-core/src/services/space_usage.spec.ts
new file mode 100644
index 0000000000..05a0fc4a26
--- /dev/null
+++ b/packages/trilium-core/src/services/space_usage.spec.ts
@@ -0,0 +1,143 @@
+import { SpaceUsageSizes } from "@triliumnext/commons";
+import { describe, expect, it } from "vitest";
+
+import { buildCanonicalForest, buildNotePath, computeSubtreeTotals } from "./space_usage.js";
+
+/** Builds a forest from a plain parent → ordered children map; extras model orphan roots. */
+function forestOf(edges: Record<string, string[]>, extraNoteIds: string[] = []) {
+ const allNoteIds = new Set<string>(extraNoteIds);
+
+ for (const [ parentId, childIds ] of Object.entries(edges)) {
+ allNoteIds.add(parentId);
+ childIds.forEach((childId) => allNoteIds.add(childId));
+ }
+
+ return buildCanonicalForest((noteId) => edges[noteId] ?? [], allNoteIds);
+}
+
+function sizeLookup(sizes: Record<string, Partial<SpaceUsageSizes>>) {
+ return (noteId: string): SpaceUsageSizes => ({
+ ownSize: sizes[noteId]?.ownSize ?? 0,
+ attachmentsSize: sizes[noteId]?.attachmentsSize ?? 0,
+ revisionsSize: sizes[noteId]?.revisionsSize ?? 0
+ });
+}
+
+describe("buildCanonicalForest", () => {
+ it("mirrors a plain tree: breadth-first order, parents and ordered children", () => {
+ const forest = forestOf({ root: [ "a", "b" ], a: [ "c" ] });
+
+ expect(forest.userNoteIds).toEqual([ "root", "a", "b", "c" ]);
+ expect(forest.hiddenNoteIds).toEqual([]);
+ expect(forest.childrenByNoteId.get("root")).toEqual([ "a", "b" ]);
+ expect(forest.childrenByNoteId.get("a")).toEqual([ "c" ]);
+ expect(forest.parentByNoteId.get("c")).toBe("a");
+ expect(forest.parentByNoteId.has("root")).toBe(false);
+ });
+
+ it("adopts a note cloned under two same-depth parents at the earlier sibling", () => {
+ const forest = forestOf({ root: [ "a", "b" ], a: [ "x" ], b: [ "x" ] });
+
+ expect(forest.parentByNoteId.get("x")).toBe("a");
+ expect(forest.childrenByNoteId.get("b")).toBeUndefined();
+ });
+
+ it("adopts a note cloned at several depths at the shallowest one", () => {
+ const forest = forestOf({ root: [ "a", "y" ], a: [ "y" ] });
+
+ expect(forest.parentByNoteId.get("y")).toBe("root");
+ expect(forest.childrenByNoteId.get("a")).toBeUndefined();
+ });
+
+ it("walks the hidden subtree last, so a note cloned into both worlds stays a user note", () => {
+ // `bm` models a bookmark: a user note cloned under the hidden bookmarks folder.
+ const forest = forestOf({
+ root: [ "_hidden", "a" ],
+ _hidden: [ "h1", "bm" ],
+ a: [ "bm" ]
+ });
+
+ expect(forest.userNoteIds).toEqual([ "root", "a", "bm" ]);
+ expect(forest.hiddenNoteIds).toEqual([ "_hidden", "h1" ]);
+ expect(forest.parentByNoteId.get("bm")).toBe("a");
+ // The hidden subtree lists after the visible children, whatever the branch order was.
+ expect(forest.childrenByNoteId.get("root")).toEqual([ "a", "_hidden" ]);
+ expect(forest.parentByNoteId.get("_hidden")).toBe("root");
+ });
+
+ it("sweeps unreachable notes and their subtrees into the hidden collection", () => {
+ const forest = forestOf({ root: [ "a" ], lost: [ "lostChild" ] }, [ "lost" ]);
+
+ expect(forest.userNoteIds).toEqual([ "root", "a" ]);
+ expect(forest.hiddenNoteIds).toEqual([ "lost", "lostChild" ]);
+ expect(forest.parentByNoteId.get("lostChild")).toBe("lost");
+ expect(forest.parentByNoteId.has("lost")).toBe(false);
+ });
+
+ it("terminates on a detached cycle, adopting each note once", () => {
+ const forest = forestOf({ root: [], one: [ "two" ], two: [ "one" ] }, [ "one", "two" ]);
+
+ expect([ ...forest.hiddenNoteIds ].sort()).toEqual([ "one", "two" ]);
+ expect(forest.hiddenNoteIds.length).toBe(2);
+ });
+});
+
+describe("computeSubtreeTotals", () => {
+ it("sums bodies with attachments, keeps revisions apart and counts notes", () => {
+ const forest = forestOf({ root: [ "a", "b" ], a: [ "c" ] });
+ const totals = computeSubtreeTotals(forest, sizeLookup({
+ a: { ownSize: 10, attachmentsSize: 5, revisionsSize: 2 },
+ b: { ownSize: 3 },
+ c: { ownSize: 1, revisionsSize: 1 }
+ }));
+
+ expect(totals.get("c")).toEqual({ size: 1, revisionsSize: 1, noteCount: 1 });
+ expect(totals.get("a")).toEqual({ size: 16, revisionsSize: 3, noteCount: 2 });
+ expect(totals.get("root")).toEqual({ size: 19, revisionsSize: 3, noteCount: 4 });
+ });
+
+ it("counts a note cloned into the hidden subtree in its user placement only", () => {
+ const forest = forestOf({
+ root: [ "_hidden", "a" ],
+ _hidden: [ "bm" ],
+ a: [ "bm" ]
+ });
+ const totals = computeSubtreeTotals(forest, sizeLookup({ bm: { ownSize: 7 } }));
+
+ expect(totals.get("a")?.size).toBe(7);
+ expect(totals.get("_hidden")).toEqual({ size: 0, revisionsSize: 0, noteCount: 1 });
+ // The hidden subtree still folds into the root, so the root total covers everything.
+ expect(totals.get("root")).toEqual({ size: 7, revisionsSize: 0, noteCount: 4 });
+ });
+
+ it("survives a pathologically deep chain without recursing", () => {
+ const edges: Record<string, string[]> = {};
+ let current = "root";
+ for (let i = 0; i < 2000; i++) {
+ const next = `n${i}`;
+ edges[current] = [ next ];
+ current = next;
+ }
+
+ const forest = forestOf(edges);
+ const totals = computeSubtreeTotals(forest, () => ({ ownSize: 1, attachmentsSize: 0, revisionsSize: 0 }));
+
+ expect(totals.get("root")).toEqual({ size: 2001, revisionsSize: 0, noteCount: 2001 });
+ });
+});
+
+describe("buildNotePath", () => {
+ it("walks canonical parents from a top-level note down, omitting the root", () => {
+ const forest = forestOf({ root: [ "a" ], a: [ "b" ], b: [ "c" ] });
+
+ expect(buildNotePath(forest.parentByNoteId, "c")).toEqual([ "a", "b", "c" ]);
+ expect(buildNotePath(forest.parentByNoteId, "a")).toEqual([ "a" ]);
+ expect(buildNotePath(forest.parentByNoteId, "root")).toEqual([]);
+ });
+
+ it("gives an orphan a path of itself", () => {
+ const forest = forestOf({ root: [] }, [ "lost" ]);
+
+ expect(buildNotePath(forest.parentByNoteId, "lost")).toEqual([ "lost" ]);
+ });
+});
diff --git a/packages/trilium-core/src/services/space_usage.ts b/packages/trilium-core/src/services/space_usage.ts
new file mode 100644
index 0000000000..b1d4f52312
--- /dev/null
+++ b/packages/trilium-core/src/services/space_usage.ts
@@ -0,0 +1,374 @@
+import {
+ SpaceUsageBucket,
+ SpaceUsageDeletedNotes,
+ SpaceUsageNoteResponse,
+ SpaceUsageOverviewResponse,
+ SpaceUsageSizes
+} from "@triliumnext/commons";
+
+import becca from "../becca/becca.js";
+import { getSql } from "./sql/index.js";
+
+/**
+ * Space usage reporting for the Content Manager: how much of the database each note occupies.
+ *
+ * All byte counting happens in a handful of grouped SQL queries — one pass over the blobs per
+ * request, never a query per note. The tree walks stay on becca, which already holds the whole tree
+ * in memory.
+ *
+ * A cloned note lives in several places but occupies space once, so every note is counted at exactly
+ * one **canonical placement**: the parent through which it is first reached by a breadth-first walk
+ * from the root that enters the hidden subtree last. Reachable outside the hidden subtree means the
+ * note is part of the user's visible tree; everything else — launchers, options, orphans — is
+ * aggregated into a "hidden" bucket rather than listed note by note.
+ *
+ * Sizes are `LENGTH(blobs.content)` like the existing per-note stats endpoints, so the numbers match
+ * what the note info widget already shows. Blobs shared between entities through deduplication are
+ * counted at each entity, so per-note numbers stay meaningful; the deleted-notes aggregate is the
+ * exception — it only counts blobs no live entity still uses, i.e. what erasing would reclaim.
+ */
+
+export const DEFAULT_OVERVIEW_LIMIT = 250;
+export const MAX_OVERVIEW_LIMIT = 1000;
+
+const ROOT_NOTE_ID = "root";
+const HIDDEN_ROOT_ID = "_hidden";
+
+export function getOverview({ includeRevisions, limit }: { includeRevisions: boolean, limit: number }): SpaceUsageOverviewResponse {
+ const sizes = collectSizes();
+ const forest = buildForestFromBecca();
+ const rankOf = (entry: SpaceUsageSizes) =>
+ entry.ownSize + entry.attachmentsSize + (includeRevisions ? entry.revisionsSize : 0);
+
+ const ranked = forest.userNoteIds
+ .map((noteId) => ({ noteId, ...sizesOf(noteId, sizes) }))
+ .sort((a, b) => rankOf(b) - rankOf(a) || a.noteId.localeCompare(b.noteId));
+
+ // Zero-sized notes are never worth an individual tile, even when the tree is smaller than the
+ // ranking cutoff — they go to the bucket, where they still count.
+ const top: typeof ranked = [];
+ const others: typeof ranked = [];
+ for (const [ index, entry ] of ranked.entries()) {
+ (index < limit && rankOf(entry) > 0 ? top : others).push(entry);
+ }
+
+ return {
+ notes: top.map(({ noteId, ...entrySizes }) => ({
+ noteId,
+ notePath: buildNotePath(forest.parentByNoteId, noteId),
+ ...entrySizes
+ })),
+ otherNotes: bucketOf(others),
+ hiddenNotes: bucketOf(forest.hiddenNoteIds.map((noteId) => sizesOf(noteId, sizes))),
+ deletedNotes: collectDeletedNotes(),
+ total: bucketOf(ranked)
+ };
+}
+
+export function getNoteUsage(noteId: string): SpaceUsageNoteResponse {
+ const note = becca.getNoteOrThrow(noteId);
+ const sizes = collectSizes();
+ const forest = buildForestFromBecca();
+ const totals = computeSubtreeTotals(forest, (id) => sizesOf(id, sizes));
+
+ const children = (forest.childrenByNoteId.get(noteId) ?? []).map((childId) => {
+ const total = totals.get(childId);
+
+ return {
+ noteId: childId,
+ subtreeSize: total?.size ?? 0,
+ subtreeRevisionsSize: total?.revisionsSize ?? 0,
+ subtreeNoteCount: total?.noteCount ?? 0
+ };
+ });
+
+ const attachmentSizes = getSql().getMap<string, number>(
+ `
+ SELECT attachments.attachmentId, COALESCE(LENGTH(blobs.content), 0)
+ FROM attachments
+ JOIN blobs ON blobs.blobId = attachments.blobId
+ WHERE attachments.ownerId = ? AND attachments.isDeleted = 0`,
+ [ noteId ]
+ );
+ const attachments = note.getAttachments().flatMap((attachment) => {
+ if (!attachment.attachmentId) {
+ return [];
+ }
+
+ return [ {
+ attachmentId: attachment.attachmentId,
+ title: attachment.getTitleOrProtected(),
+ role: attachment.role,
+ size: attachmentSizes[attachment.attachmentId] ?? 0
+ } ];
+ });
+
+ return {
+ noteId,
+ ...sizesOf(noteId, sizes),
+ attachments,
+ children,
+ // Deleted notes have no place in the tree, so they surface once, at its root.
+ ...(noteId === ROOT_NOTE_ID ? { deletedNotes: collectDeletedNotes() } : {})
+ };
+}
+
+/**
+ * Every live note's single place in the tree. The three collections cover exactly the live notes:
+ * a note is either in the user walk or in the hidden walk, and has a parent unless it is the root
+ * or unreachable.
+ */
+export interface CanonicalForest {
+ /** Canonical parent per note; the root and unreachable notes are absent. */
+ parentByNoteId: Map<string, string>;
+ /** Canonical children in tree order; a cloned note appears under its canonical parent only. */
+ childrenByNoteId: Map<string, string[]>;
+ /** Notes reachable outside the hidden subtree, in breadth-first order starting at the root. */
+ userNoteIds: string[];
+ /** Notes reachable only through the hidden subtree, then any note not reachable at all. */
+ hiddenNoteIds: string[];
+}
+
+/**
+ * Assigns every note its canonical placement: two breadth-first walks, the visible tree first and
+ * the hidden subtree second, each note adopted by the parent that reaches it first. A note cloned
+ * into both worlds therefore counts as a user note, which is what keeps bookmarks — clones under
+ * the hidden bookmarks folder — in the visible listing.
+ *
+ * @param getChildNoteIds child note IDs in tree order; queried for every visited note.
+ * @param allNoteIds every live note, so the walks can sweep up the unreachable leftovers.
+ */
+export function buildCanonicalForest(
+ getChildNoteIds: (noteId: string) => string[],
+ allNoteIds: Iterable<string>,
+ rootNoteId = ROOT_NOTE_ID,
+ hiddenRootId = HIDDEN_ROOT_ID
+): CanonicalForest {
+ const parentByNoteId = new Map<string, string>();
+ const childrenByNoteId = new Map<string, string[]>();
+ // Pre-marking the hidden root keeps the first walk out of the hidden subtree.
+ const visited = new Set<string>([ rootNoteId, hiddenRootId ]);
+
+ /** Walks breadth-first from the queued notes, recording each adoption. The queue is its own
+ * cursor-scanned array — `shift()` would make the walk quadratic. */
+ const walk = (queue: string[]) => {
+ for (let i = 0; i < queue.length; i++) {
+ const noteId = queue[i];
+
+ for (const childId of getChildNoteIds(noteId)) {
+ if (visited.has(childId)) {
+ continue;
+ }
+
+ visited.add(childId);
+ parentByNoteId.set(childId, noteId);
+ childrenByNoteId.set(noteId, [ ...(childrenByNoteId.get(noteId) ?? []), childId ]);
+ queue.push(childId);
+ }
+ }
+
+ return queue;
+ };
+
+ const allIds = new Set(allNoteIds);
+ const userNoteIds = walk([ rootNoteId ]);
+ const hiddenNoteIds: string[] = [];
+
+ if (allIds.has(hiddenRootId)) {
+ parentByNoteId.set(hiddenRootId, rootNoteId);
+ // Appended after the user children, so the hidden subtree lists last under the root.
+ childrenByNoteId.set(rootNoteId, [ ...(childrenByNoteId.get(rootNoteId) ?? []), hiddenRootId ]);
+ appendAll(hiddenNoteIds, walk([ hiddenRootId ]));
+ }
+
+ // A note reachable from nowhere still occupies space: adopt each such subtree so it is at least
+ // counted in the hidden bucket, even though nothing links to it.
+ for (const noteId of allIds) {
+ if (!visited.has(noteId)) {
+ visited.add(noteId);
+ appendAll(hiddenNoteIds, walk([ noteId ]));
+ }
+ }
+
+ return { parentByNoteId, childrenByNoteId, userNoteIds, hiddenNoteIds };
+}
+
+/** Spreading can overflow the argument limit on a huge walk, so appending stays a loop. */
+function appendAll(target: string[], items: string[]) {
+ for (const item of items) {
+ target.push(item);
+ }
+}
+
+/** The aggregate of a note's whole canonical subtree, the note itself included. */
+export interface SubtreeTotal {
+ /** Bodies plus attachments; revisions kept apart so clients can toggle them. */
+ size: number;
+ revisionsSize: number;
+ noteCount: number;
+}
+
+/**
+ * Sums every canonical subtree in one linear pass: children strictly follow their parent in each
+ * breadth-first order, so walking the orders backwards folds each finished subtree into its parent.
+ * The hidden order goes first because its root folds into the tree root, which the user order still
+ * has to fold children into afterwards — additions commute, only completeness matters. Iterative on
+ * purpose: a pathologically deep tree must not blow the stack.
+ */
+export function computeSubtreeTotals(
+ forest: CanonicalForest,
+ getSizes: (noteId: string) => SpaceUsageSizes
+): Map<string, SubtreeTotal> {
+ const totals = new Map<string, SubtreeTotal>();
+
+ for (const noteId of [ ...forest.userNoteIds, ...forest.hiddenNoteIds ]) {
+ const { ownSize, attachmentsSize, revisionsSize } = getSizes(noteId);
+ totals.set(noteId, { size: ownSize + attachmentsSize, revisionsSize, noteCount: 1 });
+ }
+
+ for (const order of [ forest.hiddenNoteIds, forest.userNoteIds ]) {
+ for (let i = order.length - 1; i >= 0; i--) {
+ const total = totals.get(order[i]);
+ const parentId = forest.parentByNoteId.get(order[i]);
+ const parentTotal = parentId === undefined ? undefined : totals.get(parentId);
+
+ if (!total || !parentTotal) {
+ continue;
+ }
+
+ parentTotal.size += total.size;
+ parentTotal.revisionsSize += total.revisionsSize;
+ parentTotal.noteCount += total.noteCount;
+ }
+ }
+
+ return totals;
+}
+
+/** The note's canonical ancestor chain, root excluded, ending with the note itself. */
+export function buildNotePath(parentByNoteId: Map<string, string>, noteId: string, rootNoteId = ROOT_NOTE_ID): string[] {
+ const path: string[] = [];
+
+ for (let current: string | undefined = noteId; current !== undefined && current !== rootNoteId; current = parentByNoteId.get(current)) {
+ path.push(current);
+ }
+
+ return path.reverse();
+}
+
+interface SizeLookup {
+ own: Record<string, number>;
+ attachments: Record<string, number>;
+ revisions: Record<string, number>;
+}
+
+/** One grouped pass per component over the blobs — the whole request's byte counting. */
+function collectSizes(): SizeLookup {
+ const sql = getSql();
+
+ const own = sql.getMap<string, number>(`
+ SELECT notes.noteId, COALESCE(LENGTH(blobs.content), 0)
+ FROM notes
+ JOIN blobs ON blobs.blobId = notes.blobId
+ WHERE notes.isDeleted = 0`);
+
+ // Owners that are revisions rather than notes simply never match a live noteId here; their
+ // attachments are picked up by the revisions query below.
+ const attachments = sql.getMap<string, number>(`
+ SELECT attachments.ownerId, SUM(COALESCE(LENGTH(blobs.content), 0))
+ FROM attachments
+ JOIN blobs ON blobs.blobId = attachments.blobId
+ WHERE attachments.isDeleted = 0
+ GROUP BY attachments.ownerId`);
+
+ const revisions = sql.getMap<string, number>(`
+ SELECT noteId, SUM(size)
+ FROM (
+ SELECT revisions.noteId AS noteId, COALESCE(LENGTH(blobs.content), 0) AS size
+ FROM revisions
+ JOIN blobs ON blobs.blobId = revisions.blobId
+ UNION ALL
+ SELECT revisions.noteId, COALESCE(LENGTH(blobs.content), 0)
+ FROM attachments
+ JOIN revisions ON revisions.revisionId = attachments.ownerId
+ JOIN blobs ON blobs.blobId = attachments.blobId
+ WHERE attachments.isDeleted = 0
+ )
+ GROUP BY noteId`);
+
+ return { own, attachments, revisions };
+}
+
+function sizesOf(noteId: string, sizes: SizeLookup): SpaceUsageSizes {
+ return {
+ ownSize: sizes.own[noteId] ?? 0,
+ attachmentsSize: sizes.attachments[noteId] ?? 0,
+ revisionsSize: sizes.revisions[noteId] ?? 0
+ };
+}
+
+function bucketOf(entries: SpaceUsageSizes[]): SpaceUsageBucket {
+ const bucket = { size: 0, revisionsSize: 0, noteCount: entries.length };
+
+ for (const entry of entries) {
+ bucket.size += entry.ownSize + entry.attachmentsSize;
+ bucket.revisionsSize += entry.revisionsSize;
+ }
+
+ return bucket;
+}
+
+/**
+ * What erasing would actually reclaim: blobs referenced by deleted entities and by no live one.
+ * Deduplicated by blobId — several deleted clones of the same content free that content once.
+ *
+ * Every `NOT IN` subquery must filter out NULL blob IDs: a single NULL in the set makes `NOT IN`
+ * evaluate to NULL for every row, silently emptying the whole result.
+ */
+function collectDeletedNotes(): SpaceUsageDeletedNotes {
+ const sql = getSql();
+
+ const size = sql.getValue<number | null>(`
+ SELECT SUM(COALESCE(LENGTH(blobs.content), 0))
+ FROM blobs
+ WHERE blobs.blobId IN (
+ SELECT blobId FROM notes WHERE isDeleted = 1
+ UNION SELECT blobId FROM attachments WHERE isDeleted = 1
+ UNION SELECT revisions.blobId FROM revisions
+ JOIN notes ON notes.noteId = revisions.noteId
+ WHERE notes.isDeleted = 1
+ ) AND blobs.blobId NOT IN (
+ SELECT blobId FROM notes WHERE isDeleted = 0 AND blobId IS NOT NULL
+ UNION SELECT blobId FROM attachments WHERE isDeleted = 0 AND blobId IS NOT NULL
+ UNION SELECT revisions.blobId FROM revisions
+ JOIN notes ON notes.noteId = revisions.noteId
+ WHERE notes.isDeleted = 0 AND revisions.blobId IS NOT NULL
+ )`) ?? 0;
+
+ const noteCount = sql.getValue<number>(`
+ SELECT COUNT(*)
+ FROM notes
+ JOIN blobs ON blobs.blobId = notes.blobId
+ WHERE notes.isDeleted = 1`);
+
+ return { size, noteCount };
+}
+
+function buildForestFromBecca(): CanonicalForest {
+ return buildCanonicalForest(
+ (noteId) => {
+ const note = becca.notes[noteId];
+ if (!note) {
+ return [];
+ }
+
+ return note.getChildBranches()
+ .flatMap((branch) => branch ? [ branch ] : [])
+ // Sorted here rather than trusting cache order, so the canonical choice between
+ // equally deep clones is the same on every instance of a sync cluster.
+ .sort((a, b) => a.notePosition - b.notePosition || a.noteId.localeCompare(b.noteId))
+ .map((branch) => branch.noteId);
+ },
+ Object.keys(becca.notes)
+ );
+}