diff --git a/Sources/GroveFHIRContract/RecordingFile.swift b/Sources/GroveFHIRContract/RecordingFile.swift index c12dd5c54..a3a93c5db 100644 --- a/Sources/GroveFHIRContract/RecordingFile.swift +++ b/Sources/GroveFHIRContract/RecordingFile.swift @@ -131,6 +131,33 @@ public struct RecordingFile: Sendable { return try builder.finish() } + /// Stages the bytes `body` produces synchronously, written in chunks of at most 64 KiB. + /// + /// An error `body` throws or an exceeded byte limit discards the file instead of returning a partial snapshot, and + /// `append` refuses every further byte after its first failure. + package static func stage( + maximumByteCount: Int, + producing body: (_ append: (Data) throws -> Void) throws -> Void + ) throws -> Self { + var builder = try Builder(maximumByteCount: maximumByteCount) + var failure: (any Error)? + try body { bytes in + if let failure { + throw failure + } + do { + try builder.append(bytes) + } catch { + failure = error + throw error + } + } + if let failure { + throw failure + } + return try builder.finish() + } + /// Reads the bytes in chunks of at most 64 KiB, independently of any other reader. /// /// Only the current chunk is retained; `consume` controls whether it retains delivered chunks. An error or diff --git a/Sources/GroveSensorKit/Sample Types/Other+Unsafe.swift b/Sources/GroveSensorKit/Sample Types/Other+Unsafe.swift index 507ad8304..024f06834 100644 --- a/Sources/GroveSensorKit/Sample Types/Other+Unsafe.swift +++ b/Sources/GroveSensorKit/Sample Types/Other+Unsafe.swift @@ -12,16 +12,6 @@ // We use the @preconcurrency import to make it work anyway, for the time being. -extension SRMessagesUsageReport: SensorKitSampleProtocol { - public typealias SafeRepresentation = DefaultSensorKitSampleSafeRepresentation -} - - -extension SRPhoneUsageReport: SensorKitSampleProtocol { - public typealias SafeRepresentation = DefaultSensorKitSampleSafeRepresentation -} - - extension SRKeyboardMetrics: SensorKitSampleProtocol { public typealias SafeRepresentation = DefaultSensorKitSampleSafeRepresentation } diff --git a/Sources/GroveSensorKit/Sample Types/UsageReports.swift b/Sources/GroveSensorKit/Sample Types/UsageReports.swift new file mode 100644 index 000000000..a638b18e8 --- /dev/null +++ b/Sources/GroveSensorKit/Sample Types/UsageReports.swift @@ -0,0 +1,105 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +public import Foundation +public import SensorKit + + +extension SRMessagesUsageReport: SensorKitSampleProtocol { + /// Every public field of a messages-usage report, copied on the SensorKit callback thread. + public struct SafeRepresentation: SensorKitSampleSafeRepresentation { + /// The time SensorKit states for the report. + public let timestamp: Date + /// The length of the reporting interval, in seconds. + public let duration: TimeInterval + /// The number of messages the person sent during the interval. + public let totalOutgoingMessages: Int + /// The number of messages the person received during the interval. + public let totalIncomingMessages: Int + /// The number of distinct contacts the person exchanged messages with during the interval. + public let totalUniqueContacts: Int + /// The report's ``timestamp``, as an empty range. + public var timeRange: Range { timestamp.. + ) -> [SafeRepresentation] { + samples.map { timestamp, report in + SafeRepresentation( + timestamp: timestamp, + duration: report.duration, + totalOutgoingMessages: report.totalOutgoingMessages, + totalIncomingMessages: report.totalIncomingMessages, + totalUniqueContacts: report.totalUniqueContacts + ) + } + } +} + + +extension SRPhoneUsageReport: SensorKitSampleProtocol { + /// Every public field of a phone-usage report, copied on the SensorKit callback thread. + public struct SafeRepresentation: SensorKitSampleSafeRepresentation { + /// The time SensorKit states for the report. + public let timestamp: Date + /// The length of the reporting interval, in seconds. + public let duration: TimeInterval + /// The number of calls the person placed during the interval. + public let totalOutgoingCalls: Int + /// The number of calls the person received during the interval. + public let totalIncomingCalls: Int + /// The number of distinct contacts the person called or was called by during the interval. + public let totalUniqueContacts: Int + /// The total length of the person's calls during the interval, in seconds. + public let totalPhoneCallDuration: TimeInterval + /// The report's ``timestamp``, as an empty range. + public var timeRange: Range { timestamp.. + ) -> [SafeRepresentation] { + samples.map { timestamp, report in + SafeRepresentation( + timestamp: timestamp, + duration: report.duration, + totalOutgoingCalls: report.totalOutgoingCalls, + totalIncomingCalls: report.totalIncomingCalls, + totalUniqueContacts: report.totalUniqueContacts, + totalPhoneCallDuration: report.totalPhoneCallDuration + ) + } + } +} diff --git a/Sources/GroveSensorKitFHIR/GroveSensorKitFHIR.docc/GroveSensorKitFHIR.md b/Sources/GroveSensorKitFHIR/GroveSensorKitFHIR.docc/GroveSensorKitFHIR.md index 402533f17..a117e37df 100644 --- a/Sources/GroveSensorKitFHIR/GroveSensorKitFHIR.docc/GroveSensorKitFHIR.md +++ b/Sources/GroveSensorKitFHIR/GroveSensorKitFHIR.docc/GroveSensorKitFHIR.md @@ -187,9 +187,9 @@ The conformance lane in `Scripts/validate-fhir-conformance.sh` proves this adapt One batch becomes records in one of two ways: - **One record per batch.** A tabular stream (accelerometer, ambient light, ambient pressure, heart rate, pedometer) becomes one ``SensorKitTabularRecording`` from all its samples, and a photoplethysmogram batch one ``SensorKitPreparedPPGRecording`` from `SensorKitPPGRecording(samples:).prepared()`. A rotation-rate batch becomes one ``SensorKitRotationRateRecord`` from its samples, which exposes no `retryEvidence`, so digest the samples you pass. The record's ordinal is 0. -- **One record per sample.** A visit, an on-wrist event, a device-usage report and an ECG session each become one ``SensorKitPreparedStructuredRecord``, and a wrist-temperature session one ``SensorKitTabularRecording``; each takes the zero-based position of its sample in the batch as its ordinal. +- **One record per sample.** A visit, an on-wrist event, a messages-usage or phone-usage report, a device-usage report and an ECG session each become one ``SensorKitPreparedStructuredRecord``, and a wrist-temperature session one ``SensorKitTabularRecording``; each takes the zero-based position of its sample in the batch as its ordinal. ``SensorKitPreparedStructuredFile`` writes the native evidence of a device-usage report or an ECG session directly into a recording file. -The other record cases, such as messages or phone usage, keyboard metrics, sleep sessions and a raw recording, take values you assemble; digest exactly what you pass. +The other record cases, such as keyboard metrics, sleep sessions and a raw recording, take values you assemble; digest exactly what you pass. ``SensorKitSourceRecordID/derived(acquisitionBatch:sourceToken:deviceProductType:recordOrdinal:)`` names each record from the batch's coordinate, the stream's catalog token (`SensorKitCatalog.sourceToken(for:)`), the batch's device product type and that ordinal, never from its content. A fresh query anchor starts a random stream partition of its own, which the coordinate states, so a reinstall names no record of an earlier installation although its cursor restarts at the same place. @@ -197,7 +197,9 @@ A fresh query anchor starts a random stream partition of its own, which the coor Your digest keeps one name meaning one content. Each preparation exposes `retryEvidence`, the bytes Grove derives the record from. Digest them, persist the digest beside the record's id, and on a redelivery of the batch fail the batch when a digest differs: SensorKit may change records inside an unacknowledged boundary, and only this digest stops an id from naming other content. -An ECG session's evidence covers its identifier, states and waveform; its start, sampling frequency, lead and guidance enter its record too, so digest them beside it. +An ECG session's evidence covers its identifier, states and waveform, followed by its start, sampling frequency, lead and guidance, which its record states too. + +Persist a ``SensorKitBatchSnapshot`` of the application, host and source devices, the time zone and the conversion instant before the first conversion of a batch, and convert a redelivery with the decoded snapshot, so the retry states the same facts. Failing a batch means throwing before `acknowledge()`: the anchor stays, and the batch is reissued after a restart under the same coordinate and ids. The reissued batch holds the same samples while SensorKit returns the same fetch results up to the batch's boundary; data recorded after the batch does not change it. An ECG batch whose last session was delivered without its end state also depends on what followed that session, as the ECG Sessions section of the GroveSensorKit documentation describes. @@ -365,7 +367,9 @@ On iOS, typed initializers map Grove's already-fetched safe representations into - ``SensorKitTabularRecording/File`` - ``SensorKitPreparedPPGRecording`` - ``SensorKitPreparedStructuredRecord`` +- ``SensorKitPreparedStructuredFile`` - ``SensorKitRecordingLocation`` +- ``SensorKitBatchSnapshot`` - ``SensorKitSummaryError`` ### Recording payloads @@ -378,3 +382,4 @@ On iOS, typed initializers map Grove's already-fetched safe representations into - ``SensorKitCatalog`` - ``SensorKitCatalogEntry`` +- ``SensorKitOutputDefinition`` diff --git a/Sources/GroveSensorKitFHIR/RegisteredRecordingFormat+PayloadValidation.swift b/Sources/GroveSensorKitFHIR/RegisteredRecordingFormat+PayloadValidation.swift index 442b28d54..2eb81d276 100644 --- a/Sources/GroveSensorKitFHIR/RegisteredRecordingFormat+PayloadValidation.swift +++ b/Sources/GroveSensorKitFHIR/RegisteredRecordingFormat+PayloadValidation.swift @@ -9,7 +9,7 @@ // This validator intentionally keeps the closed payload grammar in one exhaustive switch. // swiftlint:disable cyclomatic_complexity function_body_length -import Foundation +public import Foundation public import GroveFHIRContract import ModelsR4 @@ -48,6 +48,33 @@ extension RegisteredRecordingFormat { csvColumns == nil && self != .cdaDocument && self != .sourceFile } + /// Validates a recording file against this format's grammar within the caller's byte limit. + /// + /// A CSV is validated in bounded chunks, retaining one bounded row. JSON, FHIR and PPG payloads are decoded as a + /// whole and stay within ``maximumDecodedPayloadByteCount`` as well. The caller separately verifies the source + /// digests, the media type, the consent and the clinical graph. + /// + /// - Parameters: + /// - file: The recording file. + /// - maximumByteCount: The most bytes the file may hold, between 1 and `Int32.max`. + /// - Throws: A ``RegisteredRecordingPayloadError``, a `RecordingFile.FileError` or `CancellationError`. + public func validatePayload(_ file: RecordingFile, maximumByteCount: Int) throws { + try Self.validateByteCount(file.byteCount, maximumByteCount: maximumByteCount) + try validatePayload(file) + } + + /// Validates bytes already in memory against this format's grammar within the caller's byte limit. + /// + /// Payloads that are decoded as a whole stay within ``maximumDecodedPayloadByteCount`` as well. + /// + /// - Parameters: + /// - bytes: The payload. + /// - maximumByteCount: The most bytes the payload may hold, between 1 and `Int32.max`. + public func validatePayload(_ bytes: Data, maximumByteCount: Int) throws(RegisteredRecordingPayloadError) { + try Self.validateByteCount(bytes.count, maximumByteCount: maximumByteCount) + try validatePayload(bytes) + } + func validatePayloadSize(_ byteCount: Int) throws(RegisteredRecordingPayloadError) { guard !requiresWholePayloadDecoding || byteCount <= Self.maximumDecodedPayloadByteCount else { throw .payloadLimitExceeded } } @@ -165,3 +192,13 @@ extension RegisteredRecordingFormat { } } } + + +extension RegisteredRecordingFormat { + /// Both entry points admit at most the caller's limit, which an attachment's `Int32` size bounds. + fileprivate static func validateByteCount(_ byteCount: Int, maximumByteCount: Int) throws(RegisteredRecordingPayloadError) { + guard (1...Int(Int32.max)).contains(maximumByteCount), byteCount <= maximumByteCount else { + throw .payloadLimitExceeded + } + } +} diff --git a/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot+RecordingFacts.swift b/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot+RecordingFacts.swift new file mode 100644 index 000000000..0cf840795 --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot+RecordingFacts.swift @@ -0,0 +1,77 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import GroveFHIRContract + + +extension SensorKitBatchSnapshot { + struct RecordingFacts: Codable { + let stableUnitToken: String? + let tokenScope: String? + let name: String? + let manufacturer: String? + let model: String? + let productType: String? + let systemName: String? + let systemVersion: String? + let hardwareVersion: String? + let firmwareVersion: String? + let softwareVersion: String? + let localIdentifier: String? + let udiDeviceIdentifier: String? + let udiProductionIdentifier: String? + let serialNumber: String? + + var strings: [String] { + [ + stableUnitToken, tokenScope, name, manufacturer, + model, productType, systemName, systemVersion, + hardwareVersion, firmwareVersion, softwareVersion, localIdentifier, + udiDeviceIdentifier, udiProductionIdentifier, serialNumber + ].compactMap { $0 } + } + + var value: RecordingDevice { + var device = RecordingDevice() + device.stableUnitToken = stableUnitToken + device.tokenScope = tokenScope + device.name = name + device.manufacturer = manufacturer + device.model = model + device.productType = productType + device.systemName = systemName + device.systemVersion = systemVersion + device.hardwareVersion = hardwareVersion + device.firmwareVersion = firmwareVersion + device.softwareVersion = softwareVersion + device.localIdentifier = localIdentifier + device.udiDeviceIdentifier = udiDeviceIdentifier + device.udiProductionIdentifier = udiProductionIdentifier + device.serialNumber = serialNumber + return device + } + + init(_ device: RecordingDevice) { + stableUnitToken = device.stableUnitToken + tokenScope = device.tokenScope + name = device.name + manufacturer = device.manufacturer + model = device.model + productType = device.productType + systemName = device.systemName + systemVersion = device.systemVersion + hardwareVersion = device.hardwareVersion + firmwareVersion = device.firmwareVersion + softwareVersion = device.softwareVersion + localIdentifier = device.localIdentifier + udiDeviceIdentifier = device.udiDeviceIdentifier + udiProductionIdentifier = device.udiProductionIdentifier + serialNumber = device.serialNumber + } + } +} diff --git a/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot+Representation.swift b/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot+Representation.swift new file mode 100644 index 000000000..2e0e0a50a --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot+Representation.swift @@ -0,0 +1,97 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation +import GroveFHIRContract + + +extension SensorKitBatchSnapshot { + struct Representation: Codable { + let version: Int + let application: ApplicationFacts + let host: HostFacts + let recording: RecordingFacts? + let sources: [RecordingFacts] + let sourcesSuppliedEverySample: Bool + let timeZone: String + let instant: Date + + func validateStringBounds() throws(SnapshotError) { + guard sources.count <= 128 else { throw .capacityExceeded } + let strings = application.strings + host.strings + (recording?.strings ?? []) + sources.flatMap(\.strings) + [timeZone] + guard strings.allSatisfy({ $0.utf8.count <= 2048 }) else { throw .capacityExceeded } + } + } + + struct ApplicationFacts: Codable { + let name: String + let bundleIdentifier: String + let version: String + let build: String? + var strings: [String] { [name, bundleIdentifier, version] + [build].compactMap { $0 } } + + init(_ device: ApplicationDevice) { + name = device.name + bundleIdentifier = device.bundleIdentifier + version = device.version + build = device.build + } + + func value() throws(ApplicationDevice.ValidationError) -> ApplicationDevice { + try ApplicationDevice(name: name, bundleIdentifier: bundleIdentifier, version: version, build: build) + } + } + + struct HostFacts: Codable { + let operatingSystemName: String? + let operatingSystemVersion: String + let operatingSystemBuild: String? + let productType: String? + let model: String? + let name: String? + let manufacturer: String? + var strings: [String] { + [operatingSystemName, operatingSystemVersion, operatingSystemBuild, productType, model, name, manufacturer].compactMap { $0 } + } + + init(_ device: HostDevice) { + operatingSystemName = device.operatingSystemName + operatingSystemVersion = device.operatingSystemVersion + operatingSystemBuild = device.operatingSystemBuild + productType = device.productType + model = device.model + name = device.name + manufacturer = device.manufacturer + } + + func value() throws(HostDevice.ValidationError) -> HostDevice { + try HostDevice( + operatingSystemName: operatingSystemName, + operatingSystemVersion: operatingSystemVersion, + operatingSystemBuild: operatingSystemBuild, + productType: productType, + model: model, + name: name, + manufacturer: manufacturer + ) + } + } + + var representation: Representation { + Representation( + version: 1, + application: ApplicationFacts(application), + host: HostFacts(host), + recording: recordingDevice.map(RecordingFacts.init), + sources: sourceDevices.map(RecordingFacts.init), + sourcesSuppliedEverySample: sourceDevicesSuppliedEverySample, + timeZone: sourceTimeZone.identifier, + instant: conversionInstant + ) + } +} diff --git a/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot.swift b/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot.swift new file mode 100644 index 000000000..5519c6ac3 --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitBatchSnapshot.swift @@ -0,0 +1,141 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +public import Foundation +public import GroveFHIRContract + + +/// The application, host and source-device facts first used to convert one SensorKit batch. +/// +/// Persist the encoded snapshot before the first conversion and convert a retry with the decoded snapshot, so both +/// state the same facts. Account authority, study policy and identity secrets remain the caller's responsibility. +public struct SensorKitBatchSnapshot: Hashable, Sendable { + /// Why a snapshot could not be created, decoded or encoded. + public enum SnapshotError: Error, Equatable, Sendable { + /// The encoded snapshot has a version this release doesn't read. + case unsupportedVersion + /// A fact is invalid, such as an unknown time zone or a conversion instant outside the FHIR range. + case invalidFacts + /// The snapshot exceeds a byte limit, more than 128 source devices or 2,048 UTF-8 bytes in one string. + case capacityExceeded + } + + /// The application that converts the batch. + public let application: ApplicationDevice + /// The device that runs the application. + public let host: HostDevice + /// The device that recorded the batch, if known. + public let recordingDevice: RecordingDevice? + /// The source devices SensorKit named for the batch's samples. + public let sourceDevices: [RecordingDevice] + /// Whether SensorKit named a source device for every sample. + public let sourceDevicesSuppliedEverySample: Bool + /// The time zone of the source. + public let sourceTimeZone: TimeZone + /// The instant of the first conversion. + public let conversionInstant: Date + + /// Creates a snapshot of the facts of a batch's first conversion. + /// + /// - Throws: ``SnapshotError/capacityExceeded`` for more than 128 source devices or a string of more than 2,048 + /// UTF-8 bytes, and ``SnapshotError/invalidFacts`` for an unknown time zone, a conversion instant outside the + /// FHIR range, or source devices said to supply every sample when there are none. + public init( + application: ApplicationDevice, + host: HostDevice, + recordingDevice: RecordingDevice?, + sourceDevices: [RecordingDevice] = [], + sourceDevicesSuppliedEverySample: Bool = false, + sourceTimeZone: TimeZone, + conversionInstant: Date + ) throws(SnapshotError) { + guard sourceDevices.count <= 128 else { + throw .capacityExceeded + } + guard (0...253_402_300_799).contains(conversionInstant.timeIntervalSince1970), + !sourceDevicesSuppliedEverySample || !sourceDevices.isEmpty, + let zone = TimeZone(identifier: sourceTimeZone.identifier) else { + throw .invalidFacts + } + self.application = application + self.host = host + self.recordingDevice = recordingDevice + self.sourceDevices = sourceDevices + self.sourceDevicesSuppliedEverySample = sourceDevicesSuppliedEverySample + self.sourceTimeZone = zone + self.conversionInstant = conversionInstant + try representation.validateStringBounds() + } + + /// Decodes a snapshot that ``encoded(maximumByteCount:)`` encoded. + /// + /// The byte limit is checked before decoding, and the application and host are validated as their initializers + /// validate them. + /// + /// - Parameters: + /// - data: The encoded snapshot. + /// - maximumByteCount: The most bytes the encoded snapshot may hold. + /// - Throws: ``SnapshotError/capacityExceeded`` for an empty or oversized snapshot or string, + /// ``SnapshotError/unsupportedVersion`` for another version, and ``SnapshotError/invalidFacts`` for bytes that + /// don't decode or facts that are invalid. + public init(encoded data: Data, maximumByteCount: Int) throws(SnapshotError) { + guard maximumByteCount > 0, !data.isEmpty, data.count <= maximumByteCount else { + throw .capacityExceeded + } + // The version decides the shape, so it is read first: another version need not decode as this one. + struct Version: Decodable { + let version: Int + } + let value: Representation + do { + guard try JSONDecoder().decode(Version.self, from: data).version == 1 else { throw SnapshotError.unsupportedVersion } + value = try JSONDecoder().decode(Representation.self, from: data) + } catch SnapshotError.unsupportedVersion { + throw .unsupportedVersion + } catch { + throw .invalidFacts + } + try value.validateStringBounds() + guard let zone = TimeZone(identifier: value.timeZone) else { throw .invalidFacts } + let application: ApplicationDevice + let host: HostDevice + do { + application = try value.application.value() + host = try value.host.value() + } catch { + throw .invalidFacts + } + try self.init( + application: application, + host: host, + recordingDevice: value.recording?.value, + sourceDevices: value.sources.map(\.value), + sourceDevicesSuppliedEverySample: value.sourcesSuppliedEverySample, + sourceTimeZone: zone, + conversionInstant: value.instant + ) + } + + /// Encodes the exact retained facts, without any device lookup or current-time fallback. + /// + /// - Throws: ``SnapshotError/capacityExceeded`` when the encoding exceeds `maximumByteCount`, and + /// ``SnapshotError/invalidFacts`` if the facts can't be encoded. + public func encoded(maximumByteCount: Int) throws(SnapshotError) -> Data { + guard maximumByteCount > 0 else { throw .capacityExceeded } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + let data: Data + do { + data = try encoder.encode(representation) + } catch { + throw .invalidFacts + } + guard data.count <= maximumByteCount else { throw .capacityExceeded } + return data + } +} diff --git a/Sources/GroveSensorKitFHIR/SensorKitECGRetryEvidence.swift b/Sources/GroveSensorKitFHIR/SensorKitECGRetryEvidence.swift new file mode 100644 index 000000000..a763958e2 --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitECGRetryEvidence.swift @@ -0,0 +1,30 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) +import Foundation +import GroveSensorKit + + +@available(iOS 17.4, *) +extension SensorKitECGSession { + /// Exact fixed-width facts absent from the established native JSON, in the client retry framing order. + var groveRetryEvidenceSupplement: Data { + var supplement = Data() + for word in [ + startDate.timeIntervalSince1970.bitPattern, + frequency.converted(to: .hertz).value.bitPattern, + UInt64(bitPattern: Int64(lead.rawValue)), + UInt64(bitPattern: Int64(guidance.rawValue)) + ] { + withUnsafeBytes(of: word.bigEndian) { supplement.append(contentsOf: $0) } + } + return supplement + } +} +#endif diff --git a/Sources/GroveSensorKitFHIR/SensorKitJSONFileEncoding.swift b/Sources/GroveSensorKitFHIR/SensorKitJSONFileEncoding.swift new file mode 100644 index 000000000..2d66468c2 --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitJSONFileEncoding.swift @@ -0,0 +1,58 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) + +import Foundation + + +/// Incremental JSON punctuation with Foundation's established primitive encoding. +struct SensorKitJSONFileEncoding { + private let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + encoder.dateEncodingStrategy = .secondsSince1970 + return encoder + }() + + func value(_ value: some Encodable, append: (Data) throws -> Void) throws { + try append(encoder.encode(value)) + } + + /// Appends an object whose members are `keys`, sorted by name, with each value `value` appends. + func object( + _ keys: [Key], + name: (Key) -> String, + append: (Data) throws -> Void, + value: (Key) throws -> Void + ) throws { + try append(Data("{".utf8)) + for (index, key) in keys.sorted(by: { name($0) < name($1) }).enumerated() { + if index > 0 { + try append(Data(",".utf8)) + } + try self.value(name(key), append: append) + try append(Data(":".utf8)) + try value(key) + } + try append(Data("}".utf8)) + } + + func array(_ values: Values, append: (Data) throws -> Void, element: (Values.Element) throws -> Void) throws { + try append(Data("[".utf8)) + for (index, value) in values.enumerated() { + if index > 0 { + try append(Data(",".utf8)) + } + try element(value) + } + try append(Data("]".utf8)) + } +} + +#endif diff --git a/Sources/GroveSensorKitFHIR/SensorKitOutputDefinition.swift b/Sources/GroveSensorKitFHIR/SensorKitOutputDefinition.swift new file mode 100644 index 000000000..ce2a57744 --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitOutputDefinition.swift @@ -0,0 +1,124 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +public import GroveFHIRContract + + +/// Portable output-selection facts for a cataloged SensorKit converter. +/// These facts describe the current producer's resource shapes, not permission to collect, +/// operating-system availability, or full validation of every field against the guide. +public struct SensorKitOutputDefinition: Sendable { + /// The effective-time datatypes an Observation states. + public enum Effective: Sendable, Equatable { + /// A whole interval. + case period + /// Either a point in time or an interval. + case dateTimeOrPeriod + } + + /// The value shape of an Observation. + public enum ValueShape: Sendable, Equatable { + /// A top-level Quantity. + case quantity + /// A top-level CodeableConcept. + case coded + /// Components without a top-level value. + case components + /// A top-level SampledData. + case sampledData + /// A component whose value is SampledData. + case sampledDataComponent + } + + /// The facts of a converter's structured Observation. + public struct Observation: Sendable { + /// The structured contract of the converter. + public let contract: SensorKitStructuredContract + /// All simultaneous profile claims, read directly from the generated catalog row. + public let profiles: [String] + /// The effective-time datatypes the Observation states. + public let effective: Effective + /// The value shape of the Observation. + public let valueShape: ValueShape + /// Whether conversion requires an accompanying exact native recording. + public let requiresRecording: Bool + + /// The sole SensorKit-specific claim, distinct from additional shared sensor profile claims. + public var primaryProfile: String? { + let candidates = profiles.filter { $0.hasPrefix(SensorKitContract.canonicalRoot + "/StructureDefinition/") } + return candidates.count == 1 ? candidates.first : nil + } + } + + /// The source's catalog token. + public let sourceToken: String + /// The source-type code the outputs state. + public let sourceTypeCode: String + /// The converter's structured Observation, when the source has one. + public let observation: Observation? + /// Every simultaneous profile on an emitted recording DocumentReference. + public let recordingProfiles: [String] + /// Registered native formats admitted by the source; this is not arbitrary opaque JSON admission. + public let recordingFormats: [RegisteredRecordingFormat] + /// Profiles required for complete source custody; this does not grant any study access to those outputs. + public let requiredCompanionProfiles: [String] + + init?(_ entry: SensorKitCatalogEntry) { + sourceToken = entry.sourceToken + sourceTypeCode = entry.sourceTypeCode + recordingProfiles = entry.rawProfiles + recordingFormats = entry.rawFormats + observation = entry.structuredContract.map { contract in + Observation( + contract: contract, + profiles: entry.structuredProfiles, + effective: contract == .onWrist ? .dateTimeOrPeriod : .period, + valueShape: Self.valueShape(contract), + requiresRecording: Self.requiresRecording(contract) + ) + } + if observation?.requiresRecording == true { + guard entry.rawProfiles.contains(SensorKitContract.recordingDocumentProfile) else { + return nil + } + requiredCompanionProfiles = [SensorKitContract.recordingDocumentProfile] + } else { + requiredCompanionProfiles = [] + } + } + + private static func valueShape(_ contract: SensorKitStructuredContract) -> ValueShape { + switch contract { + case .sampledData: .sampledData + case .electrocardiogram: .sampledDataComponent + case .onWrist: .coded + case .deviceUsage, .phoneUsage, .keyboardMetrics, .sleepSession: .quantity + case .visit, .messagesUsage, .accelerometer, .ppg, .wristTemperature: .components + } + } + + private static func requiresRecording(_ contract: SensorKitStructuredContract) -> Bool { + switch contract { + case .electrocardiogram, .deviceUsage, .keyboardMetrics, .accelerometer, .ppg, .wristTemperature: true + case .sampledData, .onWrist, .visit, .messagesUsage, .phoneUsage, .sleepSession: false + } + } +} + + +extension SensorKitCatalogEntry { + /// Current converter output shapes, distinct from the guide's inventory/status label. + /// A missing descriptor leaves deferred or unadmitted streams unavailable. + public var implementedOutput: SensorKitOutputDefinition? { + guard status != .deferred, status != .intentionallyUnsupported, + structuredContract != nil || !rawFormats.isEmpty else { + return nil + } + return SensorKitOutputDefinition(self) + } +} diff --git a/Sources/GroveSensorKitFHIR/SensorKitPreparedStructuredFile+DeviceUsage.swift b/Sources/GroveSensorKitFHIR/SensorKitPreparedStructuredFile+DeviceUsage.swift new file mode 100644 index 000000000..0c71e327b --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitPreparedStructuredFile+DeviceUsage.swift @@ -0,0 +1,88 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) +import Foundation +import GroveFHIRContract +public import GroveSensorKit +public import SensorKit + + +extension SensorKitPreparedStructuredFile { + /// Streams individual applications, notifications, web entries and text-input sessions in source order. + /// The resulting native JSON and clinical summary preserve the complete public report. + @available(iOS 18, *) + public init(deviceUsage report: SRDeviceUsageReport.SafeRepresentation, maximumByteCount: Int) throws { + let writer = SensorKitJSONFileEncoding() + let file = try RecordingFile.stage( + maximumByteCount: min(maximumByteCount, RegisteredRecordingFormat.maximumDecodedPayloadByteCount) + ) { append in + try writer.object(DeviceUsageEvidence.CodingKeys.allCases, name: \.rawValue, append: append) { key in + switch key { + case .timestamp: try writer.value(report.timestamp, append: append) + case .duration: try writer.value(report.duration, append: append) + case .totalScreenWakes: try writer.value(report.totalScreenWakes, append: append) + case .totalUnlocks: try writer.value(report.totalUnlocks, append: append) + case .totalUnlockDuration: try writer.value(report.totalUnlockDuration, append: append) + case .version: try writer.value(report.version, append: append) + case .appUsageByCategory: + try writer.categoryValues(report.appUsageByCategory, append: append) { try writer.applicationUsage($0, append: append) } + case .notificationUsageByCategory: + try writer.categoryValues(report.notificationUsageByCategory, append: append) { + try writer.value(DeviceUsageEvidence.NotificationUsage( + bundleIdentifier: $0.bundleIdentifier, eventRawValue: $0.event.rawValue + ), append: append) + } + case .webUsageByCategory: + try writer.categoryValues(report.webUsageByCategory, append: append) { + try writer.value(DeviceUsageEvidence.WebUsage(totalUsageTime: $0.totalUsageTime), append: append) + } + } + } + } + self.init(file: file) { sourceID, native in + .deviceUsage(SensorKitDeviceUsageRecord(sourceRecordID: sourceID, report: report, nativeRecording: native)) + } + } +} + + +@available(iOS 18, *) +extension SensorKitJSONFileEncoding { + fileprivate func categoryValues( + _ categories: [SRDeviceUsageReport.CategoryKey: [Value]], append: (Data) throws -> Void, element: (Value) throws -> Void + ) throws { + let values = Dictionary(uniqueKeysWithValues: categories.map { ($0.key.rawValue, $0.value) }) + try object(Array(values.keys), name: { $0 }, append: append) { key in + try array(values[key, default: []], append: append, element: element) + } + } + + fileprivate func applicationUsage(_ usage: SRDeviceUsageReport.SafeRepresentation.AppUsage, append: (Data) throws -> Void) throws { + let keys = DeviceUsageEvidence.ApplicationUsage.CodingKeys.allCases.filter { $0 != .bundleIdentifier || usage.bundleIdentifier != nil } + try object(keys, name: \.rawValue, append: append) { key in + switch key { + case .bundleIdentifier: try value(usage.bundleIdentifier, append: append) + case .reportApplicationIdentifier: try value(usage.reportApplicationIdentifier, append: append) + case .relativeStartTime: try value(usage.relativeStartTime, append: append) + case .usageTime: try value(usage.usageTime, append: append) + case .supplementalCategories: + try array(usage.supplementalCategories.sorted { $0.identifier < $1.identifier }, append: append) { + try value(DeviceUsageEvidence.ApplicationUsage.SupplementalCategory(identifier: $0.identifier), append: append) + } + case .textInputSessions: + try array(usage.textInputSessions, append: append) { + try value(DeviceUsageEvidence.ApplicationUsage.TextInputSession( + duration: $0.duration, sessionTypeRawValue: $0.sessionType.rawValue, identifier: $0.identifier + ), append: append) + } + } + } + } +} +#endif diff --git a/Sources/GroveSensorKitFHIR/SensorKitPreparedStructuredFile.swift b/Sources/GroveSensorKitFHIR/SensorKitPreparedStructuredFile.swift new file mode 100644 index 000000000..a4637ac54 --- /dev/null +++ b/Sources/GroveSensorKitFHIR/SensorKitPreparedStructuredFile.swift @@ -0,0 +1,120 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) + +public import Foundation +public import GroveFHIRContract +public import GroveSensorKit +import SensorKit + + +/// File-backed native evidence with the same bytes and retry facts as the structured Data preparation. +/// The native SDK sample remains caller-owned; this avoids a second complete JSON representation in memory. +public struct SensorKitPreparedStructuredFile: Sendable { + private enum ECGKey: String, CaseIterable { + case batches + case sessionIdentifier + case sessionStates + } + + private enum ECGBatchKey: String, CaseIterable { + case offsetSeconds + case samples + } + + private struct ECGSampleEvidence: Encodable { + let flags: UInt + let microvolts: Double + } + + /// The native recording. + public let file: RecordingFile + private let retryEvidenceSupplement: Data + private let makeRecord: @Sendable (SensorKitSourceRecordID, SensorKitNativeRecording) throws -> SensorKitRecord + + init( + file: RecordingFile, + retryEvidenceSupplement: Data = Data(), + makeRecord: @escaping @Sendable (SensorKitSourceRecordID, SensorKitNativeRecording) throws -> SensorKitRecord + ) { + self.file = file + self.retryEvidenceSupplement = retryEvidenceSupplement + self.makeRecord = makeRecord + } + + /// Writes each ECG sample independently while preserving the established JSON field order and numeric representation. + @available(iOS 17.4, *) + public init(electrocardiogram session: SensorKitECGSession, maximumByteCount: Int) throws { + self.file = try Self.ecgFile(session, maximumByteCount: maximumByteCount) + self.retryEvidenceSupplement = session.groveRetryEvidenceSupplement + self.makeRecord = { sourceID, native in + .electrocardiogram(try SensorKitECGRecord(sourceRecordID: sourceID, session: session, nativeRecording: native)) + } + } + + /// Reads the exact source facts a retry compares, the bytes of + /// ``SensorKitPreparedStructuredRecord/retryEvidence``: the native JSON, followed by any fact the JSON doesn't + /// state. + public func readRetryEvidenceChunks(_ consume: (Data) throws -> Void) throws { + try file.readChunks(consume) + try Task.checkCancellation() + if !retryEvidenceSupplement.isEmpty { try consume(retryEvidenceSupplement) } + } + + /// Builds the FHIR input, referencing the file at an archive-relative path. + /// + /// This module generated the JSON, so the file is attached without being parsed again to check it. + /// + /// - Parameters: + /// - sourceRecordID: The identity of the source sample. + /// - title: The attachment title. + /// - sidecarPath: The archive-relative path the file is stored at. + /// - admission: The caller's authorization to attach the native recording. + public func sensorKitRecord( + sourceRecordID: SensorKitSourceRecordID, title: String, sidecarPath: String, admission: RecordingPayloadAdmission + ) throws -> SensorKitRecord { + let native = try SensorKitNativeRecording( + title: title, format: .nativeRecordingJSON, payload: .file(path: sidecarPath, contents: file), admission: admission + ) { _ in } + return try makeRecord(sourceRecordID, native) + } +} + + +extension SensorKitPreparedStructuredFile { + @available(iOS 17.4, *) + private static func ecgFile(_ session: SensorKitECGSession, maximumByteCount: Int) throws -> RecordingFile { + let writer = SensorKitJSONFileEncoding() + return try RecordingFile.stage(maximumByteCount: min(maximumByteCount, RegisteredRecordingFormat.maximumDecodedPayloadByteCount)) { append in + try writer.object(ECGKey.allCases, name: \.rawValue, append: append) { key in + switch key { + case .batches: + try writer.array(session.batches, append: append) { batch in + try writer.object(ECGBatchKey.allCases, name: \.rawValue, append: append) { key in + switch key { + case .offsetSeconds: try writer.value(batch.offset, append: append) + case .samples: + try writer.array(batch.samples, append: append) { sample in + try writer.value(ECGSampleEvidence( + flags: sample.flags.rawValue, microvolts: sample.voltage.converted(to: .microvolts).value + ), append: append) + } + } + } + } + case .sessionIdentifier: try writer.value(session.sessionIdentifier, append: append) + case .sessionStates: try writer.value(session.sessionStates.map(\.rawValue), append: append) + } + } + } + } +} + + +#endif diff --git a/Sources/GroveSensorKitFHIR/SensorKitStructuredPreparation+GroveSensorKit.swift b/Sources/GroveSensorKitFHIR/SensorKitStructuredPreparation+GroveSensorKit.swift index 9affaeac7..b7e6b1d0d 100644 --- a/Sources/GroveSensorKitFHIR/SensorKitStructuredPreparation+GroveSensorKit.swift +++ b/Sources/GroveSensorKitFHIR/SensorKitStructuredPreparation+GroveSensorKit.swift @@ -25,7 +25,10 @@ public struct SensorKitPreparedStructuredRecord: Sendable { _ sourceRecordID: SensorKitSourceRecordID, _ nativeRecording: SensorKitNativeRecording? ) throws -> SensorKitRecord + /// The exact source facts a retry compares: the native payload, followed by any fact the payload doesn't state. + /// It doesn't contribute to resource identities. public let retryEvidence: Data + /// The native bytes Grove generated, when the record carries a native recording. public let nativePayload: Data? public init(visit: SRVisit.SafeRepresentation) throws { @@ -104,10 +107,58 @@ public struct SensorKitPreparedStructuredRecord: Sendable { nativeRecording: nativeRecording )) } - self.retryEvidence = payload + self.retryEvidence = payload + session.groveRetryEvidenceSupplement self.nativePayload = payload } + /// Prepares every public messages-usage field without carrying a non-Sendable SDK object. + public init(messagesUsage report: SRMessagesUsageReport.SafeRepresentation) throws { + var writer = RecordingBinaryWriter() + try writer.writeFloat64(report.timestamp.timeIntervalSince1970) + try writer.writeFloat64(report.duration) + writer.writeVarint(Int64(report.totalIncomingMessages)) + writer.writeVarint(Int64(report.totalOutgoingMessages)) + writer.writeVarint(Int64(report.totalUniqueContacts)) + self.makeRecord = { sourceRecordID, nativeRecording in + .messagesUsage(SensorKitMessagesUsageRecord( + sourceRecordID: sourceRecordID, + timestamp: report.timestamp, + durationSeconds: report.duration, + totalIncomingMessages: report.totalIncomingMessages, + totalOutgoingMessages: report.totalOutgoingMessages, + totalUniqueContacts: report.totalUniqueContacts, + nativeRecording: nativeRecording + )) + } + self.retryEvidence = writer.data() + self.nativePayload = nil + } + + /// Prepares every public phone-usage field without carrying a non-Sendable SDK object. + public init(phoneUsage report: SRPhoneUsageReport.SafeRepresentation) throws { + var writer = RecordingBinaryWriter() + try writer.writeFloat64(report.timestamp.timeIntervalSince1970) + try writer.writeFloat64(report.duration) + writer.writeVarint(Int64(report.totalIncomingCalls)) + writer.writeVarint(Int64(report.totalOutgoingCalls)) + writer.writeVarint(Int64(report.totalUniqueContacts)) + try writer.writeFloat64(report.totalPhoneCallDuration) + self.makeRecord = { sourceRecordID, nativeRecording in + .phoneUsage(SensorKitPhoneUsageRecord( + sourceRecordID: sourceRecordID, + timestamp: report.timestamp, + durationSeconds: report.duration, + totalIncomingCalls: report.totalIncomingCalls, + totalOutgoingCalls: report.totalOutgoingCalls, + totalPhoneCallDurationSeconds: report.totalPhoneCallDuration, + totalUniqueContacts: report.totalUniqueContacts, + nativeRecording: nativeRecording + )) + } + self.retryEvidence = writer.data() + self.nativePayload = nil + } + /// Creates the Grove record. Native evidence is required exactly when `nativePayload` is non-nil. public func sensorKitRecord( sourceRecordID: SensorKitSourceRecordID, @@ -150,8 +201,17 @@ public struct SensorKitPreparedStructuredRecord: Sendable { @available(iOS 18, *) -private struct DeviceUsageEvidence: Encodable { +struct DeviceUsageEvidence: Encodable { + enum CodingKeys: String, CodingKey, CaseIterable { + case timestamp, duration, totalScreenWakes, totalUnlocks, totalUnlockDuration, version + case appUsageByCategory, notificationUsageByCategory, webUsageByCategory + } + struct ApplicationUsage: Encodable { + enum CodingKeys: String, CodingKey, CaseIterable { + case bundleIdentifier, reportApplicationIdentifier, relativeStartTime, usageTime, supplementalCategories, textInputSessions + } + struct SupplementalCategory: Encodable { let identifier: String } diff --git a/Tests/GroveFHIRTests/RecordingFormats/RecordingFileProducerTests.swift b/Tests/GroveFHIRTests/RecordingFormats/RecordingFileProducerTests.swift new file mode 100644 index 000000000..0b5f2b172 --- /dev/null +++ b/Tests/GroveFHIRTests/RecordingFormats/RecordingFileProducerTests.swift @@ -0,0 +1,51 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation +import GroveFHIRContract +import Testing + + +@Suite +struct RecordingFileProducerTests { + private enum Failure: Error { + case interrupted + } + + @Test + func bufferedProductionPreservesBoundariesAndRefusesPartialSuccess() throws { + let chunk = Data(repeating: 17, count: 32_769) + let count = chunk.count * 3 + let file = try RecordingFile.stage(maximumByteCount: count) { append in + for _ in 0..<3 { try append(chunk) } + } + var actual = Data() + try file.readChunks { actual.append($0) } + #expect(actual == chunk + chunk + chunk) + #expect(throws: RecordingFile.FileError.byteLimitExceeded) { + try RecordingFile.stage(maximumByteCount: count - 1) { append in + for _ in 0..<3 { try append(chunk) } + } + } + #expect(throws: RecordingFile.FileError.byteLimitExceeded) { + try RecordingFile.stage(maximumByteCount: 1) { append in + try append(Data([1])) + do { try append(Data([2])) } catch { } + } + } + #expect(throws: Failure.interrupted) { + try RecordingFile.stage(maximumByteCount: count) { append in + try append(chunk) + throw Failure.interrupted + } + } + #expect(throws: RecordingFile.FileError.emptySource) { + try RecordingFile.stage(maximumByteCount: count) { _ in } + } + } +} diff --git a/Tests/GroveSensorKitFHIRTests/RegisteredRecordingFileValidationTests.swift b/Tests/GroveSensorKitFHIRTests/RegisteredRecordingFileValidationTests.swift new file mode 100644 index 000000000..b00fac9c6 --- /dev/null +++ b/Tests/GroveSensorKitFHIRTests/RegisteredRecordingFileValidationTests.swift @@ -0,0 +1,105 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation +import GroveFHIRContract +import GroveSensorKitFHIR +import Testing + + +@Suite +struct RegisteredRecordingFileValidationTests { + @Test + func callerBudgetIsCheckedBeforeGrammarAndAllowsItsExactBoundary() throws { + let file = try staged(Data("{\"value\":1}".utf8)) + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(file, maximumByteCount: file.byteCount) + for limit in [-1, 0, file.byteCount - 1, Int(Int32.max) + 1] { + #expect(throws: RegisteredRecordingPayloadError.payloadLimitExceeded) { + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(file, maximumByteCount: limit) + } + } + } + + @Test + func memoryEntryPointAppliesTheSameCallerBudget() throws { + let bytes = Data("{\"value\":1}".utf8) + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(bytes, maximumByteCount: bytes.count) + for limit in [-1, 0, bytes.count - 1, Int(Int32.max) + 1] { + #expect(throws: RegisteredRecordingPayloadError.payloadLimitExceeded) { + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(bytes, maximumByteCount: limit) + } + } + } + + @Test + func fileEntryPointUsesStrictJSONAndTypedCSVValidation() throws { + let duplicate = try staged(Data("{\"value\":1,\"value\":2}".utf8)) + #expect(throws: RegisteredRecordingPayloadError.duplicateJSONMember("value")) { + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(duplicate, maximumByteCount: 1_024) + } + let format = RegisteredRecordingFormat.heartRateSamples + let header = try #require(format.csvColumns).joined(separator: ",") + let invalidRow = try staged(Data("\(header)\nnot-a-timestamp,60,2,Watch\n".utf8)) + #expect(throws: RegisteredRecordingPayloadError.invalidTabularPayload(.invalidColumnValue(row: 1, column: "timestamp"))) { + try format.validatePayload(invalidRow, maximumByteCount: 16_384) + } + } + + @Test + func nonStreamingGrammarRetainsItsHardLimitEvenWhenCallerAllowsMore() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("oversized.json") + try Data().write(to: url, options: .withoutOverwriting) + let writer = try FileHandle(forWritingTo: url) + defer { try? writer.close() } + let chunk = Data(repeating: 32, count: 65_536) + for _ in 0..<(RegisteredRecordingFormat.maximumDecodedPayloadByteCount / chunk.count) { try writer.write(contentsOf: chunk) } + try writer.write(contentsOf: Data([0])) + try writer.synchronize() + let file = try RecordingFile.stage(copying: url, maximumByteCount: RegisteredRecordingFormat.maximumDecodedPayloadByteCount + 1) + for format in [RegisteredRecordingFormat.nativeRecordingJSON, .providerResponseJSON, .photoplethysmogramSamples, .sensorSampleCollectionBundle] { + #expect(throws: RegisteredRecordingPayloadError.payloadLimitExceeded) { + try format.validatePayload(file, maximumByteCount: file.byteCount) + } + } + } + + @Test + func retainedBytesUseTheSameGrammarAndInclusiveCallerBudget() throws { + let bytes = Data("{\"value\":1}".utf8) + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(bytes, maximumByteCount: bytes.count) + for limit in [-1, 0, bytes.count - 1] { + #expect(throws: RegisteredRecordingPayloadError.payloadLimitExceeded) { + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(bytes, maximumByteCount: limit) + } + } + let duplicate = Data("{\"value\":1,\"value\":2}".utf8) + #expect(throws: RegisteredRecordingPayloadError.duplicateJSONMember("value")) { + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(duplicate, maximumByteCount: duplicate.count) + } + let csv = Data("timestamp,value,confidence,device\n1,not-a-number,3,Watch\n".utf8) + #expect(throws: RegisteredRecordingPayloadError.invalidTabularPayload(.invalidColumnValue(row: 1, column: "value"))) { + try RegisteredRecordingFormat.heartRateSamples.validatePayload(csv, maximumByteCount: csv.count) + } + let oversized = Data(repeating: 32, count: RegisteredRecordingFormat.maximumDecodedPayloadByteCount + 1) + #expect(throws: RegisteredRecordingPayloadError.payloadLimitExceeded) { + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(oversized, maximumByteCount: oversized.count) + } + } + + private func staged(_ bytes: Data) throws -> RecordingFile { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("source") + try bytes.write(to: url, options: .withoutOverwriting) + return try RecordingFile.stage(copying: url, maximumByteCount: bytes.count) + } +} diff --git a/Tests/GroveSensorKitFHIRTests/SensorKitBatchSnapshotTests.swift b/Tests/GroveSensorKitFHIRTests/SensorKitBatchSnapshotTests.swift new file mode 100644 index 000000000..3c8255386 --- /dev/null +++ b/Tests/GroveSensorKitFHIRTests/SensorKitBatchSnapshotTests.swift @@ -0,0 +1,107 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation +import GroveFHIRContract +@testable import GroveSensorKitFHIR +import Testing + + +struct SensorKitBatchSnapshotTests { + @Test + func retainsEveryDeviceFactAndFractionalInstant() throws { + var device = RecordingDevice() + device.stableUnitToken = "stable-unit" + device.tokenScope = "participant" + device.name = "Recording device" + device.manufacturer = "Manufacturer" + device.model = "Model" + device.productType = "Watch1,1" + device.systemName = "watchOS" + device.systemVersion = "27.2" + device.hardwareVersion = "hardware" + device.firmwareVersion = "firmware" + device.softwareVersion = "software" + device.localIdentifier = "local" + device.udiDeviceIdentifier = "udi-device" + device.udiProductionIdentifier = "udi-production" + device.serialNumber = "serial" + let original = try snapshot(device: device) + let bytes = try original.encoded(maximumByteCount: 16_384) + let restored = try SensorKitBatchSnapshot(encoded: bytes, maximumByteCount: 16_384) + #expect(restored == original) + #expect(restored.recordingDevice == device) + #expect(restored.sourceDevices == [device]) + #expect(try restored.encoded(maximumByteCount: 16_384) == bytes) + } + + @Test + func boundsBeforeDecodingAndAfterEncoding() throws { + let original = try snapshot() + let bytes = try original.encoded(maximumByteCount: 16_384) + #expect(throws: SensorKitBatchSnapshot.SnapshotError.capacityExceeded) { + try SensorKitBatchSnapshot(encoded: bytes, maximumByteCount: bytes.count - 1) + } + #expect(throws: SensorKitBatchSnapshot.SnapshotError.capacityExceeded) { + try original.encoded(maximumByteCount: bytes.count - 1) + } + #expect(throws: SensorKitBatchSnapshot.SnapshotError.capacityExceeded) { + try SensorKitBatchSnapshot(encoded: Data(), maximumByteCount: 16_384) + } + } + + @Test(arguments: ["version", "timeZone", "application", "instant", "malformed"]) + func rejectsUnknownVersionOrInvalidRetainedFacts(field: String) throws { + let bytes = try snapshot().encoded(maximumByteCount: 16_384) + var object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + switch field { + case "version": + // Another version needn't have this version's shape. + object[field] = 2 + object.removeValue(forKey: "host") + case "timeZone": object[field] = "Invalid/TimeZone" + case "instant": object[field] = "not a date" + case "malformed": object.removeValue(forKey: "host") + default: + var application = try #require(object[field] as? [String: Any]) + application["bundleIdentifier"] = "" + object[field] = application + } + let corrupted = try JSONSerialization.data(withJSONObject: object) + let expected: SensorKitBatchSnapshot.SnapshotError = field == "version" ? .unsupportedVersion : .invalidFacts + #expect(throws: expected) { + try SensorKitBatchSnapshot(encoded: corrupted, maximumByteCount: 16_384) + } + } + + @Test + func moreSourceDevicesThanTheLimitExceedTheCapacityCreatedAndDecoded() throws { + #expect(try snapshot(sourceDevices: 128).sourceDevices.count == 128) + #expect(throws: SensorKitBatchSnapshot.SnapshotError.capacityExceeded) { try snapshot(sourceDevices: 129) } + let bytes = try snapshot().encoded(maximumByteCount: 16_384) + var object = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + let source = try #require((object["sources"] as? [Any])?.first) + object["sources"] = Array(repeating: source, count: 129) + let oversized = try JSONSerialization.data(withJSONObject: object) + #expect(throws: SensorKitBatchSnapshot.SnapshotError.capacityExceeded) { + try SensorKitBatchSnapshot(encoded: oversized, maximumByteCount: oversized.count) + } + } + + private func snapshot(device: RecordingDevice = RecordingDevice(), sourceDevices: Int = 1) throws -> SensorKitBatchSnapshot { + try SensorKitBatchSnapshot( + application: SensorKitExporterFixtures.application, + host: SensorFHIRIdentityTestSupport.converterHost, + recordingDevice: device, + sourceDevices: Array(repeating: device, count: sourceDevices), + sourceDevicesSuppliedEverySample: true, + sourceTimeZone: SensorKitExporterFixtures.timeZone, + conversionInstant: SensorKitExporterFixtures.instant.addingTimeInterval(0.123456) + ) + } +} diff --git a/Tests/GroveSensorKitFHIRTests/SensorKitECGRetryEvidenceTests.swift b/Tests/GroveSensorKitFHIRTests/SensorKitECGRetryEvidenceTests.swift new file mode 100644 index 000000000..f3f934f82 --- /dev/null +++ b/Tests/GroveSensorKitFHIRTests/SensorKitECGRetryEvidenceTests.swift @@ -0,0 +1,83 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) +import Foundation +import GroveFHIRContract +@testable import GroveSensorKit +import GroveSensorKitFHIR +import SensorKit +import Testing + + +@Suite +struct SensorKitECGRetryEvidenceTests { + @available(iOS 17.4, *) + @Test(arguments: ["start", "frequency", "lead", "guidance"]) + func sourceFactsOutsideNativePayloadChangeTheRetryEvidence(field: String) throws { + let first = try SensorKitPreparedStructuredRecord(electrocardiogram: session()) + let changed = try SensorKitPreparedStructuredRecord(electrocardiogram: session(changing: field)) + let payload = try #require(first.nativePayload) + #expect(first.nativePayload == changed.nativePayload) + #expect(first.retryEvidence.count == payload.count + 32) + #expect(first.retryEvidence != changed.retryEvidence) + } + + @available(iOS 17.4, *) + @Test + func retryEvidenceAppendsTheExistingClientFramingToTheNativePayload() throws { + let sample = session() + let prepared = try SensorKitPreparedStructuredRecord(electrocardiogram: sample) + var existing = Data() + for word in [ + sample.startDate.timeIntervalSince1970.bitPattern, + sample.frequency.converted(to: .hertz).value.bitPattern, + UInt64(bitPattern: Int64(sample.lead.rawValue)), + UInt64(bitPattern: Int64(sample.guidance.rawValue)) + ] { + withUnsafeBytes(of: word.bigEndian) { existing.append(contentsOf: $0) } + } + #expect(prepared.retryEvidence == (try #require(prepared.nativePayload)) + existing) + } + + @available(iOS 17.4, *) + @Test + func filePreparationPreservesExactBytesAndRetryEvidence() throws { + let sample = session() + let data = try SensorKitPreparedStructuredRecord(electrocardiogram: sample) + let file = try SensorKitPreparedStructuredFile(electrocardiogram: sample, maximumByteCount: 4096) + var bytes = Data() + try file.file.readChunks { bytes.append($0) } + #expect(bytes == data.nativePayload) + var evidence = Data() + try file.readRetryEvidenceChunks { evidence.append($0) } + #expect(evidence == data.retryEvidence) + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(file.file, maximumByteCount: file.file.byteCount) + #expect(throws: RecordingFile.FileError.byteLimitExceeded) { + try SensorKitPreparedStructuredFile(electrocardiogram: sample, maximumByteCount: file.file.byteCount - 1) + } + let exact = try SensorKitPreparedStructuredFile(electrocardiogram: sample, maximumByteCount: file.file.byteCount) + #expect(exact.file.byteCount == file.file.byteCount) + } + + @available(iOS 17.4, *) + private func session(changing field: String = "") -> SensorKitECGSession { + SensorKitECGSession( + startDate: Date(timeIntervalSince1970: field == "start" ? 101 : 100), + sessionIdentifier: "synthetic-ecg-session", + sessionStates: [.begin, .active, .end], + frequency: Measurement(value: field == "frequency" ? 256 : 512, unit: .hertz), + lead: field == "lead" ? .leftArmMinusRightArm : .rightArmMinusLeftArm, + guidance: field == "guidance" ? .unguided : .guided, + batches: [ + .init(offset: 0, samples: [.init(flags: [], voltage: Measurement(value: 1, unit: .microvolts))]) + ] + ) + } +} +#endif diff --git a/Tests/GroveSensorKitFHIRTests/SensorKitOutputDefinitionTests.swift b/Tests/GroveSensorKitFHIRTests/SensorKitOutputDefinitionTests.swift new file mode 100644 index 000000000..5027c7d7c --- /dev/null +++ b/Tests/GroveSensorKitFHIRTests/SensorKitOutputDefinitionTests.swift @@ -0,0 +1,73 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +import Foundation +import GroveFHIRContract +@testable import GroveSensorKitFHIR +import ModelsR4 +import Testing + + +struct SensorKitOutputDefinitionTests { + @Test + func deferredInventoryDoesNotBecomeProducerAvailability() throws { + let rows = SensorKitCatalog.current.entries + #expect(rows.compactMap(\.implementedOutput).count == 21) + #expect(rows.filter { $0.status == .deferred }.allSatisfy { $0.implementedOutput == nil }) + for row in rows { + guard let output = row.implementedOutput else { continue } + #expect(output.recordingFormats == row.rawFormats) + #expect(output.recordingProfiles == row.rawProfiles) + #expect(output.observation?.profiles == row.structuredContract.map { _ in row.structuredProfiles }) + if let observation = output.observation { + #expect(observation.primaryProfile != nil) + #expect(output.requiredCompanionProfiles == ( + observation.requiresRecording ? [SensorKitContract.recordingDocumentProfile] : [] + )) + } + } + } + + @Test(arguments: [false, true]) + func onWristDescriptorMatchesActualPointAndIntervalOutput(interval: Bool) async throws { + let instant = SensorKitExporterFixtures.instant + let input = SensorKitRecord.onWrist(.init( + sourceRecordID: .init(UUID()), + timestamp: instant, + onWrist: true, + currentStateStart: interval ? instant.addingTimeInterval(-60) : instant, + wristLocation: .left, + crownOrientation: .right + )) + let output = try #require(SensorKitCatalog.current.entry(sourceToken: input.sourceToken)?.implementedOutput?.observation) + #expect(output.effective == .dateTimeOrPeriod) + #expect(output.valueShape == .coded) + #expect(!output.requiresRecording) + let record = try await SensorKitExporterFixtures.record(input) + let observation = try #require(record.graph.bundle.entry?.compactMap { entry -> Observation? in + if case .observation(let observation)? = entry.resource { observation } else { nil } + }.first) + #expect(observation.meta?.profile?.map { $0.value?.url.absoluteString } == output.profiles.map(Optional.some)) + if interval { + guard case .period = observation.effective else { + Issue.record("Missing declared interval") + return + } + } else { + guard case .dateTime = observation.effective else { + Issue.record("Missing declared point") + return + } + } + guard case .codeableConcept = observation.value else { + Issue.record("Missing declared coded value") + return + } + #expect(observation.component?.count == 2) + } +} diff --git a/Tests/GroveSensorKitFHIRTests/SensorKitStructuredFileTests.swift b/Tests/GroveSensorKitFHIRTests/SensorKitStructuredFileTests.swift new file mode 100644 index 000000000..26d495bc7 --- /dev/null +++ b/Tests/GroveSensorKitFHIRTests/SensorKitStructuredFileTests.swift @@ -0,0 +1,63 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) +import Foundation +import GroveFHIRContract +import GroveSensorKit +import GroveSensorKitFHIR +import SensorKit +import Testing + + +struct SensorKitStructuredFileTests { + @available(iOS 18, *) + @Test(arguments: [false, true]) + func deviceUsageFilePreservesEveryNestedFieldAndOptionalOmission(hasBundle: Bool) throws { + let report = SRDeviceUsageReport.SafeRepresentation( + timestamp: Date(timeIntervalSince1970: 1_787_009_400.125), + duration: 300, + totalScreenWakes: 3, + totalUnlocks: 2, + totalUnlockDuration: 42.5, + version: "synthetic/1", + appUsageByCategory: [ + // Names whose order depends on case and digit handling pin the file's member order to the in-memory encoding's. + .init(rawValue: "Category-10"): [], + .init(rawValue: "category-9"): [], + .init(rawValue: "CATEGORY-2"): [], + .init(rawValue: "category-b"): [], + .init(rawValue: "category-a"): [ + .init( + bundleIdentifier: hasBundle ? "org.example.synthetic" : nil, + relativeStartTime: 1.5, + usageTime: 3.25, + reportApplicationIdentifier: "app/one", + textInputSessions: [.init(duration: 1.25, sessionType: .keyboard, identifier: "input/one")], + supplementalCategories: [.init(identifier: "z"), .init(identifier: "a")] + ) + ] + ], + notificationUsageByCategory: [.init(rawValue: "notifications"): [.init(bundleIdentifier: nil, event: .received)]], + webUsageByCategory: [.init(rawValue: "web"): [.init(totalUsageTime: 2.5)]] + ) + let data = try SensorKitPreparedStructuredRecord(deviceUsage: report) + let file = try SensorKitPreparedStructuredFile(deviceUsage: report, maximumByteCount: 16_384) + var bytes = Data() + try file.readRetryEvidenceChunks { bytes.append($0) } + #expect(bytes == data.retryEvidence) + #expect(bytes == data.nativePayload) + try RegisteredRecordingFormat.nativeRecordingJSON.validatePayload(file.file, maximumByteCount: file.file.byteCount) + #expect(throws: RecordingFile.FileError.byteLimitExceeded) { + try SensorKitPreparedStructuredFile(deviceUsage: report, maximumByteCount: file.file.byteCount - 1) + } + let exact = try SensorKitPreparedStructuredFile(deviceUsage: report, maximumByteCount: file.file.byteCount) + #expect(exact.file.byteCount == file.file.byteCount) + } +} +#endif diff --git a/Tests/GroveSensorKitFHIRTests/SensorKitUsagePreparationTests.swift b/Tests/GroveSensorKitFHIRTests/SensorKitUsagePreparationTests.swift new file mode 100644 index 000000000..51b60aa5d --- /dev/null +++ b/Tests/GroveSensorKitFHIRTests/SensorKitUsagePreparationTests.swift @@ -0,0 +1,76 @@ +// +// This source file is part of the Grove open-source project +// +// SPDX-FileCopyrightText: 2026 Stanford University and the project authors (see CONTRIBUTORS.md) +// +// SPDX-License-Identifier: MIT +// + +#if os(iOS) + +import Foundation +import GroveFHIRContract +import GroveSensorKit +import GroveSensorKitFHIR +import SensorKit +import Testing + + +struct SensorKitUsagePreparationTests { + @Test + func messagesRetainEveryPublicFieldAndStableRetryEvidence() throws { + let instant = Date(timeIntervalSince1970: 1_800_000_000) + let sample = SRMessagesUsageReport.SafeRepresentation( + timestamp: instant, duration: 60, totalOutgoingMessages: 3, totalIncomingMessages: 4, totalUniqueContacts: 5 + ) + let prepared = try SensorKitPreparedStructuredRecord(messagesUsage: sample) + #expect(prepared.nativePayload == nil) + #expect(try SensorKitPreparedStructuredRecord(messagesUsage: sample).retryEvidence == prepared.retryEvidence) + let identity = SensorKitSourceRecordID(UUID()) + guard case .messagesUsage(let record) = try prepared.sensorKitRecord(sourceRecordID: identity) else { + Issue.record("Expected messages usage record") + return + } + #expect(record.sourceRecordID == identity) + #expect(record.timestamp == instant) + #expect(record.durationSeconds == 60) + #expect(record.totalOutgoingMessages == 3) + #expect(record.totalIncomingMessages == 4) + #expect(record.totalUniqueContacts == 5) + let changed = SRMessagesUsageReport.SafeRepresentation( + timestamp: instant, duration: 60, totalOutgoingMessages: 3, totalIncomingMessages: 4, totalUniqueContacts: 6 + ) + #expect(try SensorKitPreparedStructuredRecord(messagesUsage: changed).retryEvidence != prepared.retryEvidence) + } + + @Test + func phoneDurationParticipatesInBothProjectionAndRetryEvidence() throws { + let instant = Date(timeIntervalSince1970: 1_800_000_000) + func sample(duration: Double) -> SRPhoneUsageReport.SafeRepresentation { + .init( + timestamp: instant, + duration: 60, + totalOutgoingCalls: 1, + totalIncomingCalls: 2, + totalUniqueContacts: 3, + totalPhoneCallDuration: duration + ) + } + let prepared = try SensorKitPreparedStructuredRecord(phoneUsage: sample(duration: 40)) + let changed = try SensorKitPreparedStructuredRecord(phoneUsage: sample(duration: 41)) + #expect(prepared.retryEvidence != changed.retryEvidence) + #expect(prepared.nativePayload == nil) + guard case .phoneUsage(let record) = try prepared.sensorKitRecord(sourceRecordID: .init(UUID())) else { + Issue.record("Expected phone usage record") + return + } + #expect(record.timestamp == instant) + #expect(record.durationSeconds == 60) + #expect(record.totalOutgoingCalls == 1) + #expect(record.totalIncomingCalls == 2) + #expect(record.totalUniqueContacts == 3) + #expect(record.totalPhoneCallDurationSeconds == 40) + } +} + +#endif