Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep Apple Health imports and archival from overwriting a live restore (#10899)

Adam Eivy9d56c26a5dc7
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 5931213d92..cb33431d91 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -616,8 +616,9 @@ Dry runs and unrelated selective restores do not acquire this settings boundary.
A full live restore acquires boundaries in this order: shared snapshot cut
(asset publications drained), task schedule, settings, CoS configuration, CoS
-runtime state, media model registry. A selective restore acquires the same order
-minus the boundaries its scope does not touch; the snapshot cut is always held.
+runtime state, media model registry, Apple Health day-file admission. A
+selective restore acquires the same order minus the boundaries its scope does
+not touch; the snapshot cut is always held.
Each boundary stays held until everything inside it — transfer and cache
reconciliation, including after a partial transfer failure — has settled, so the
settings queue remains held through CoS reconciliation. The order is declared once
@@ -664,6 +665,27 @@ errors still report that files may have been overwritten; a cache-reload failure
requires restarting PortOS before using CoS. Dry runs and selective restores
outside the CoS state/config scope do not acquire this boundary.
+### Restoring Apple Health day files in a running server
+
+Full live file restores, `health` restores, and single-day `health/...` restores
+own Apple Health mutation admission (`withLiveHealthRestore` in
+`server/services/appleHealthIngest.js`). JSON ingest, XML import batch flushes,
+and health archive capture and removal each take admission before their day's
+write queue and hold it until that day's read-modify-write (or capture/removal)
+settles, so no cycle can carry a pre-restore read across the transfer.
+
+From the moment the restore is requested, new day cycles wait. Cycles already
+admitted finish first; then rsync runs; then health caches are invalidated and
+admission reopens — on success, partial transfer failure, or reconciliation
+failure alike. Waiting imports then read the restored day files, so points the
+snapshot recovered are preserved. An XML import takes admission per day, so a
+restore can land between two of its days. Archival releases admission while
+`tar` encodes; its hash-conditional removal retains any day whose bytes the
+restore changed. Outside a restore, different days still import concurrently.
+Health admission is acquired last, so a restore refused earlier (for example by
+`COS_RESTORE_BUSY`) never pauses imports. Dry runs and unrelated selective
+restores do not acquire it.
+
## Database maintenance admission
While the server is still running, `GET /api/database/maintenance/status` reads the journal without querying PostgreSQL or launching shell probes. It uses the ordinary instance authentication gate (authentication remains optional) and returns `{ stage: "idle", fenced: false }` when no operation exists, or the operation's `id`, `stage`, source/target mode names, and `fenced: true`. Connection identities and coordinator credentials are never returned. Responses are not cacheable; damaged or unreadable state returns HTTP 503 with `DATABASE_MAINTENANCE`, never idle. A `verified` stage alone still reports fenced: it does not authorize writers or prove admission has reopened. Once the server has stopped or its boot fence refuses startup, use the local status command below; this endpoint does not bypass the boot fence.
diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.js
index 03e8de234d..1edc194172 100644
--- a/server/services/appleHealthIngest.js
+++ b/server/services/appleHealthIngest.js
@@ -15,10 +15,76 @@ import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';
/**
* Per-date write queue to serialize read-modify-write cycles.
* Keyed by date string (YYYY-MM-DD) so different days fan out in parallel
- * while writes to the same day serialize. Shared with XML import and archival
- * capture/removal so every day-file mutation sees the latest committed bytes.
+ * while writes to the same day serialize. Reached only through
+ * `queueHealthDayMutation`, so every day-file mutation is also admitted.
*/
-export const queueDayWrite = createKeyedFileWriteQueue();
+const queueDayWrite = createKeyedFileWriteQueue();
+
+/**
+ * Health mutation admission (#10899). A live file restore that reaches
+ * `data/health` closes admission, waits for every admitted day cycle to settle,
+ * transfers, and reopens. Admission is taken BEFORE a day's queue and held until
+ * its write settles, so a cycle never carries a pre-image across a restore.
+ * Ordinary cycles only count themselves: distinct days stay concurrent.
+ */
+const admission = { active: 0, restores: 0, reopen: null, drained: null };
+let restoreTail = Promise.resolve();
+
+/**
+ * Run one read-modify-write (or capture/removal) cycle for `dateStr` inside
+ * health mutation admission and that day's queue. JSON ingest, XML flushes and
+ * health archival all mutate day files through this — never around it.
+ *
+ * @param {string} dateStr - YYYY-MM-DD string
+ * @param {() => Promise<*>} mutate - Reads, then writes or removes, the day file
+ * @returns {Promise<*>} The cycle's result
+ */
+export async function queueHealthDayMutation(dateStr, mutate) {
+ // The open path admits and enqueues synchronously, before the first await.
+ while (admission.restores > 0) await admission.reopen.promise;
+ admission.active += 1;
+ try {
+ return await queueDayWrite(dateStr, mutate);
+ } finally {
+ admission.active -= 1;
+ if (admission.active === 0) admission.drained?.resolve();
+ }
+}
+
+/**
+ * Own Apple Health day files through an out-of-band live restore. Closes new
+ * mutation admission synchronously at the call, drains admitted day cycles,
+ * runs `transfer`, invalidates health caches and reopens admission on every
+ * outcome. Competing restores serialize and keep admission closed between them.
+ * Acquire after the backup snapshot cut; never call `queueHealthDayMutation`
+ * from `transfer` (it would wait on itself).
+ *
+ * @param {() => Promise<*>} transfer
+ * @returns {Promise<*>} The transfer's result
+ */
+export function withLiveHealthRestore(transfer) {
+ if (admission.restores++ === 0) admission.reopen = Promise.withResolvers();
+ const run = restoreTail.then(async () => {
+ try {
+ if (admission.active > 0) {
+ admission.drained = Promise.withResolvers();
+ await admission.drained.promise;
+ }
+ const [result] = await Promise.allSettled([Promise.resolve().then(transfer)]);
+ // A restored day can change any metric, including the body metrics the
+ // writers invalidate, and a failed rsync may already have replaced some
+ // days — so invalidate after every outcome.
+ invalidateMeatspace(['healthBody']);
+ if (result.status === 'rejected') throw result.reason;
+ return result.value;
+ } finally {
+ admission.drained = null;
+ if (--admission.restores === 0) admission.reopen.resolve();
+ }
+ });
+ restoreTail = run.catch(() => {});
+ return run;
+}
// === Pure Functions ===
@@ -131,7 +197,7 @@ export function upsertPoints(existing, newPoints) {
* @returns {Promise<Object>} { added, updated, totalPoints }
*/
export async function mergeIntoDay(dateStr, metricName, newPoints) {
- return queueDayWrite(dateStr, async () => {
+ return queueHealthDayMutation(dateStr, async () => {
const dayData = await readDayFile(dateStr);
const existing = dayData.metrics[metricName] || [];
diff --git a/server/services/appleHealthIngest.restore.test.js b/server/services/appleHealthIngest.restore.test.js
new file mode 100644
index 0000000000..ed1baf80cb
--- /dev/null
+++ b/server/services/appleHealthIngest.restore.test.js
@@ -0,0 +1,187 @@
+/**
+ * Apple Health live-restore admission (#10899) against XML flushes and health
+ * archival. Real synthetic day files in a temp data root; each restore's
+ * transfer replaces destination bytes exactly as rsync does at its process
+ * boundary. The JSON ingest crossing is covered end to end through
+ * restoreSnapshot in backup.test.js.
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, readdir, rm, writeFile } from 'fs/promises';
+import { join, resolve } from 'path';
+import { execFileSync } from '../lib/childProcess.js';
+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const controls = vi.hoisted(() => ({ readFile: null, rm: null, tar: null }));
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: () => root });
+});
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readFile: (...args) => controls.readFile ? controls.readFile(...args) : actual.readFile(...args),
+ rm: (...args) => controls.rm ? controls.rm(...args) : actual.rm(...args),
+ };
+});
+vi.mock('../lib/childProcess.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, execFile: (command, args, options, callback) => (controls.tar
+ ? controls.tar(command, args, options, callback)
+ : actual.execFile(command, args, options, callback)) };
+});
+
+const root = createTempDataRoot('portos-health-restore-');
+const { archiveCategory } = await import('./dataManager.js');
+const { mergeIntoDay, withLiveHealthRestore } = await import('./appleHealthIngest.js');
+const { importAppleHealthXml } = await import('./appleHealthXml.js');
+
+const health = join(root, 'health');
+const day = '2024-01-01';
+const liveDay = () => join(health, `${day}.json`);
+const point = (hour, qty) => ({ date: `${day} ${hour}:00:00 +0000`, qty });
+const original = point('08', 60);
+const recovered = point('10', 80);
+const dayBytes = (...points) => JSON.stringify({ date: day, metrics: { heart_rate: points } });
+const quantities = async () => JSON.parse(await readFile(liveDay(), 'utf8')).metrics.heart_rate.map(p => p.qty).sort();
+const archived = (result) => JSON.parse(execFileSync('tar', ['-xOzf', resolve(result.archivePath), `${day}.json`], { encoding: 'utf8' }));
+const tick = () => new Promise(done => setImmediate(done));
+// The faithful transfer: install the snapshot day that still holds `recovered`.
+const restoreDay = () => {
+ const transfer = vi.fn(() => writeFile(liveDay(), dayBytes(original, recovered)));
+ return { transfer, restore: withLiveHealthRestore(transfer) };
+};
+const holdOnce = (install) => {
+ const reached = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ let held = false;
+ install(async () => {
+ if (held) return;
+ held = true;
+ reached.resolve();
+ await release.promise;
+ });
+ return { reached: reached.promise, release: () => release.resolve() };
+};
+const holdDayRead = (path = liveDay()) => holdOnce(pause => {
+ controls.readFile = async (target, ...args) => {
+ const actual = await vi.importActual('fs/promises');
+ const bytes = await actual.readFile(target, ...args);
+ if (target === path) await pause();
+ return bytes;
+ };
+});
+
+beforeEach(async () => {
+ await rm(root, { recursive: true, force: true });
+ await mkdir(health, { recursive: true });
+ await writeFile(liveDay(), dayBytes(original));
+ Object.assign(controls, { readFile: null, rm: null, tar: null });
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-08T12:00:00Z'));
+});
+afterEach(() => vi.useRealTimers());
+afterAll(async () => { await rm(root, { recursive: true, force: true }); });
+
+describe('Apple Health restore admission (#10899)', () => {
+ it('settles an XML flush holding its pre-image before transfer; a later flush keeps restored points', async () => {
+ const xml = async (hour, value) => {
+ const xmlPath = join(root, `export-${hour}.xml`);
+ const date = `${day} ${hour}:00:00 +0000`;
+ await writeFile(xmlPath, `<HealthData><Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Watch" unit="count/min" startDate="${date}" endDate="${date}" value="${value}"/></HealthData>`);
+ return importAppleHealthXml(xmlPath);
+ };
+ const read = holdDayRead();
+ const stale = xml('09', 72);
+ let restore;
+ try {
+ await read.reached;
+ const restoring = restoreDay();
+ restore = restoring.restore;
+ await tick();
+ expect(restoring.transfer).not.toHaveBeenCalled();
+ const later = xml('11', 90);
+ read.release();
+ await Promise.all([stale, restore, later]);
+ } finally {
+ read.release();
+ await restore?.catch(() => {});
+ }
+ expect(await quantities()).toEqual([60, 80, 90]);
+ });
+
+ it('keeps restored bytes when archive removal had already compared the old day', async () => {
+ const removal = holdOnce(pause => {
+ controls.rm = async (path, ...args) => {
+ if (path === liveDay()) await pause();
+ const actual = await vi.importActual('fs/promises');
+ return actual.rm(path, ...args);
+ };
+ });
+ const archive = archiveCategory('health');
+ let restore;
+ try {
+ await removal.reached;
+ const restoring = restoreDay();
+ restore = restoring.restore;
+ await tick();
+ expect(restoring.transfer).not.toHaveBeenCalled();
+ removal.release();
+ const [result] = await Promise.all([archive, restore]);
+ expect(result).toMatchObject({ archived: 1, removed: 1 });
+ expect(archived(result).metrics.heart_rate).toEqual([original]);
+ } finally {
+ removal.release();
+ await restore?.catch(() => {});
+ }
+ // Without admission the hash-matched removal deletes the restored day.
+ expect(await quantities()).toEqual([60, 80]);
+ });
+
+ it('admits a restore while tar runs and retains the restored day instead of removing it', async () => {
+ const actual = await vi.importActual('../lib/childProcess.js');
+ const tar = holdOnce(pause => {
+ controls.tar = (command, args, options, callback) => actual.execFile(command, args, options, (...outcome) => {
+ pause().then(() => callback(...outcome));
+ });
+ });
+ const archive = archiveCategory('health');
+ try {
+ await tar.reached;
+ await restoreDay().restore;
+ } finally {
+ tar.release();
+ }
+ const result = await archive;
+ expect(result).toMatchObject({ archived: 1, removed: 0, retained: 1 });
+ expect(archived(result).metrics.heart_rate).toEqual([original]);
+ expect(await quantities()).toEqual([60, 80]);
+ });
+
+ it('reopens admission after a failed transfer so queued writers read the partial restore', async () => {
+ const transfer = vi.fn(async () => {
+ await writeFile(liveDay(), dayBytes(original, recovered));
+ throw Object.assign(new Error('synthetic rsync failure'), { code: 'BACKUP_RSYNC_FAILED' });
+ });
+ const restore = withLiveHealthRestore(transfer);
+ const later = mergeIntoDay(day, 'heart_rate', [point('11', 90)]);
+ await expect(restore).rejects.toMatchObject({ code: 'BACKUP_RSYNC_FAILED' });
+ await later;
+ expect(await quantities()).toEqual([60, 80, 90]);
+ });
+
+ it('keeps distinct days concurrent outside a restore', async () => {
+ const otherDay = '2024-01-02';
+ const read = holdDayRead();
+ const held = mergeIntoDay(day, 'heart_rate', [point('09', 72)]);
+ try {
+ await read.reached;
+ await expect(mergeIntoDay(otherDay, 'heart_rate', [{ date: `${otherDay} 09:00:00 +0000`, qty: 70 }]))
+ .resolves.toMatchObject({ added: 1 });
+ } finally {
+ read.release();
+ }
+ await held;
+ expect(await readdir(health)).toEqual([`${day}.json`, `${otherDay}.json`]);
+ });
+});
diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.js
index f92b706992..138e1e9473 100644
--- a/server/services/appleHealthXml.js
+++ b/server/services/appleHealthXml.js
@@ -8,7 +8,7 @@
import { createReadStream } from 'fs';
import { unlink } from 'fs/promises';
-import { extractDateStr, readDayFile, writeDayFile, upsertPoints, queueDayWrite } from './appleHealthIngest.js';
+import { extractDateStr, readDayFile, writeDayFile, upsertPoints, queueHealthDayMutation } from './appleHealthIngest.js';
import { createAppleHealthRecordStream } from './appleHealthXmlParser.js';
// === Mapping Tables ===
@@ -248,7 +248,9 @@ async function flushDayBuckets(dayBuckets) {
const allDates = Object.keys(dayBuckets);
for (const dateStr of allDates) {
- await queueDayWrite(dateStr, async () => {
+ // Admission is per day, so a live health restore can run between days and
+ // every later day re-reads the restored file rather than a stale one.
+ await queueHealthDayMutation(dateStr, async () => {
const metrics = dayBuckets[dateStr];
// Aggregate step_count: sum all qty values into single daily total
diff --git a/server/services/backup.js b/server/services/backup.js
index 84570b8775..fe4ebe0a00 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1728,8 +1728,11 @@ const COS_RESTORE_SCOPES = ['cos', 'cos/config.json', 'cos/state.json', 'cos/age
* - The settings queue stays held through CoS reconciliation.
* - CoS acquires config then runtime internally (`withLiveCosRestore`) and
* refuses a busy daemon/mind/agent with `COS_RESTORE_BUSY`.
- * - The media registry refuses edits for the whole hold and is acquired last,
- * so its write fence never outlives a refused CoS restore.
+ * - The media registry refuses edits for the whole hold and is acquired after
+ * CoS, so its write fence never outlives a refused CoS restore.
+ * - Apple Health admission is acquired last, for the same reason: it closes
+ * import/archive admission and drains admitted day cycles (which wait on no
+ * other owner) before the transfer, then reopens after cache invalidation.
*/
const LIVE_FILE_RESTORE_OWNERS = Object.freeze([
{
@@ -1773,6 +1776,14 @@ const LIVE_FILE_RESTORE_OWNERS = Object.freeze([
return withLiveMediaModelsRestore(inner);
},
},
+ {
+ name: 'Apple Health day files',
+ appliesTo: scope => !scope || scope === 'health' || scope.startsWith('health/'),
+ hold: async (inner) => {
+ const { withLiveHealthRestore } = await import('./appleHealthIngest.js');
+ return withLiveHealthRestore(inner);
+ },
+ },
]);
/** Run `operation` inside every live-restore owner that applies to `scope`, in table order. */
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index f1f7e615f6..a5965b671a 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -3140,6 +3140,13 @@ vi.mock('./taskScheduleStore.js', async (importOriginal) => {
});
import { withLiveTaskScheduleRestore, updateSchedule } from './taskScheduleStore.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+// Passthrough spy: health admission and day persistence stay real.
+vi.mock('./appleHealthIngest.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, withLiveHealthRestore: vi.fn(actual.withLiveHealthRestore) };
+});
+import { ingestHealthData, withLiveHealthRestore } from './appleHealthIngest.js';
+import { meatspaceEvents } from './meatspaceEvents.js';
describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () => {
beforeEach(() => {
@@ -3487,6 +3494,90 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>
});
});
+ describe('Apple Health restore ownership boundary (#10899)', () => {
+ const day = '2024-01-01';
+ const dayPath = () => join(PATHS.health, `${day}.json`);
+ const point = (hour, qty) => ({ date: `${day} ${hour}:00:00 +0000`, qty });
+ const ingest = (...points) => ingestHealthData({ data: { metrics: [{ name: 'heart_rate', data: points }] } });
+ const quantities = () => JSON.parse(readFileSync(dayPath(), 'utf8')).metrics.heart_rate.map(p => p.qty).sort();
+ beforeEach(() => { withLiveHealthRestore.mockClear(); });
+
+ it.each([undefined, 'health', 'health/', `health/${day}.json`])('holds health admission for affected live scope %s', async subdirFilter => {
+ await runRestore('/dest', 'snap-1', { dryRun: false, subdirFilter });
+ expect(withLiveHealthRestore).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([{ dryRun: true }, { dryRun: true, subdirFilter: 'health' }, { dryRun: false, subdirFilter: 'meatspace' }, { dryRun: false, subdirFilter: 'cos' }])('leaves unaffected scope alone: %j', async options => {
+ await runRestore('/dest', 'snap-1', options);
+ expect(withLiveHealthRestore).not.toHaveBeenCalled();
+ });
+
+ it('acquires health admission last and skips it when CoS refuses', async () => {
+ const order = [];
+ withLiveMediaModelsRestore.mockImplementationOnce(async fn => { order.push('media'); return fn(); });
+ withLiveHealthRestore.mockImplementationOnce(async fn => { order.push('health'); return fn(); });
+ await runRestore('/dest', 'snap-1', { dryRun: false });
+ expect(order).toEqual(['media', 'health']);
+ withLiveCosRestore.mockRejectedValueOnce(Object.assign(new Error('Stop CoS before restoring'), { code: 'COS_RESTORE_BUSY' }));
+ await expect(restoreSnapshot('/dest', 'snap-1', { dryRun: false })).rejects.toMatchObject({ code: 'COS_RESTORE_BUSY' });
+ expect(withLiveHealthRestore).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([0, 1])('drains an ingest holding a pre-image before rsync and keeps restored points (exit %s)', async exitCode => {
+ const actual = await vi.importActual('fs/promises');
+ const original = point('08', 60);
+ const recovered = point('10', 80);
+ await actual.mkdir(PATHS.health, { recursive: true });
+ writeFileSync(dayPath(), JSON.stringify({ date: day, metrics: { heart_rate: [original] } }));
+ const reading = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ let held = false;
+ fs.readFile.mockImplementation(async (path, ...args) => {
+ const bytes = await actual.readFile(path, ...args);
+ if (path === dayPath() && !held) {
+ held = true;
+ reading.resolve();
+ await release.promise;
+ }
+ return bytes;
+ });
+ const invalidated = vi.fn();
+ meatspaceEvents.on('changed', invalidated);
+ const proc = fakeProc();
+ spawn.mockImplementationOnce(() => {
+ // Real destination bytes at the rsync process boundary: the snapshot
+ // still holds a point the live day lost.
+ writeFileSync(dayPath(), JSON.stringify({ date: day, metrics: { heart_rate: [original, recovered] } }));
+ setImmediate(() => proc.emit('close', exitCode));
+ return proc;
+ });
+ let restore;
+ try {
+ const stale = ingest(point('09', 72));
+ await reading.promise;
+ restore = restoreSnapshot('/dest', 'snap-1', { dryRun: false, subdirFilter: 'health' });
+ await vi.waitFor(() => expect(withLiveHealthRestore).toHaveBeenCalledTimes(1));
+ await settle();
+ expect(spawn).not.toHaveBeenCalled();
+ const later = ingest(point('11', 90));
+ release.resolve();
+ await stale;
+ if (exitCode) await expect(restore).rejects.toThrow(/Some files may already have been overwritten/);
+ else await restore;
+ await later;
+ // The admitted ingest settled before transfer; the queued one read the
+ // restored day, so the recovered point survives both.
+ expect(quantities()).toEqual([60, 80, 90]);
+ expect(invalidated).toHaveBeenCalledWith({ resources: ['healthBody'] });
+ } finally {
+ release.resolve();
+ await restore?.catch(() => {});
+ meatspaceEvents.off('changed', invalidated);
+ fs.readFile.mockImplementation(actual.readFile);
+ }
+ });
+ });
+
describe('settings restore ownership boundary', () => {
it.each([undefined, 'settings.json'])('holds the boundary for affected live scope %s', async subdirFilter => {
const proc = fakeProc();
diff --git a/server/services/dataManager.archive.test.js b/server/services/dataManager.archive.test.js
index e26f6660af..88899ac3d4 100644
--- a/server/services/dataManager.archive.test.js
+++ b/server/services/dataManager.archive.test.js
@@ -20,9 +20,9 @@ vi.mock('fs/promises', async (importOriginal) => {
});
vi.mock('./appleHealthIngest.js', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, queueDayWrite: (...args) => {
+ return { ...actual, queueHealthDayMutation: (...args) => {
controls.queued?.(...args);
- return actual.queueDayWrite(...args);
+ return actual.queueHealthDayMutation(...args);
} };
});
vi.mock('crypto', async (importOriginal) => {
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 2b0486ac05..5164283382 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -420,7 +420,7 @@ export async function archiveCategory(categoryKey, options = {}) {
try {
const capturedDays = [];
- let queueDayWrite;
+ let queueHealthDayMutation;
if (categoryKey === 'health') {
const daysToKeep = options.daysToKeep ?? 365;
const cutoff = new Date();
@@ -431,13 +431,14 @@ export async function archiveCategory(categoryKey, options = {}) {
const oldFiles = files.filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f) && f.slice(0, 10) < cutoffStr);
if (oldFiles.length === 0) return { archived: 0, removed: 0, retained: 0, alreadyAbsent: 0, archivePath: null, message: 'No old files to archive' };
- // Share the importers' queue for capture and removal, but release it
- // during tar so a large archive does not block a historical backfill.
- ({ queueDayWrite } = await import('./appleHealthIngest.js'));
+ // Share the importers' admission and day queue for capture and removal,
+ // but release both during tar so a large archive blocks neither a
+ // historical backfill nor a live health restore (#10899).
+ ({ queueHealthDayMutation } = await import('./appleHealthIngest.js'));
const stagedDays = join(operationDir, 'days');
await ensureDir(stagedDays);
for (const file of oldFiles) {
- await queueDayWrite(file.slice(0, 10), async () => {
+ await queueHealthDayMutation(file.slice(0, 10), async () => {
const bytes = await readFile(join(dirPath, file));
await writeFileGuarded(join(stagedDays, file), bytes, { flag: 'wx' });
capturedDays.push({ file, hash: sha256Text(bytes) });
@@ -468,7 +469,7 @@ export async function archiveCategory(categoryKey, options = {}) {
let retained = 0;
let alreadyAbsent = 0;
for (const { file, hash } of capturedDays) {
- await queueDayWrite(file.slice(0, 10), async () => {
+ await queueHealthDayMutation(file.slice(0, 10), async () => {
const livePath = join(dirPath, file);
const bytes = await readFile(livePath).catch(error => {
// Another archive may already have removed this exact day.