Skip to content

Prepare SensorKit usage reports, snapshots and file-backed evidence - #163

Open
PSchmiedmayer wants to merge 10 commits into
sensorkit-scoped-acquisitionfrom
sensorkit-preparation
Open

PSchmiedmayer wants to merge 10 commits into
sensorkit-scoped-acquisitionfrom
sensorkit-preparation

Conversation

@PSchmiedmayer

@PSchmiedmayer PSchmiedmayer commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

♻️ Current situation & Problem

This PR builds on #162.

A study client such as Trove converts SensorKit batches into FHIR and must convert the same batch again after a crash or an interrupted upload, with the same resource identities and content. GroveSensorKitFHIR lacked several pieces for that. Messages-usage and phone-usage reports had only the generic safe representation, which wraps the non-Sendable SensorKit object, and no prepared record with retry evidence. A retry had no way to state the same devices, time zone and conversion instant as the first conversion. Structured native evidence (the JSON of an ECG session or a device-usage report) existed only as one Data value, so a large one sat in memory twice. ECG retry evidence did not cover the start, sampling frequency, lead and guidance that the record states. A client had no list of the streams the converter actually produces, and a receiver had no public way to validate an uploaded recording against its registered format within a limit of its own.

Trove persists a SensorKitBatchSnapshot in its batch receipt, writes ECG sessions and device-usage reports through SensorKitPreparedStructuredFile, derives its collection capabilities from implementedOutput, and validates uploads on its server with validatePayload(_:maximumByteCount:).

⚙️ Release Notes

  • Usage reports: SRMessagesUsageReport.SafeRepresentation and SRPhoneUsageReport.SafeRepresentation are dedicated structs that copy every public field on the callback thread. SensorKitPreparedStructuredRecord(messagesUsage:) and (phoneUsage:) prepare them with retry evidence over every field.

  • Breaking: those two SafeRepresentation types replace the DefaultSensorKitSampleSafeRepresentation typealias, so the wrapped sample property is gone.

  • Batch snapshot: SensorKitBatchSnapshot retains the application, host, recording and source devices, source time zone and conversion instant of a batch's first conversion. The caller persists it before the first conversion and converts every redelivery with the decoded snapshot. The encoding is versioned JSON with sorted keys, bounded by a caller byte limit, at most 128 source devices and 2,048 UTF-8 bytes per string; every failure is a SnapshotError (unsupportedVersion, invalidFacts, capacityExceeded).

    let snapshot = try SensorKitBatchSnapshot(
        application: application, host: host, recordingDevice: watch,
        sourceDevices: devices, sourceTimeZone: .current, conversionInstant: .now
    )
    receipt.facts = try snapshot.encoded(maximumByteCount: maximumFactsBytes)
    // After a restart:
    let facts = try SensorKitBatchSnapshot(encoded: receipt.facts, maximumByteCount: maximumFactsBytes)
  • File-backed evidence: SensorKitPreparedStructuredFile(electrocardiogram:maximumByteCount:) and (deviceUsage:maximumByteCount:) write the native JSON into a RecordingFile one element at a time. The bytes equal the in-memory preparation, so digests match, and a failure discards the file. readRetryEvidenceChunks(_:) streams the retry evidence, and sensorKitRecord(sourceRecordID:title:sidecarPath:admission:) attaches the file at an archive-relative path.

    let prepared = try SensorKitPreparedStructuredFile(electrocardiogram: session, maximumByteCount: limit)
    var hasher = SHA256()
    try prepared.readRetryEvidenceChunks { hasher.update(data: $0) }
    let record = try prepared.sensorKitRecord(
        sourceRecordID: id, title: "ECG", sidecarPath: "recordings/ecg-0.json", admission: admission
    )
  • Behavior change: an ECG session's retryEvidence now ends with its start, sampling frequency, lead and guidance as fixed-width big-endian words, so one digest covers every fact the record states. ECG digests stored before this change no longer match.

  • SensorKitCatalogEntry.implementedOutput returns a SensorKitOutputDefinition (source token, Observation contract and profiles, effective and value shape, recording profiles and formats, required companion profiles) for each stream the converter produces, and nil otherwise. It describes output and grants no permission to collect.

  • RegisteredRecordingFormat.validatePayload(_:maximumByteCount:) validates Data or a RecordingFile against its registered format within a caller limit between 1 and Int32.max; the registry's decode limit still applies, and CSV files are validated in chunks.

  • The preparations take the shared RecordingPayloadAdmission from Stage recordings in owned files and read them in bounded chunks #159. Package-internal RecordingFile.stage(maximumByteCount:producing:) builds a file from a synchronous producer.

