Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core/content manager: make the size calculations more consistent
Adorian Doran8a06fa5bec01
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 90c3ddb5c1..674bcf01a0 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2676,10 +2676,14 @@"attachment_tooltip": "Attachment: {{- title}} ({{size}})","child_tooltip": "Child note: {{- title}} ({{size}})","center_note_size": "Note: {{size}}",+ "center_note_size_hint": "Space this note actually occupies: body, attachments and revisions, with duplicated content counted once","center_subtree_size": "Subtree: {{size}}",+ "center_subtree_size_hint": "Space this note and all of its descendants actually occupy, revisions included, with duplicated content counted once","back": "Back",- "status_total": "Total: {{size}}",- "status_deleted": "Deleted notes: {{size}}"+ "status_content": "Database content: {{size}}",+ "status_content_hint": "Space the content actually occupies: all notes (hidden ones included), attachments and revisions, with duplicated content counted once",+ "status_deleted": "Deleted notes: {{size}}",+ "status_deleted_hint": "Space still held by deleted notes; erasing them reclaims it"},"note_language": {"not_set": "No language set",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.tsindex 4ac0a1d741..3e2bb464dd 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts@@ -10,6 +10,8 @@ function usage(overrides: Partial<SpaceUsageNoteResponse> = {}): SpaceUsageNoteRownSize: 0,attachmentsSize: 0,revisionsSize: 0,+ noteContentSize: 0,+ subtreeContentSize: 0,attachments: [],children: [],...overridesdiff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsxindex 95f0bba55c..4d30c66188 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx@@ -35,8 +35,12 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro{overview && (<footer className="space-usage-status">- <span>{t("space_usage.status_total", { size: formatSize(overview.total.size) })}</span>- <span>{t("space_usage.status_deleted", { size: formatSize(overview.deletedNotes.size) })}</span>+ <span title={t("space_usage.status_content_hint")}>+ {t("space_usage.status_content", { size: formatSize(overview.contentSize) })}+ </span>+ <span title={t("space_usage.status_deleted_hint")}>+ {t("space_usage.status_deleted", { size: formatSize(overview.deletedNotes.size) })}+ </span></footer>)}</div>diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsxindex f02fb0c924..9d9d4315c1 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsx@@ -44,9 +44,6 @@ export default function NoteUsageDonut({ usage, title, notePath, outerRings = []})}), [ usage ]);- const noteSize = usage.ownSize + usage.attachmentsSize + usage.revisionsSize;- const subtreeSize = noteSize + usage.children.reduce(- (sum, child) => sum + child.subtreeSize + child.subtreeRevisionsSize, 0);return (<DonutChart<UsageSegmentData>@@ -67,8 +64,12 @@ export default function NoteUsageDonut({ usage, title, notePath, outerRings = []});}}>{title}</a>- <span className="note-usage-donut-size">{t("space_usage.center_note_size", { size: formatSize(noteSize) })}</span>- <span className="note-usage-donut-size">{t("space_usage.center_subtree_size", { size: formatSize(subtreeSize) })}</span>+ <span className="note-usage-donut-size" title={t("space_usage.center_note_size_hint")}>+ {t("space_usage.center_note_size", { size: formatSize(usage.noteContentSize) })}+ </span>+ <span className="note-usage-donut-size" title={t("space_usage.center_subtree_size_hint")}>+ {t("space_usage.center_subtree_size", { size: formatSize(usage.subtreeContentSize) })}+ </span></DonutChart>);}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.tsindex 76824441b6..34eaf0b4a2 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts@@ -10,6 +10,7 @@ function entry(noteId: string, notePath: string[], sizes: Partial<SpaceUsageOverfunction response(notes: SpaceUsageOverviewNote[], overrides: Partial<SpaceUsageOverviewResponse> = {}): SpaceUsageOverviewResponse {return {+ contentSize: 0,notes,otherNotes: { size: 0, revisionsSize: 0, noteCount: 0 },hiddenNotes: { size: 0, revisionsSize: 0, noteCount: 0 },diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 52f31783c7..87f4ac7b67 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -270,6 +270,13 @@ export interface SpaceUsageDeletedNotes {}export interface SpaceUsageOverviewResponse {+ /**+ * What the live content actually occupies: every blob referenced by a live note, attachment or+ * revision — hidden subtree included — counted once however many entities share it through+ * deduplication. This is the "database size" figure; the per-note numbers below intentionally+ * count per entity instead, so a note's reported size never depends on duplicates elsewhere.+ */+ contentSize: number;/** The largest notes first, ranked by body + attachments (+ revisions when requested). */notes: SpaceUsageOverviewNote[];/** The remaining notes of the visible tree, below the ranking cutoff. */@@ -298,6 +305,14 @@ export interface SpaceUsageAttachment {export interface SpaceUsageNoteResponse extends SpaceUsageSizes {noteId: string;+ /**+ * What the note alone actually occupies — body, attachments and revisions, each shared blob+ * counted once. Smaller than the per-entity components sum whenever revisions still share the+ * note's blob or attachments repeat content.+ */+ noteContentSize: number;+ /** Like {@link noteContentSize}, over the note's whole canonical subtree. */+ subtreeContentSize: number;attachments: SpaceUsageAttachment[];/** Canonical children only: a cloned child is listed under its canonical parent alone. */children: SpaceUsageChild[];diff --git a/packages/trilium-core/src/routes/api/space_usage.spec.ts b/packages/trilium-core/src/routes/api/space_usage.spec.tsindex 1d06d2e8a6..4d7eee4df2 100644--- a/packages/trilium-core/src/routes/api/space_usage.spec.ts+++ b/packages/trilium-core/src/routes/api/space_usage.spec.ts@@ -88,6 +88,20 @@ describe("Space usage API (core)", () => {expect(limited.otherNotes.noteCount).toBe(limited.total.noteCount - 1);});+ it("counts deduplicated content once in contentSize, but per entity in the note sizes", async () => {+ const duplicated = `<p>${"space-usage-dedup-".repeat(300)}</p>`;+ const before = await getOverview({ limit: 1 });++ await createTextNote(api, { title: "Space usage dedup 1", content: duplicated });+ await createTextNote(api, { title: "Space usage dedup 2", content: duplicated });++ const after = await getOverview({ limit: 1 });+ // Two notes, one shared blob: the visible-tree total grows twice, the deduplicated+ // database-content figure only once.+ expect(after.total.size - before.total.size).toBe(2 * duplicated.length);+ expect(after.contentSize - before.contentSize).toBe(duplicated.length);+ });+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 });@@ -120,6 +134,27 @@ describe("Space usage API (core)", () => {expect(childEntry?.subtreeNoteCount).toBe(1);});+ it("reports deduplicated note and subtree content sizes", async () => {+ const childUsage = await getNoteUsage(child.noteId);+ // The revision snapshots the unchanged body and attachment, sharing their blobs — so it+ // adds nothing to the deduplicated figures, unlike the per-entity revisionsSize.+ expect(childUsage.noteContentSize).toBe(CHILD_CONTENT.length + ATTACHMENT_CONTENT.length);+ expect(childUsage.subtreeContentSize).toBe(childUsage.noteContentSize);+ expect(childUsage.revisionsSize).toBeGreaterThan(0);++ const parentUsage = await getNoteUsage(parent.noteId);+ expect(parentUsage.noteContentSize).toBe(PARENT_CONTENT.length);+ expect(parentUsage.subtreeContentSize)+ .toBe(PARENT_CONTENT.length + CHILD_CONTENT.length + ATTACHMENT_CONTENT.length);++ // The root's canonical subtree is the whole live tree, so its figure can only stay within+ // the database-content total (which additionally sweeps up unreachable leftovers).+ const overview = await getOverview({ limit: 1 });+ const rootUsage = await getNoteUsage("root");+ expect(rootUsage.subtreeContentSize).toBeGreaterThan(0);+ expect(rootUsage.subtreeContentSize).toBeLessThanOrEqual(overview.contentSize);+ });+it("counts a cloned note only under its canonical parent", async () => {const usage = await getNoteUsage(cloneTarget.noteId);diff --git a/packages/trilium-core/src/services/space_usage.spec.ts b/packages/trilium-core/src/services/space_usage.spec.tsindex 05a0fc4a26..799a7c6b5c 100644--- a/packages/trilium-core/src/services/space_usage.spec.ts+++ b/packages/trilium-core/src/services/space_usage.spec.ts@@ -1,7 +1,7 @@import { SpaceUsageSizes } from "@triliumnext/commons";import { describe, expect, it } from "vitest";-import { buildCanonicalForest, buildNotePath, computeSubtreeTotals } from "./space_usage.js";+import { buildCanonicalForest, buildNotePath, collectSubtreeNoteIds, 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[] = []) {@@ -126,6 +126,16 @@ describe("computeSubtreeTotals", () => {});});+describe("collectSubtreeNoteIds", () => {+ it("collects the canonical subtree only — a cloned-in child counts elsewhere", () => {+ const forest = forestOf({ root: [ "a", "b" ], a: [ "x" ], b: [ "x" ] });++ expect(collectSubtreeNoteIds(forest, "a")).toEqual([ "a", "x" ]);+ expect(collectSubtreeNoteIds(forest, "b")).toEqual([ "b" ]);+ expect([ ...collectSubtreeNoteIds(forest, "root") ].sort()).toEqual([ "a", "b", "root", "x" ]);+ });+});+describe("buildNotePath", () => {it("walks canonical parents from a top-level note down, omitting the root", () => {const forest = forestOf({ root: [ "a" ], a: [ "b" ], b: [ "c" ] });diff --git a/packages/trilium-core/src/services/space_usage.ts b/packages/trilium-core/src/services/space_usage.tsindex b56166ac6b..38befb426c 100644--- a/packages/trilium-core/src/services/space_usage.ts+++ b/packages/trilium-core/src/services/space_usage.ts@@ -53,6 +53,7 @@ export function getOverview({ includeRevisions, limit }: { includeRevisions: boo}return {+ contentSize: collectContentSize(),notes: top.map(({ noteId, ...entrySizes }) => ({noteId,notePath: buildNotePath(forest.parentByNoteId, noteId),@@ -106,6 +107,8 @@ export function getNoteUsage(noteId: string): SpaceUsageNoteResponse {return {noteId,...sizesOf(noteId, sizes),+ noteContentSize: collectContentSizeOf([ noteId ]),+ subtreeContentSize: collectContentSizeOf(collectSubtreeNoteIds(forest, noteId)),attachments,children,// Deleted notes have no place in the tree, so they surface once, at its root.@@ -245,6 +248,20 @@ export function computeSubtreeTotals(return totals;}+/** The note's whole canonical subtree, itself included — the canonical forest is a tree, so no+ * note is visited twice. The queue is its own cursor-scanned array, keeping deep trees safe. */+export function collectSubtreeNoteIds(forest: CanonicalForest, noteId: string): string[] {+ const queue = [ noteId ];++ for (let i = 0; i < queue.length; i++) {+ for (const childId of forest.childrenByNoteId.get(queue[i]) ?? []) {+ queue.push(childId);+ }+ }++ return queue;+}+/** 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[] = [];@@ -318,6 +335,54 @@ function bucketOf(entries: SpaceUsageSizes[]): SpaceUsageBucket {return bucket;}+/**+ * What the live content actually occupies on disk: every blob referenced by a live note, a live+ * attachment or a revision of a live note — the hidden subtree included — counted once however+ * many entities share it through deduplication. The per-entity numbers elsewhere deliberately+ * count differently, so this is the one figure comparable to the database's real size.+ */+function collectContentSize(): number {+ return getSql().getValue<number | null>(`+ SELECT SUM(COALESCE(LENGTH(blobs.content), 0))+ FROM blobs+ WHERE blobs.blobId 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;+}++/**+ * Like {@link collectContentSize}, but restricted to the given notes: every blob referenced by+ * their bodies, their attachments, their revisions or those revisions' attachments, counted once.+ * This is what makes a note's — or a subtree's — figure comparable to the database-content one.+ */+function collectContentSizeOf(noteIds: string[]): number {+ const sql = getSql();+ sql.fillParamList(noteIds);++ return sql.getValue<number | null>(`+ SELECT SUM(COALESCE(LENGTH(blobs.content), 0))+ FROM blobs+ WHERE blobs.blobId IN (+ SELECT notes.blobId FROM notes+ JOIN param_list ON param_list.paramId = notes.noteId+ WHERE notes.isDeleted = 0 AND notes.blobId IS NOT NULL+ UNION SELECT attachments.blobId FROM attachments+ JOIN param_list ON param_list.paramId = attachments.ownerId+ WHERE attachments.isDeleted = 0 AND attachments.blobId IS NOT NULL+ UNION SELECT revisions.blobId FROM revisions+ JOIN param_list ON param_list.paramId = revisions.noteId+ WHERE revisions.blobId IS NOT NULL+ UNION SELECT attachments.blobId FROM attachments+ JOIN revisions ON revisions.revisionId = attachments.ownerId+ JOIN param_list ON param_list.paramId = revisions.noteId+ WHERE attachments.isDeleted = 0 AND attachments.blobId IS NOT NULL+ )`) ?? 0;+}+/*** 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.