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: dedupe Apple Health daily totals across devices and importers (#8450)

[._.]/ Adam Eivy3564f42c732f
diff --git a/server/services/appleHealthIngest.js b/server/services/appleHealthIngest.js
index d99bc68de4..344c328169 100644
--- a/server/services/appleHealthIngest.js
+++ b/server/services/appleHealthIngest.js
@@ -169,7 +169,11 @@ export async function ingestHealthData(payload) {
const dataPoints = metric.data ?? [];
metricsProcessed++;
- // Group data points by extracted day string
+ // Group data points by extracted day string, stamping origin so the
+ // read side can pick a single source of truth per metric-day and avoid
+ // double-counting against XML-imported points for the same day (#8450).
+ // HealthKit has already deduplicated across devices before Health Auto
+ // Export sends this payload.
const byDay = new Map();
for (const point of dataPoints) {
const dateStr = extractDateStr(point.date);
@@ -178,7 +182,7 @@ export async function ingestHealthData(payload) {
continue;
}
if (!byDay.has(dateStr)) byDay.set(dateStr, []);
- byDay.get(dateStr).push(point);
+ byDay.get(dateStr).push({ ...point, origin: 'hae' });
}
// Merge each day's points into the corresponding day file
diff --git a/server/services/appleHealthIngest.test.js b/server/services/appleHealthIngest.test.js
index 83622a61ef..14b9a9c2c6 100644
--- a/server/services/appleHealthIngest.test.js
+++ b/server/services/appleHealthIngest.test.js
@@ -269,7 +269,7 @@ describe('ingestHealthData', () => {
date: '2024-01-15',
metrics: {
step_count: [
- { date: '2024-01-15 08:00:00 -0800', qty: 9000 },
+ { date: '2024-01-15 08:00:00 -0800', qty: 9000, origin: 'hae' },
],
},
updated: originalTime,
@@ -296,6 +296,42 @@ describe('ingestHealthData', () => {
expect(result.recordsSkipped).toBe(1); // counted as dupe
});
+ it('re-stamps a legacy point (no origin) as an update exactly once, then treats it as a dupe (#8450)', async () => {
+ const dayPath = join(PATHS.health, '2024-01-16.json');
+ await writeFile(dayPath, JSON.stringify({
+ date: '2024-01-16',
+ metrics: {
+ step_count: [
+ { date: '2024-01-16 08:00:00 -0800', qty: 9000 }, // pre-#8450: no origin stamp
+ ],
+ },
+ updated: new Date('2024-01-01T00:00:00Z').toISOString(),
+ }), 'utf-8');
+
+ const payload = {
+ data: {
+ metrics: [
+ { name: 'step_count', data: [{ date: '2024-01-16 08:00:00 -0800', qty: 9000 }] },
+ ],
+ },
+ };
+
+ // First re-sync after upgrading: same value, but ingestHealthData now
+ // stamps origin, so the stored point differs from the legacy one and is
+ // counted as an update (self-healing one-time migration).
+ const first = await ingestHealthData(payload);
+ expect(first.recordsIngested).toBe(0);
+ expect(first.recordsUpdated).toBe(1);
+ expect(first.recordsSkipped).toBe(0);
+
+ // Second re-sync: the stored point now carries origin: 'hae' too, so it's
+ // a true dupe again.
+ const second = await ingestHealthData(payload);
+ expect(second.recordsIngested).toBe(0);
+ expect(second.recordsUpdated).toBe(0);
+ expect(second.recordsSkipped).toBe(1);
+ });
+
it('mixes additions, updates, and dupes in one ingest', async () => {
const dayPath = join(PATHS.health, '2024-01-15.json');
const originalTime = new Date('2024-01-01T00:00:00Z').toISOString();
@@ -303,8 +339,8 @@ describe('ingestHealthData', () => {
date: '2024-01-15',
metrics: {
step_count: [
- { date: '2024-01-15 08:00:00 -0800', qty: 300 }, // will be updated
- { date: '2024-01-15 12:00:00 -0800', qty: 400 }, // will be skipped (dupe)
+ { date: '2024-01-15 08:00:00 -0800', qty: 300, origin: 'hae' }, // will be updated
+ { date: '2024-01-15 12:00:00 -0800', qty: 400, origin: 'hae' }, // will be skipped (dupe)
],
},
updated: originalTime,
diff --git a/server/services/appleHealthQuery.js b/server/services/appleHealthQuery.js
index fc1db697f1..ef18af601c 100644
--- a/server/services/appleHealthQuery.js
+++ b/server/services/appleHealthQuery.js
@@ -50,6 +50,61 @@ export async function getAvailableDateRange() {
return { from: dates[0], to: dates[dates.length - 1], totalDays: dates.length };
}
+// === Aggregation Helpers ===
+
+/**
+ * Choose the single source of truth for a summed metric-day, avoiding
+ * double-counting when multiple devices and/or importers recorded the same
+ * day (e.g. an XML export from an iPhone + Apple Watch pair, or an XML
+ * import overlapping a Health Auto Export sync of the same day).
+ *
+ * - If any point carries `origin: 'hae'` (Health Auto Export — HealthKit has
+ * already deduplicated across devices before sending it), use only the
+ * HAE points.
+ * - Otherwise, group the remaining (XML-origin) points by `src` (source
+ * device) and return only the single source with the largest total. This
+ * is the standard approximation of Apple Health's own source-priority
+ * dedup and never double-counts by summing across devices.
+ * - Legacy points written before origin stamping (#8450) have no `origin`:
+ * a point carrying an `src` key is XML-origin (only the XML importer ever
+ * writes `src`); anything else is treated as HAE-origin, which keeps
+ * legacy HAE-only installs byte-identical.
+ *
+ * @param {Array<Object>} points - A day's points for one summed metric
+ * @param {(point: Object) => number} getValue - Extracts the summable value from a point
+ * @returns {Array<Object>} The chosen subset of points to sum/aggregate
+ */
+export function pickDaySumPoints(points, getValue) {
+ if (points.length === 0) return points;
+
+ const originOf = (p) => p.origin ?? (Object.prototype.hasOwnProperty.call(p, 'src') ? 'xml' : 'hae');
+
+ const haePoints = points.filter((p) => originOf(p) === 'hae');
+ if (haePoints.length > 0) return haePoints;
+
+ const xmlPoints = points.filter((p) => originOf(p) === 'xml');
+ if (xmlPoints.length === 0) return points;
+
+ const bySrc = new Map();
+ for (const p of xmlPoints) {
+ const src = p.src ?? 'unknown';
+ if (!bySrc.has(src)) bySrc.set(src, []);
+ bySrc.get(src).push(p);
+ }
+
+ let bestSrc = null;
+ let bestTotal = -Infinity;
+ for (const [src, pts] of bySrc) {
+ const total = pts.reduce((sum, p) => sum + (getValue(p) || 0), 0);
+ if (total > bestTotal) {
+ bestTotal = total;
+ bestSrc = src;
+ }
+ }
+
+ return bySrc.get(bestSrc);
+}
+
// === Metric Queries ===
/**
@@ -145,13 +200,16 @@ export async function getDailyAggregates(metricName, from, to) {
let value;
if (metricName === 'sleep_analysis') {
- // Sum all aggregated sleep entries (batch flushing may produce multiple per day)
+ // Sum aggregated sleep entries for the day's chosen source of truth
+ // (batch flushing may produce multiple per day per source; multiple
+ // *sources* the same night must not be summed together — #8450).
const sleepPoints = points.filter(p => p.totalSleep !== undefined);
if (sleepPoints.length > 0) {
- const deep = sleepPoints.reduce((s, p) => s + (p.deep ?? 0), 0);
- const rem = sleepPoints.reduce((s, p) => s + (p.rem ?? 0), 0);
- const core = sleepPoints.reduce((s, p) => s + (p.core ?? 0), 0);
- const awake = sleepPoints.reduce((s, p) => s + (p.awake ?? 0), 0);
+ const chosen = pickDaySumPoints(sleepPoints, (p) => (p.deep ?? 0) + (p.rem ?? 0) + (p.core ?? 0));
+ const deep = chosen.reduce((s, p) => s + (p.deep ?? 0), 0);
+ const rem = chosen.reduce((s, p) => s + (p.rem ?? 0), 0);
+ const core = chosen.reduce((s, p) => s + (p.core ?? 0), 0);
+ const awake = chosen.reduce((s, p) => s + (p.awake ?? 0), 0);
results.push({
date: dateStr,
value: Math.round((deep + rem + core) * 100) / 100,
@@ -160,8 +218,10 @@ export async function getDailyAggregates(metricName, from, to) {
}
continue;
} else if (SUM_METRICS.has(metricName)) {
- // Sum qty per day
- value = points.reduce((sum, p) => sum + (p.qty ?? 0), 0);
+ // Sum qty for the day's chosen source of truth, not every stored
+ // point — multiple devices/importers would otherwise double-count (#8450).
+ const chosen = pickDaySumPoints(points, (p) => p.qty ?? 0);
+ value = chosen.reduce((sum, p) => sum + (p.qty ?? 0), 0);
} else if (metricName === 'heart_rate') {
// Average of Avg values (JSON ingest) or qty values (XML ingest)
const avgPoints = points.filter(p => p.Avg !== undefined);
diff --git a/server/services/appleHealthQuery.test.js b/server/services/appleHealthQuery.test.js
new file mode 100644
index 0000000000..40537e683b
--- /dev/null
+++ b/server/services/appleHealthQuery.test.js
@@ -0,0 +1,148 @@
+/**
+ * Apple Health Query Service Tests
+ *
+ * `pickDaySumPoints` is the read-side fix for #8450: a metric-day's stored
+ * points can come from multiple devices (XML export: iPhone + Apple Watch)
+ * and/or multiple importers (XML import + Health Auto Export JSON ingest)
+ * covering the same day. Summing all of them double- or triple-counts
+ * steps, energy, and sleep. These tests pin the dedup rule at the pure
+ * boundary, then verify `getDailyAggregates` applies it end-to-end.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
+
+const tempDirs = [];
+beforeEach(async () => {
+ const tempDir = await mkdtemp(join(tmpdir(), 'portos-ahQuery-test-'));
+ tempDirs.push(tempDir);
+ Object.defineProperty(PATHS, 'health', {
+ value: tempDir,
+ configurable: true,
+ });
+});
+
+afterEach(async () => {
+ for (const dir of tempDirs) {
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
+ }
+ tempDirs.length = 0;
+});
+
+const { pickDaySumPoints, getDailyAggregates } = await import('./appleHealthQuery.js');
+
+const qty = (p) => p.qty ?? 0;
+
+describe('pickDaySumPoints', () => {
+ it('picks the largest single XML source instead of summing devices (acceptance #1)', () => {
+ const points = [
+ { date: '2024-01-15 08:00:00 -0800', qty: 8000, src: 'iPhone', origin: 'xml' },
+ { date: '2024-01-15 08:05:00 -0800', qty: 9000, src: 'Apple Watch', origin: 'xml' },
+ ];
+ const chosen = pickDaySumPoints(points, qty);
+ expect(chosen).toHaveLength(1);
+ expect(chosen[0].src).toBe('Apple Watch');
+ expect(chosen.reduce((s, p) => s + p.qty, 0)).toBe(9000);
+ });
+
+ it('prefers HAE (already HealthKit-deduplicated) points over any XML points (acceptance #2)', () => {
+ const points = [
+ { date: '2024-01-15 08:00:00 -0800', qty: 8000, src: 'iPhone', origin: 'xml' },
+ { date: '2024-01-15 08:05:00 -0800', qty: 9000, src: 'Apple Watch', origin: 'xml' },
+ { date: '2024-01-15T00:00:00Z', qty: 9100, origin: 'hae' },
+ ];
+ const chosen = pickDaySumPoints(points, qty);
+ expect(chosen).toHaveLength(1);
+ expect(chosen[0].origin).toBe('hae');
+ expect(chosen.reduce((s, p) => s + p.qty, 0)).toBe(9100);
+ });
+
+ it('reports the larger of two sleep sources rather than summing them (acceptance #3)', () => {
+ const points = [
+ { date: '2024-01-15 22:00:00 -0800', deep: 1, rem: 1, core: 3, awake: 0.5, src: 'Apple Watch', origin: 'xml' },
+ { date: '2024-01-15 23:00:00 -0800', deep: 0.5, rem: 0.5, core: 2, awake: 0.2, src: 'iPhone', origin: 'xml' },
+ ];
+ const getSleepTotal = (p) => (p.deep ?? 0) + (p.rem ?? 0) + (p.core ?? 0);
+ const chosen = pickDaySumPoints(points, getSleepTotal);
+ expect(chosen).toHaveLength(1);
+ expect(chosen[0].src).toBe('Apple Watch');
+ });
+
+ it('sums legacy HAE-only points with no origin/src exactly as before (acceptance #4)', () => {
+ const points = [
+ { date: '2024-01-15T00:00:00Z', qty: 4000 },
+ { date: '2024-01-15T06:00:00Z', qty: 5000 },
+ ];
+ const chosen = pickDaySumPoints(points, qty);
+ expect(chosen).toEqual(points);
+ expect(chosen.reduce((s, p) => s + p.qty, 0)).toBe(9000);
+ });
+
+ it('treats legacy points carrying an src key (no origin) as XML and dedups by source', () => {
+ const points = [
+ { date: '2024-01-15 08:00:00 -0800', qty: 8000, src: 'iPhone' },
+ { date: '2024-01-15 08:05:00 -0800', qty: 9000, src: 'Apple Watch' },
+ ];
+ const chosen = pickDaySumPoints(points, qty);
+ expect(chosen).toHaveLength(1);
+ expect(chosen[0].src).toBe('Apple Watch');
+ });
+
+ it('returns the input unchanged for an empty array', () => {
+ expect(pickDaySumPoints([], qty)).toEqual([]);
+ });
+});
+
+describe('getDailyAggregates', () => {
+ async function writeDay(dateStr, metrics) {
+ await writeFile(
+ join(PATHS.health, `${dateStr}.json`),
+ JSON.stringify({ date: dateStr, metrics, updated: new Date().toISOString() }),
+ 'utf-8'
+ );
+ }
+
+ it('does not double-count step_count across two XML source devices for the same day', async () => {
+ await writeDay('2024-02-01', {
+ step_count: [
+ { date: '2024-02-01 08:00:00 -0800', qty: 8000, unit: 'count', src: 'iPhone', origin: 'xml' },
+ { date: '2024-02-01 08:05:00 -0800', qty: 9000, unit: 'count', src: 'Apple Watch', origin: 'xml' },
+ ],
+ });
+
+ const results = await getDailyAggregates('step_count', '2024-02-01', '2024-02-01');
+ expect(results).toEqual([{ date: '2024-02-01', value: 9000 }]);
+ });
+
+ it('does not double-count sleep_analysis across two sources for the same night', async () => {
+ await writeDay('2024-02-02', {
+ sleep_analysis: [
+ { date: '2024-02-02 22:00:00 -0800', totalSleep: 5, deep: 1, rem: 1, core: 3, awake: 0.5, src: 'Apple Watch', origin: 'xml' },
+ { date: '2024-02-02 23:00:00 -0800', totalSleep: 3, deep: 0.5, rem: 0.5, core: 2, awake: 0.2, src: 'iPhone', origin: 'xml' },
+ ],
+ });
+
+ const results = await getDailyAggregates('sleep_analysis', '2024-02-02', '2024-02-02');
+ expect(results).toHaveLength(1);
+ expect(results[0].value).toBe(5);
+ expect(results[0].deep).toBe(1);
+ expect(results[0].rem).toBe(1);
+ expect(results[0].core).toBe(3);
+ expect(results[0].awake).toBe(0.5);
+ });
+
+ it('aggregates legacy HAE-only day files exactly as before (no origin/src)', async () => {
+ await writeDay('2024-02-03', {
+ step_count: [
+ { date: '2024-02-03T00:00:00Z', qty: 4000 },
+ { date: '2024-02-03T06:00:00Z', qty: 5000 },
+ ],
+ });
+
+ const results = await getDailyAggregates('step_count', '2024-02-03', '2024-02-03');
+ expect(results).toEqual([{ date: '2024-02-03', value: 9000 }]);
+ });
+});
diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.js
index 9a244b96ab..b5679c4775 100644
--- a/server/services/appleHealthXml.js
+++ b/server/services/appleHealthXml.js
@@ -131,7 +131,7 @@ export function normalizeXmlRecord(node) {
: 0;
const valueLower = value?.toLowerCase() ?? '';
const stage = SLEEP_STAGE_MAP[valueLower] ?? value ?? 'unknown';
- const dataPoint = { date: startdate, stage, durationHours };
+ const dataPoint = { date: startdate, stage, durationHours, src: sourcename ?? null, origin: 'xml' };
return { metricName, dateStr, dataPoint };
}
@@ -145,6 +145,7 @@ export function normalizeXmlRecord(node) {
unit: unit ?? null,
src: sourcename ?? null,
end: enddate ?? null,
+ origin: 'xml',
};
return { metricName, dateStr, dataPoint };
}
@@ -157,6 +158,7 @@ export function normalizeXmlRecord(node) {
qty: parsed,
unit: unit ?? null,
src: sourcename ?? null,
+ origin: 'xml',
};
return { metricName, dateStr, dataPoint };
}
@@ -164,41 +166,70 @@ export function normalizeXmlRecord(node) {
// === Aggregation ===
/**
- * Aggregate step_count entries in a day bucket — sum all qty values into a single total.
- * Apple Health emits per-activity step records; we want the daily total.
+ * Group data points by their `src` (source device name), preserving insertion order.
+ *
+ * @param {Array} points - Data points, each optionally carrying `src`
+ * @returns {Map<string|null, Array>} Points grouped by src
+ */
+function groupBySrc(points) {
+ const bySrc = new Map();
+ for (const p of points) {
+ const src = p.src ?? null;
+ if (!bySrc.has(src)) bySrc.set(src, []);
+ bySrc.get(src).push(p);
+ }
+ return bySrc;
+}
+
+/**
+ * Aggregate step_count entries in a day bucket into one total PER SOURCE DEVICE.
+ * Apple Health emits per-activity step records, often from multiple devices
+ * (iPhone + Watch) covering the same walk — summing across sources would
+ * double-count, so this keeps one aggregate per `src` and defers picking the
+ * single source of truth to read time (see `pickDaySumPoints` in appleHealthQuery.js).
*
* @param {Array} points - Array of step_count data points
- * @returns {Array} Single-element array with aggregated total
+ * @returns {Array} One aggregated entry per source device
*/
function aggregateStepCount(points) {
if (!points.length) return points;
- const total = points.reduce((sum, p) => sum + (p.qty || 0), 0);
- // Use first point's date for the aggregated entry
- return [{ date: points[0].date, qty: total, unit: points[0].unit ?? null }];
+ return Array.from(groupBySrc(points).entries()).map(([src, pts]) => ({
+ date: pts[0].date,
+ qty: pts.reduce((sum, p) => sum + (p.qty || 0), 0),
+ unit: pts[0].unit ?? null,
+ src,
+ origin: 'xml',
+ }));
}
/**
- * Aggregate sleep_analysis entries in a day bucket — sum duration by stage per day.
+ * Aggregate sleep_analysis entries in a day bucket into one summary PER SOURCE DEVICE.
+ * Multiple sleep sources (Watch, iPhone, third-party trackers) can record the
+ * same night — summing across sources would double-count, so this keeps one
+ * summary per `src` and defers picking the single source of truth to read
+ * time (see `pickDaySumPoints` in appleHealthQuery.js).
*
* @param {Array} points - Array of sleep_analysis data points with stage/durationHours
- * @returns {Object} Aggregated sleep summary { date, totalSleep, deep, rem, core, awake, inBed, asleep }
+ * @returns {Array} One aggregated summary per source device: { date, totalSleep, deep, rem, core, awake, inBed, asleep, src, origin }
*/
function aggregateSleepAnalysis(points) {
if (!points.length) return points;
- const summary = { date: points[0].date, totalSleep: 0, deep: 0, rem: 0, core: 0, awake: 0, inBed: 0, asleep: 0 };
- for (const p of points) {
- const stage = p.stage;
- const dur = p.durationHours || 0;
- if (stage === 'deep') summary.deep += dur;
- else if (stage === 'rem') summary.rem += dur;
- else if (stage === 'core') summary.core += dur;
- else if (stage === 'awake') summary.awake += dur;
- else if (stage === 'inBed') summary.inBed += dur;
- else if (stage === 'asleep') summary.asleep += dur;
- }
- // totalSleep = meaningful sleep stages (deep + rem + core)
- summary.totalSleep = summary.deep + summary.rem + summary.core;
- return [summary];
+ return Array.from(groupBySrc(points).entries()).map(([src, pts]) => {
+ const summary = { date: pts[0].date, totalSleep: 0, deep: 0, rem: 0, core: 0, awake: 0, inBed: 0, asleep: 0, src, origin: 'xml' };
+ for (const p of pts) {
+ const stage = p.stage;
+ const dur = p.durationHours || 0;
+ if (stage === 'deep') summary.deep += dur;
+ else if (stage === 'rem') summary.rem += dur;
+ else if (stage === 'core') summary.core += dur;
+ else if (stage === 'awake') summary.awake += dur;
+ else if (stage === 'inBed') summary.inBed += dur;
+ else if (stage === 'asleep') summary.asleep += dur;
+ }
+ // totalSleep = meaningful sleep stages (deep + rem + core)
+ summary.totalSleep = summary.deep + summary.rem + summary.core;
+ return summary;
+ });
}
// === Main Export ===