fix(storage): judge unreferenced files without a brake anyone can trip

The 20 % brake skipped a category and wiped its marks every night once a
fifth of it looked unreferenced. Any user could push a small install over
that line, a backlog from #2924 started braked, and a second install on the
same bucket below the line was not caught at all. It is gone:

- Each pass leaves a trek-owner-<install id> marker at the root of every
  category it judges. A category holding another install's marker is
  skipped as foreign_install, one where the marker cannot be written as
  owner_unknown. Backups leave the markers out.
- The install id lives in app_settings outside the storage.* prefix. The
  switch is stored as that id, so a database from another install reads as
  off, and every reopen (a restore) writes this install's id back, turns
  deletion off and drops the marks, confirmations and reports.
- More than a fifth unreferenced still marks and reports, but deletes only
  after an admin confirmed the count shown (POST .../reclaim/confirm). A
  larger count later waits again.

A skip no longer touches the marks, so a failed listing or lookup does not
restart the week. Check now runs in the background and answers 202; the
admin state says running and keeps the last deleting report apart, so a
report-only check never resets what was freed. A pass that deletes writes a
system audit entry, a pass that stops or fails keeps its partial counts and
marks the rest interrupted, a backend error stops deleting in its category,
and deleting stops for the rest of the pass once the switch is off or a
backup is reading the uploads. The usage scan waits for a pass still
running.