📚 Documentation

GroveSensorKitFHIR.md describes the usage reports, SensorKitPreparedStructuredFile, the extended ECG retry evidence and persisting a SensorKitBatchSnapshot, and lists the new types in its topics. The new types, SnapshotError and both validatePayload overloads have symbol documentation.

✅ Testing

  • SensorKitUsagePreparationTests (new): usage reports keep every field, and the phone call duration enters the record and the retry evidence.
  • SensorKitBatchSnapshotTests (new): device facts and a fractional instant round-trip; byte limits, other versions, unknown time zones, invalid facts, malformed bytes and too many source devices are refused with the right error.
  • SensorKitECGRetryEvidenceTests (new): each of the four ECG facts changes the evidence, and the file preparation matches the in-memory bytes and evidence.
  • SensorKitStructuredFileTests (new): the device-usage file keeps every nested field and the in-memory member order.
  • SensorKitOutputDefinitionTests (new): deferred entries have no output, and the on-wrist definition matches the emitted Observations.
  • RegisteredRecordingFileValidationTests (new): the caller limit is inclusive and checked first, the decode limit still holds, and file and in-memory payloads follow the same grammar.
  • RecordingFileProducerTests (new, GroveFHIRTests): RecordingFile.stage keeps every byte across large appends, refuses an empty producer and discards the file on failure.

Code of Conduct & Contributing Guidelines

By creating and submitting this pull request, you agree to follow our Code of Conduct and Contributing Guidelines:

@PSchmiedmayer
PSchmiedmayer added this pull request to stack #166 November 18, 2026 16:52
@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d243d49d-9566-4ca5-a3e2-66c8ca6ef244

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Messages-usage and phone-usage reports gain safe representations that
copy every public field, and SensorKitPreparedStructuredRecord prepares
them like the other structured samples. SensorKitBatchSnapshot retains
the application, host and source-device facts, time zone and conversion
instant of a batch's first conversion in a bounded, versioned encoding,
so a retry states the same facts. SensorKitPreparedStructuredFile writes
the native evidence of a device-usage report or an ECG session directly
into a recording file, and SensorKitOutputDefinition describes the
outputs a cataloged converter implements.

An ECG session's retry evidence now ends with the start, frequency, lead
and guidance its record states, so one digest covers every fact.
RegisteredRecordingFormat validates a payload or file within a caller's
byte limit.
`SensorKitBatchSnapshot` now throws only `SnapshotError`, and decoding maps
malformed bytes and invalid application or host facts to `invalidFacts`.
Both registered payload validators accept a caller limit between 1 and
`Int32.max`, the usage report representations document their fields, and the
structured file's `sensorKitRecord` states that the generated JSON is not
parsed again, which the validation override now guarantees.
Keep the shared caller-limit check of the registered payload validators out
of the instance methods, as the type order rule requires.
`SensorKitBatchSnapshot(encoded:maximumByteCount:)` decodes the version
first, so another version reports `unsupportedVersion` even when its shape
differs, and `encoded(maximumByteCount:)` throws only `SnapshotError`.
`SensorKitBatchSnapshot.init` throws `capacityExceeded` for more than 128
source devices, as decoding does, instead of `invalidFacts`. The device usage
file test adds category names whose order depends on case and digit handling,
which pins the member order of the file to that of the in-memory encoding.
The file and Data validation tests of a registered payload now expect the reader error that invalidTabularPayload carries: the invalid timestamp and the invalid value of their rows.
@PSchmiedmayer
PSchmiedmayer marked this pull request as ready for review December 6, 2026 06:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant