Skip to content
30 changes: 30 additions & 0 deletions docs/production-incident-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -21250,3 +21250,33 @@ Drizzle schema and runtime Zod schemas. Findings and remediations:
- **Remaining risk / follow-up:** Group coupled CodeQL and Slack dependencies
in Dependabot configuration so future updates arrive atomically. Continue to
require a native Release build for Sentry React Native updates.

## 2026-07-30 — HealthKit Observer Expirations Reported as Sentry Errors

- **Status:** Fixed in source; pending native iOS release and Sentry resolution.
- **Symptoms:** Sentry issue
[DOFEK-MOBILE-1C](https://east-bay-software.sentry.io/issues/7633118736/)
recorded handled `com.dofek.healthkit-observer: Code: 1` events when native
observer callbacks expired before JavaScript acknowledged them.
- **User impact:** No crash or data loss. HealthKit can redeliver updates after
expiration, and successful syncs still uploaded data. The events were false
positives under iOS background suspension and long-running observer syncs.
- **Evidence:** Prior fixes scoped observer syncs to delivered types, removed
JavaScript debouncing, and suppressed Sentry capture only while JavaScript
reported an active sync. Expirations still reached Sentry when the JavaScript
thread was suspended before `setObserverSyncInProgress(true)` ran, and when
sync exceeded the unchanged 25-second native boundary without the flag set.
- **Root cause:** Observer expiration telemetry treated an expected iOS
background timing boundary as an actionable error, and the sync-in-progress
flag was set too late in the JavaScript delivery path.
Comment thread
qodo-code-review[bot] marked this conversation as resolved.
Resolved
- **Fix / mitigation:** Mark observer sync in progress at native delivery and
in the JavaScript listener before queueing work. Never capture observer
expirations to Sentry; record them as informational breadcrumbs only. Clear
the in-progress flag only when no observer updates remain pending natively or
in the JavaScript queue. Prior type-scoped sync, anchor commit, and timeout
behavior are unchanged.
- **Validation:** Mobile Vitest background HealthKit orchestration tests pass.
The HealthKit Swift package passes 78 tests, including pending-update
tracking on the observer coordinator.
- **Remaining risk / follow-up:** Ship through the normal native iOS release
path, then resolve DOFEK-MOBILE-1C in Sentry after production events stop.
2 changes: 2 additions & 0 deletions packages/mobile/lib/background-health-kit-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -662,13 +662,15 @@ describe("initBackgroundHealthKitSync", () => {
const startingSyncCount = mockLoggerInfo.mock.calls.filter(
([, message]) => message === "Starting sync",
).length;
mockSetObserverSyncInProgress.mockClear();

const listener = mockAddSampleUpdateListener.mock.calls[0][0];
listener({
typeIdentifier: "HKQuantityTypeIdentifierStepCount",
updateId: "update-1",
});

expect(mockSetObserverSyncInProgress).toHaveBeenCalledWith(true);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(
mockLoggerInfo.mock.calls.filter(([, message]) => message === "Starting sync"),
).toHaveLength(startingSyncCount + 1);
Expand Down
3 changes: 2 additions & 1 deletion packages/mobile/lib/background-health-kit-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ async function drainSyncQueue(): Promise<void> {
}
} finally {
syncing = undefined;
setObserverSyncInProgress(false);
setObserverSyncInProgress(pendingUpdates.size > 0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

await drainSyncQueue();
Expand Down Expand Up @@ -246,6 +246,7 @@ export async function initBackgroundHealthKitSync(
typeIdentifier: event.typeIdentifier,
});
pendingUpdates.set(event.updateId, event.typeIdentifier);
setObserverSyncInProgress(true);
void drainSyncQueue();
});

Expand Down
12 changes: 7 additions & 5 deletions packages/mobile/modules/health-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@ Updates delivered during a running sync remain pending for the next serialized
sync. Re-registration, JavaScript teardown, and Expo module destruction stop
the queries and complete every callback still pending.

A native 25-second expiration completes an update exactly once and reports the
expired update ID, HealthKit sample type, and monotonic callback age to Sentry
if JavaScript never responds. JavaScript logs the start and completion of each
query, upload batch, and post-sync callback with its duration and item context.
A native 25-second expiration completes an update exactly once and records the
expired update ID, HealthKit sample type, and monotonic callback age as a Sentry
breadcrumb when JavaScript never responds. Observer expirations are expected
under iOS background constraints and are not reported as Sentry errors. JavaScript
logs the start and completion of each query, upload batch, and post-sync callback
with its duration and item context.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
This is a failure boundary, not a successful sync signal; the next HealthKit
delivery remains eligible to retry the same data. Apple's background-delivery
contract requires calling the observer completion handler only after processing
Expand Down Expand Up @@ -94,7 +96,7 @@ a physical iPhone with a Release build:
that the query, upload, post-sync callback, and overall observer logs include
monotonic durations and item context.
3. Verify JavaScript acknowledges the update ID before the 25-second native
expiration and that no `com.dofek.healthkit-observer` expiration event is
expiration and that no `com.dofek.healthkit-observer` Sentry error is
reported.
4. Repeat with multiple sample types delivered together and confirm every
update ID is completed exactly once after its queued serialized sync settles.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ final class HealthKitObserverUpdateCoordinatorTests: XCTestCase {
XCTAssertEqual(completionCount, 1)
}

func testHasPendingUpdatesReflectsRegistrationAndCompletion() {
let coordinator = HealthKitObserverUpdateCoordinator(timeout: 60)
XCTAssertFalse(coordinator.hasPendingUpdates)

let updateId = coordinator.register(typeIdentifier: "HKQuantityTypeIdentifierStepCount") {}
XCTAssertTrue(coordinator.hasPendingUpdates)

XCTAssertEqual(coordinator.complete(updateIds: [updateId]), 1)
XCTAssertFalse(coordinator.hasPendingUpdates)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

func testTeardownCompletesEveryPendingUpdateExactlyOnce() {
var completionCount = 0
let coordinator = HealthKitObserverUpdateCoordinator(timeout: 60)
Expand Down
52 changes: 23 additions & 29 deletions packages/mobile/modules/health-kit/ios/HealthKitModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,38 +46,27 @@ public class HealthKitModule: Module {
private lazy var observerUpdateCoordinator = HealthKitObserverUpdateCoordinator(
timeout: 25,
reportExpiration: { [weak self] expiration in
guard let self else {
return
}
if self.observerSyncInProgress {
let breadcrumb = Breadcrumb(level: .info, category: "healthkit.observer")
breadcrumb.message =
"Observer update expired while JavaScript sync was still running"
breadcrumb.data = [
"updateId": expiration.updateId,
"typeIdentifier": expiration.typeIdentifier,
"ageMilliseconds": expiration.ageMilliseconds,
]
SentrySDK.addBreadcrumb(breadcrumb)
return
}
SentrySDK.capture(
error: NSError(
domain: "com.dofek.healthkit-observer",
code: 1,
userInfo: [
NSLocalizedDescriptionKey:
"HealthKit observer update expired before JavaScript sync completed",
"updateId": expiration.updateId,
"typeIdentifier": expiration.typeIdentifier,
"ageMilliseconds": expiration.ageMilliseconds,
]
)
)
self?.handleObserverUpdateExpiration(expiration)
}
)
private var observerQueries: [HKObserverQuery] = []

private func handleObserverUpdateExpiration(_ expiration: HealthKitObserverUpdateExpiration) {
let breadcrumb = Breadcrumb(level: .info, category: "healthkit.observer")
breadcrumb.message = observerSyncInProgress
? "Observer update expired while JavaScript sync was still running"
: "Observer update expired before JavaScript sync completed"
breadcrumb.data = [
"updateId": expiration.updateId,
"typeIdentifier": expiration.typeIdentifier,
"ageMilliseconds": expiration.ageMilliseconds,
]
SentrySDK.addBreadcrumb(breadcrumb)
if !observerUpdateCoordinator.hasPendingUpdates {
observerSyncInProgress = false
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

@discardableResult
private func stopBackgroundObservers() -> Int {
for query in observerQueries {
Expand Down Expand Up @@ -862,6 +851,7 @@ public class HealthKitModule: Module {
typeIdentifier: sampleType.identifier,
completion: completionHandler
)
self.observerSyncInProgress = true
MainThreadEventEmitter.emit(
[
"typeIdentifier": sampleType.identifier,
Expand Down Expand Up @@ -914,7 +904,11 @@ public class HealthKitModule: Module {
}

Function("setObserverSyncInProgress") { (inProgress: Bool) in
self.observerSyncInProgress = inProgress
if inProgress {
self.observerSyncInProgress = true
} else if !self.observerUpdateCoordinator.hasPendingUpdates {
self.observerSyncInProgress = false
}
}

Function("completeObserverUpdates") { (updateIds: [String], succeeded: Bool) -> Int in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ final class HealthKitObserverUpdateCoordinator {
self.reportExpiration = reportExpiration
}

var hasPendingUpdates: Bool {
lock.withLock {
!pendingUpdates.isEmpty
}
}

func register(typeIdentifier: String, completion: @escaping () -> Void) -> String {
let updateId = UUID().uuidString
let expiration = DispatchWorkItem { [weak self] in
Expand Down
3 changes: 3 additions & 0 deletions packages/server/src/routers/health-report.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createReportEmptyState } from "../contracts/report-empty-state.ts";
import { HealthReportRepository, SharedReport } from "../repositories/health-report-repository.ts";
import { createTestCallerFactory, makeMockSensorStore } from "./test-helpers.ts";

Expand Down Expand Up @@ -99,6 +100,7 @@ describe("healthReportRouter", () => {
"Repeat or deliberately adjust one part of the routine next week, then compare it with this baseline.",
],
}),
emptyState: createReportEmptyState("weekly"),
}),
null,
);
Expand Down Expand Up @@ -162,6 +164,7 @@ describe("healthReportRouter", () => {
"Repeat or deliberately adjust one part of the routine next month, then compare it with this baseline.",
],
}),
emptyState: createReportEmptyState("monthly"),
}),
30,
);
Expand Down
51 changes: 3 additions & 48 deletions packages/web/src/components/MonthlyReportContent.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { MonthlyReportContent } from "./MonthlyReportContent.tsx";
import { monthlyReportEmptyStateFixture } from "./report-empty-state-fixtures.ts";

const meta = {
title: "Reports/MonthlyReportContent",
Expand Down Expand Up @@ -34,30 +35,7 @@ const meta = {
"These period averages can show co-movement, but they cannot establish cause and effect.",
],
},
emptyState: {
reportKind: "monthly",
title: "Your monthly report will appear here",
message: "No activity, sleep, or recovery data is available for this report yet.",
minimumObservedDays: 1,
acceptedDataTypes: ["activity", "sleep", "recovery"],
requirement:
"At least 1 observed day of activity, sleep, or recovery data is required to create a monthly report.",
previewTitle: "When ready, your monthly report will include",
previewItems: [
"Training time and activity count",
"Average daily strain",
"Average sleep duration",
"Average resting heart rate",
"Average heart rate variability",
"Month-over-month training and sleep changes",
],
note: "This preview shows report sections only. No personal values or conclusions are estimated.",
},
recovery: {
range: { startDate: "2026-03-01", endDate: "2026-03-24" },
emptyMessage:
"No activity, sleep, or recovery data was found from 2026-03-01 through 2026-03-24.",
},
emptyState: monthlyReportEmptyStateFixture,
},
},
} satisfies Meta<typeof MonthlyReportContent>;
Expand All @@ -74,30 +52,7 @@ export const Empty: Story = {
current: null,
history: [],
decisionSupport: null,
emptyState: {
reportKind: "monthly",
title: "Your monthly report will appear here",
message: "No activity, sleep, or recovery data is available for this report yet.",
minimumObservedDays: 1,
acceptedDataTypes: ["activity", "sleep", "recovery"],
requirement:
"At least 1 observed day of activity, sleep, or recovery data is required to create a monthly report.",
previewTitle: "When ready, your monthly report will include",
previewItems: [
"Training time and activity count",
"Average daily strain",
"Average sleep duration",
"Average resting heart rate",
"Average heart rate variability",
"Month-over-month training and sleep changes",
],
note: "This preview shows report sections only. No personal values or conclusions are estimated.",
},
recovery: {
range: { startDate: "2026-03-01", endDate: "2026-03-24" },
emptyMessage:
"No activity, sleep, or recovery data was found from 2026-03-01 through 2026-03-24.",
},
emptyState: monthlyReportEmptyStateFixture,
},
},
};
29 changes: 2 additions & 27 deletions packages/web/src/components/MonthlyReportContent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { textColors } from "@dofek/scoring/colors";
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { MonthlyReportContent } from "./MonthlyReportContent.tsx";
import { monthlyReportEmptyStateFixture } from "./report-empty-state-fixtures.ts";