Sources read each category once per pass and answer the pre-delete
re-check with a query narrowed to the keys' plain runs. Bare names keep
their raw spelling (a '#', '?' or trailing blank is part of an upload's
name), and local roots are resolved through their symlinks before the
overlap check. A pass lists only a category's root.
This commit is contained in:
Maurice
2026-11-01 16:18:08 +01:00
parent e59992d56d
commit 790fccb92c
48 changed files with 1786 additions and 661 deletions
+55 -11
View File
@@ -6,8 +6,10 @@ import {
storageAdminStateSchema,
storageBackfillStatusSchema,
storageConfigSchema,
STORAGE_RECLAIM_SKIP_REASONS,
storageReclaimConfirmRequestSchema,
storageReclaimReportSchema,
storageReclaimRunRequestSchema,
storageReclaimRunStartedSchema,
storageReclaimSettingsRequestSchema,
storageReclaimStateSchema,
storageSecretFields,
@@ -191,7 +193,14 @@ describe('backfill + usage wire shapes', () => {
describe('the reclaim contract', () => {
const counts = { objects: 0, bytes: 0 };
const perCategory = { objects: 3, unreferenced: counts, eligible: counts, deleted: counts, skipped: null };
const perCategory = {
objects: 3,
unreferenced: counts,
eligible: counts,
deleted: counts,
confirmationRequired: false,
skipped: null,
};
const report = {
startedAt: 1_700_000_000_000,
finishedAt: 1_700_000_001_000,
@@ -205,25 +214,60 @@ describe('the reclaim contract', () => {
expect(storageReclaimReportSchema.parse(report)).toEqual(report);
});
it('a report missing a category, or naming an unknown skip reason, is refused', () => {
it('a report missing a category, a confirmation flag, or naming an unknown skip reason, is refused', () => {
const { photos: _photos, ...withoutPhotos } = report.categories;
expect(storageReclaimReportSchema.safeParse({ ...report, categories: withoutPhotos }).success).toBe(false);
const odd = { ...report, categories: { ...report.categories, covers: { ...perCategory, skipped: 'tired' } } };
expect(storageReclaimReportSchema.safeParse(odd).success).toBe(false);
const { confirmationRequired: _flag, ...unflagged } = perCategory;
const old = { ...report, categories: { ...report.categories, covers: unflagged } };
expect(storageReclaimReportSchema.safeParse(old).success).toBe(false);
});
it('the admin state carries the switch and a nullable last run', () => {
it('names every skip reason a pass reports, the brake that used to skip a category gone', () => {
expect([...STORAGE_RECLAIM_SKIP_REASONS]).toEqual([
'not_reclaimed',
'sources_missing',
'shared_location',
'foreign_install',
'owner_unknown',
'list_failed',
'source_failed',
'delete_failed',
'interrupted',
]);
for (const skipped of STORAGE_RECLAIM_SKIP_REASONS) {
const row = { ...report, categories: { ...report.categories, covers: { ...perCategory, skipped } } };
expect(storageReclaimReportSchema.safeParse(row).success).toBe(true);
}
expect(storageReclaimReportSchema.safeParse({ ...report, stopped: 'failed' }).success).toBe(true);
expect(storageReclaimReportSchema.safeParse({ ...report, stopped: 'tired' }).success).toBe(false);
});
it('the admin state carries the switch, the running flag and both nullable reports', () => {
const shape = storageAdminStateSchema.pick({ reclaim: true });
expect(shape.parse({ reclaim: { deleteEnabled: false, lastRun: null } })).toEqual({
reclaim: { deleteEnabled: false, lastRun: null },
});
expect(storageReclaimStateSchema.safeParse({ deleteEnabled: 'yes', lastRun: null }).success).toBe(false);
const idle = { deleteEnabled: false, running: false, lastRun: null, lastDeleteRun: null };
expect(shape.parse({ reclaim: idle })).toEqual({ reclaim: idle });
expect(shape.parse({ reclaim: null })).toEqual({ reclaim: null });
expect(storageReclaimStateSchema.parse({ ...idle, running: true, lastRun: report, lastDeleteRun: report })).toEqual(
{
...idle,
running: true,
lastRun: report,
lastDeleteRun: report,
},
);
expect(storageReclaimStateSchema.safeParse({ ...idle, deleteEnabled: 'yes' }).success).toBe(false);
expect(storageReclaimStateSchema.safeParse({ deleteEnabled: false, lastRun: null }).success).toBe(false);
});
it('the requests are closed objects', () => {
it('the requests are closed objects, and a started check answers started: true', () => {
expect(storageReclaimSettingsRequestSchema.parse({ deleteEnabled: true })).toEqual({ deleteEnabled: true });
expect(storageReclaimSettingsRequestSchema.safeParse({ deleteEnabled: true, extra: 1 }).success).toBe(false);
expect(storageReclaimRunRequestSchema.parse({})).toEqual({});
expect(storageReclaimRunRequestSchema.safeParse({ reportOnly: 'no' }).success).toBe(false);
expect(storageReclaimConfirmRequestSchema.parse({ category: 'covers' })).toEqual({ category: 'covers' });
expect(storageReclaimConfirmRequestSchema.safeParse({ category: 'nowhere' }).success).toBe(false);
expect(storageReclaimConfirmRequestSchema.safeParse({ category: 'covers', count: 3 }).success).toBe(false);
expect(storageReclaimRunStartedSchema.parse({ started: true })).toEqual({ started: true });
expect(storageReclaimRunStartedSchema.safeParse({ started: false }).success).toBe(false);
});
});
+37 -11
View File
@@ -283,20 +283,27 @@ export const STORAGE_RECLAIM_CATEGORIES = [...STORAGE_CATEGORIES, 'photos'] as c
export const storageReclaimCategorySchema = z.enum(STORAGE_RECLAIM_CATEGORIES);
/**
* Why a category deleted nothing on a pass, whatever the switch says:
* Why a category was not judged on a pass, or stopped short, whatever the switch says:
* - `not_reclaimed`: the category is never reclaimed (a cache, the backups, the legacy photos folder);
* - `sources_missing`: a domain whose rows can name its objects did not answer, so nothing can be proven unreferenced;
* - `shared_location`: its objects sit where another category's do, or where they cannot be told apart;
* - `too_many_unreferenced`: more than a fifth of its objects look unreferenced, which points at a shared bucket;
* - `list_failed` / `source_failed`: the listing or a reference lookup failed, so the pass stopped there.
* - `foreign_install`: another TREK installation keeps its uploads in the same place (its owner marker is there);
* - `owner_unknown`: this installation's owner marker could not be written there, so a shared place cannot be ruled out;
* - `list_failed` / `source_failed`: the listing or a reference lookup failed, so the pass stopped there;
* - `delete_failed`: deleting failed on the backend, so the pass stopped deleting in this category;
* - `interrupted`: the pass stopped (`stopped` says why) before it finished this category; its figures are partial.
* A skip keeps the marks it found: only a pass that judges the category moves them.
*/
export const STORAGE_RECLAIM_SKIP_REASONS = [
'not_reclaimed',
'sources_missing',
'shared_location',
'too_many_unreferenced',
'foreign_install',
'owner_unknown',
'list_failed',
'source_failed',
'delete_failed',
'interrupted',
] as const;
const storageObjectCountSchema = z.object({ objects: z.number().int().nonnegative(), bytes: z.number().nonnegative() });
@@ -309,6 +316,11 @@ export const storageReclaimCategoryReportSchema = z.object({
/** Unreferenced on every pass for at least a week: what a pass with deletion on removes. */
eligible: storageObjectCountSchema,
deleted: storageObjectCountSchema,
/**
* More than a fifth of the category is unreferenced, and more than an admin
* last confirmed: deletion waits for a confirmation (POST .../reclaim/confirm).
*/
confirmationRequired: z.boolean(),
skipped: z.enum(STORAGE_RECLAIM_SKIP_REASONS).nullable(),
});
export type StorageReclaimCategoryReport = z.infer<typeof storageReclaimCategoryReportSchema>;
@@ -316,27 +328,41 @@ export type StorageReclaimCategoryReport = z.infer<typeof storageReclaimCategory
export const storageReclaimReportSchema = z.object({
startedAt: z.number(),
finishedAt: z.number(),
/** `delete` only when the admin switched deletion on and the pass was not asked to only report. */
/** `delete` when the pass started with deletion switched on; a check started by hand always only reports. */
mode: z.enum(['report', 'delete']),
/** Why the pass stopped before the end: the database was swapped under it (a restore). Null when it ran through. */
stopped: z.enum(['database_reopened']).nullable(),
/**
* Why the pass stopped before the end: the database was swapped under it (a
* restore), or an unexpected error. Null when it ran through.
*/
stopped: z.enum(['database_reopened', 'failed']).nullable(),
categories: z.record(storageReclaimCategorySchema, storageReclaimCategoryReportSchema),
});
export type StorageReclaimReport = z.infer<typeof storageReclaimReportSchema>;
export const storageReclaimStateSchema = z.object({
/** Off after install and upgrade: a pass then only reports. */
/** Off after install, upgrade and every backup restore: a pass then only reports. */
deleteEnabled: z.boolean(),
/** A pass is running now (the nightly one or a check started by hand). */
running: z.boolean(),
/** The last pass of any kind; null before the first. */
lastRun: storageReclaimReportSchema.nullable(),
/** The last pass that ran with deletion on, which a check started by hand never replaces; null before one. */
lastDeleteRun: storageReclaimReportSchema.nullable(),
});
export type StorageReclaimState = z.infer<typeof storageReclaimStateSchema>;
export const storageReclaimSettingsRequestSchema = z.strictObject({ deleteEnabled: z.boolean() });
export type StorageReclaimSettingsRequest = z.infer<typeof storageReclaimSettingsRequestSchema>;
/** `reportOnly` runs a pass that deletes nothing even with deletion switched on. */
export const storageReclaimRunRequestSchema = z.strictObject({ reportOnly: z.boolean().optional() });
export type StorageReclaimRunRequest = z.infer<typeof storageReclaimRunRequestSchema>;
/** POST .../reclaim/run answers 202 at once; the pass reports through the admin state. */
export const storageReclaimRunStartedSchema = z.object({ started: z.literal(true) });
/**
* Lets the pass delete in a category whose unreferenced share is over a
* fifth, up to the count the last report showed for it.
*/
export const storageReclaimConfirmRequestSchema = z.strictObject({ category: storageReclaimCategorySchema });
export type StorageReclaimConfirmRequest = z.infer<typeof storageReclaimConfirmRequestSchema>;
export const storageAdminStateSchema = z.object({
backends: z.array(