describe("MonthlyReportContent", () => {
it("renders current and previous monthly snapshots", () => {
Expand Down Expand Up @@ -41,29 +42,7 @@ describe("MonthlyReportContent", () => {
whatToTryNext: ["Repeat the routine next month."],
confidenceAndMissingData: ["Confidence is limited."],
},
recovery: {
range: { startDate: "2026-07-01", endDate: "2026-07-31" },
emptyMessage: "No data found for this period.",
},
emptyState: {
reportKind: "monthly",
title: "Your monthly report will appear here",
message: "No activity, sleep, or recovery data is available for this report yet.",
minimumObservedDays: 1,
acceptedDataTypes: ["activity", "sleep", "recovery"],
requirement:
"At least 1 observed day of activity, sleep, or recovery data is required to create a monthly report.",
previewTitle: "When ready, your monthly report will include",
previewItems: [
"Training time and activity count",
"Average daily strain",
"Average sleep duration",
"Average resting heart rate",
"Average heart rate variability",
"Month-over-month training and sleep changes",
],
note: "This preview shows report sections only. No personal values or conclusions are estimated.",
},
emptyState: monthlyReportEmptyStateFixture,
}}
/>,
);
Expand All @@ -87,10 +66,6 @@ describe("MonthlyReportContent", () => {
current: null,
history: [],
decisionSupport: null,
recovery: {
range: { startDate: "2026-03-01", endDate: "2026-03-24" },
emptyMessage: "No data found for this period.",
},
emptyState: {
reportKind: "monthly",
title: "Server monthly preview title",
Expand Down
4 changes: 2 additions & 2 deletions packages/web/src/components/MonthlyReportContent.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { formatDurationMinutes, formatHRV, formatMonthYear } from "@dofek/format/format";
import { textColors } from "@dofek/scoring/colors";
import type { MonthlyReportResult, MonthSummary } from "dofek-server/types";
import type { MonthlyReportData, MonthSummary } from "dofek-server/types";
import { EmptyStatePreview } from "./EmptyStatePreview.tsx";
import { ReportDecisionSynthesis } from "./ReportDecisionSynthesis.tsx";

export function MonthlyReportContent({ data }: { data: MonthlyReportResult | undefined }) {
export function MonthlyReportContent({ data }: { data: MonthlyReportData | undefined }) {
if (!data) {
return (
<div className="card p-6">
Expand Down
24 changes: 2 additions & 22 deletions packages/web/src/components/WeeklyReportCard.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { weeklyReportEmptyStateFixture } from "./report-empty-state-fixtures.ts";
import { WeeklyReportCard } from "./WeeklyReportCard";

const meta = {
Expand Down Expand Up @@ -50,23 +51,7 @@ const meta = {
"These period averages can show co-movement, but they cannot establish cause and effect.",
],
},
emptyState: {
reportKind: "weekly",
title: "Your weekly report will appear here",
message: "No activity, sleep, or recovery data is available for this report yet.",
minimumObservedDays: 1,
acceptedDataTypes: ["activity", "sleep", "recovery"],
requirement:
"At least 1 observed day of activity, sleep, or recovery data is required to create a weekly report.",
previewTitle: "When ready, your weekly report will include",
previewItems: ["Training time and activity count", "Average nightly sleep"],
note: "This preview shows report sections only. No personal values or conclusions are estimated.",
},
recovery: {
range: { startDate: "2026-03-30", endDate: "2026-04-05" },
emptyMessage:
"No activity, sleep, or recovery data was found from 2026-03-30 through 2026-04-05.",
},
emptyState: weeklyReportEmptyStateFixture,
},
},
} satisfies Meta<typeof WeeklyReportCard>;
Expand All @@ -90,11 +75,6 @@ export const Empty: Story = {
current: null,
history: [],
decisionSupport: null,
recovery: {
range: { startDate: "2026-03-30", endDate: "2026-04-05" },
emptyMessage:
"No activity, sleep, or recovery data was found from 2026-03-30 through 2026-04-05.",
},
emptyState: {
reportKind: "weekly",
title: "Your weekly report will appear here",
Expand Down
Loading
Loading