IobJsonTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import Foundation
  2. import Testing
  3. @testable import Trio
  4. /// This test suite is to help us debug and verify iob errors from Trio devices
  5. ///
  6. /// There are two key components. First, we have a version of the Javascript that has a number
  7. /// of bugs fixed. We don't want to fix the real Javascript, so we put this fixed Javascript in the
  8. /// testing bundle and use it to run comparisons. If the error we see in the field is one that we know
  9. /// about and have fixed in JS, the Swift and JS implementations will produce the same results. You
  10. /// can find the fixed JS here:
  11. /// https://github.com/kingst/trio-oref/tree/tcd-fixes-for-swift-comparison
  12. ///
  13. /// Second, we have a server that runs (part of `trio-oref-logs`) to serve error logs captured
  14. /// from the field. This server needs to run on the same machine as the simulator where this test runs.
  15. /// You can find more information about it from the `trio-oref-logs` repo.
  16. @Suite("IoB using real pump history JSON", .serialized) struct IobJsonTests {
  17. let timeZoneForTests = TimeZoneForTests()
  18. struct IobHistoryResult: Codable {
  19. var insulin: Decimal?
  20. var rate: Decimal?
  21. var duration: Decimal?
  22. var timestamp: String?
  23. var started_at: String?
  24. var created_at: String?
  25. var date: Decimal?
  26. enum CodingKeys: String, CodingKey {
  27. case insulin
  28. case rate
  29. case duration
  30. case timestamp
  31. case started_at
  32. case created_at
  33. case date
  34. }
  35. }
  36. // Note: This test case has a memory leak so limit your inputs
  37. // to about 250 files at a time
  38. @Test(
  39. "IoB should produce same results for fixed JS and different for bundle JS",
  40. .enabled(if: ReplayTests.enabled)
  41. ) func replayErrorInputs() async throws {
  42. let files = try await HttpFiles.listFiles()
  43. let testingTimezone = ReplayTests.timezone
  44. for filePath in files {
  45. let algorithmComparison = try await HttpFiles.downloadFile(at: filePath)
  46. print("Checking \(filePath) @ \(algorithmComparison.createdAt)")
  47. guard algorithmComparison.timezone == testingTimezone else {
  48. continue
  49. }
  50. guard let iobInputs = algorithmComparison.iobInput else {
  51. print("Skipping, no iobInputs found")
  52. if let str = algorithmComparison.comparisonError {
  53. print(str)
  54. }
  55. if let str = algorithmComparison.swiftException {
  56. print(str)
  57. }
  58. continue
  59. }
  60. // The JS implementation of IoB when the pump is suspend is so fundamentally
  61. // broken that I wasn't able to fix it in JS. So we'll just skip these, but I
  62. // verified them by hand and the Swift implementation appears to be correct
  63. if let mostRecentSuspendResumeEvent = iobInputs.history.filter({ $0.type == .pumpSuspend || $0.type == .pumpResume })
  64. .first
  65. {
  66. if mostRecentSuspendResumeEvent.type == .pumpSuspend
  67. {
  68. print("Skipping, known issue with JS and currently suspended pumps")
  69. continue
  70. }
  71. }
  72. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  73. try await checkFixedJsAgainstSwift(iobInputs: iobInputs)
  74. // try await checkBundleJsAgainstSwift(iobInputs: iobInputs)
  75. timeZoneForTests.resetTimezone()
  76. }
  77. }
  78. func checkFixedJsAgainstSwift(iobInputs: IobInputs) async throws {
  79. let openAps = OpenAPSFixed()
  80. let (iobResultSwift, _) = OpenAPSSwift.iob(
  81. pumphistory: iobInputs.history,
  82. profile: try JSONBridge.to(iobInputs.profile),
  83. clock: iobInputs.clock,
  84. autosens: try JSONBridge.to(iobInputs.autosens)
  85. )
  86. let iobResultJavascript = await openAps.iobJavascript(
  87. pumphistory: iobInputs.history,
  88. profile: try JSONBridge.to(iobInputs.profile),
  89. clock: iobInputs.clock,
  90. autosens: try JSONBridge.to(iobInputs.autosens)
  91. )
  92. // In suspendedPrior mode (first suspend/resume event is a Resume), JS incorrectly
  93. // returns pre-resume temp basals in lastTemp because history.js line 566 uses
  94. // tempHistory instead of splitHistory. Swift correctly handles this case.
  95. if case let .success(jsRawJson) = iobResultJavascript,
  96. let jsIobEntries = try? JSONBridge.iobResult(from: jsRawJson),
  97. let jsLastTempDate = jsIobEntries.first?.lastTemp?.date
  98. {
  99. let suspendResumeEvents = iobInputs.history
  100. .filter { $0.type == .pumpSuspend || $0.type == .pumpResume }
  101. .sorted { $0.timestamp < $1.timestamp }
  102. if let firstEvent = suspendResumeEvents.first,
  103. firstEvent.type == .pumpResume
  104. {
  105. let firstResumeTime = UInt64(firstEvent.timestamp.timeIntervalSince1970 * 1000)
  106. if jsLastTempDate < firstResumeTime {
  107. print("Skipping, known issue with JS lastTemp in suspendedPrior mode")
  108. return
  109. }
  110. }
  111. }
  112. let comparison = JSONCompare.createComparison(
  113. function: .iob,
  114. swift: iobResultSwift,
  115. swiftDuration: 0.1,
  116. javascript: iobResultJavascript,
  117. javascriptDuration: 0.1,
  118. iobInputs: nil,
  119. mealInputs: nil,
  120. autosensInputs: nil,
  121. determineBasalInputs: nil
  122. )
  123. if comparison.resultType == .valueDifference {
  124. print(comparison.differences!.prettyPrintedJSON!)
  125. }
  126. if comparison.resultType != .matching {
  127. print("REPLAY ERROR: Fixed JS didn't match")
  128. }
  129. #expect(comparison.resultType == .matching)
  130. }
  131. func checkBundleJsAgainstSwift(iobInputs: IobInputs) async throws {
  132. let openAps = OpenAPS(storage: BaseFileStorage(), tddStorage: MockTDDStorage())
  133. let (iobResultSwift, _) = OpenAPSSwift.iob(
  134. pumphistory: iobInputs.history,
  135. profile: try JSONBridge.to(iobInputs.profile),
  136. clock: iobInputs.clock,
  137. autosens: try JSONBridge.to(iobInputs.autosens)
  138. )
  139. let iobResultJavascript = await openAps.iobJavascript(
  140. pumphistory: iobInputs.history,
  141. profile: try JSONBridge.to(iobInputs.profile),
  142. clock: iobInputs.clock,
  143. autosens: try JSONBridge.to(iobInputs.autosens)
  144. )
  145. let comparison = JSONCompare.createComparison(
  146. function: .iob,
  147. swift: iobResultSwift,
  148. swiftDuration: 0.1,
  149. javascript: iobResultJavascript,
  150. javascriptDuration: 0.1,
  151. iobInputs: nil,
  152. mealInputs: nil,
  153. autosensInputs: nil,
  154. determineBasalInputs: nil
  155. )
  156. if comparison.resultType != .valueDifference {
  157. print("REPLAY ERROR: bundle JS did't produce value difference")
  158. }
  159. #expect(comparison.resultType == .valueDifference)
  160. }
  161. func checkHistoryConsistency(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  162. let swiftNetBolus = swiftTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  163. let jsNetBolus = jsTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  164. let swiftNetBasal = swiftTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  165. let jsNetBasal = jsTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  166. #expect(swiftNetBasal == jsNetBasal)
  167. #expect(swiftNetBolus == jsNetBolus)
  168. }
  169. func checkRunningBasal(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  170. let swiftBasals = swiftTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  171. let jsBasals = jsTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  172. #expect(swiftBasals.count == jsBasals.count)
  173. for (swift, js) in zip(swiftBasals, jsBasals) {
  174. #expect(Decimal(swift.date) == js.date!)
  175. #expect(swift.duration!.isWithin(0.01, of: js.duration!))
  176. #expect(swift.rate == js.rate)
  177. let start = js.date!
  178. let end = js.date! + js.duration! * 60 * 1000
  179. let swiftTempBolus = swiftTreatments
  180. .filter({ Decimal($0.date) >= start && Decimal($0.date) < end && $0.insulin != nil && $0.insulin! < 0.1 })
  181. .map({ $0.insulin! }).reduce(0, +)
  182. let jsTempBolus = jsTreatments
  183. .filter({ $0.date! >= start && $0.date! < end && $0.insulin != nil && $0.insulin! < 0.1 }).map({ $0.insulin! })
  184. .reduce(0, +)
  185. if swiftTempBolus != jsTempBolus {
  186. print("temp bolus @ \(swift.timestamp) mismatch swift: \(swiftTempBolus) js: \(jsTempBolus)")
  187. }
  188. #expect(swiftTempBolus == jsTempBolus)
  189. }
  190. }
  191. @Test("Debug utility for checking one IOB error", .enabled(if: false)) func debugSignleIobError() async throws {
  192. let algorithmComparison = try await HttpFiles.downloadFile(at: "/files/dd31e618-5023-40ca-ab7e-0fdd2475fbd9.2.json")
  193. let iobInputs = algorithmComparison.iobInput!
  194. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  195. try await checkFixedJsAgainstSwift(iobInputs: iobInputs)
  196. timeZoneForTests.resetTimezone()
  197. }
  198. @Test("Debug utility for checking iob-history", .enabled(if: false)) func debugIobHistory() async throws {
  199. let algorithmComparison = try await HttpFiles.downloadFile(at: "/files/dd31e618-5023-40ca-ab7e-0fdd2475fbd9.2.json")
  200. let iobInputs = algorithmComparison.iobInput!
  201. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  202. let swiftIobHistory = try IobHistory.calcTempTreatments(
  203. history: iobInputs.history.map { $0.computedEvent() },
  204. profile: iobInputs.profile,
  205. clock: iobInputs.clock,
  206. autosens: iobInputs.autosens,
  207. zeroTempDuration: nil
  208. )
  209. let openAps = OpenAPSFixed()
  210. let jsIobHistoryRaw = try await openAps.iobHistory(
  211. pumphistory: iobInputs.history,
  212. profile: JSONBridge.to(iobInputs.profile),
  213. clock: iobInputs.clock,
  214. autosens: JSONBridge.to(iobInputs.autosens),
  215. zeroTempDuration: RawJSON.null
  216. )
  217. let jsIobHistory = try JSONDecoder().decode([IobHistoryResult].self, from: jsIobHistoryRaw.rawJSON.data(using: .utf8)!)
  218. let encoder = JSONCoding.encoder
  219. var output = try encoder.encode(swiftIobHistory)
  220. var sharedDir = FileManager.default.temporaryDirectory
  221. var outputURL = sharedDir.appendingPathComponent("swift_treatments.json")
  222. print("Writing to: \(outputURL.path)")
  223. try output.write(to: outputURL)
  224. output = try encoder.encode(jsIobHistory)
  225. sharedDir = FileManager.default.temporaryDirectory
  226. outputURL = sharedDir.appendingPathComponent("js_treatments.json")
  227. print("Writing to: \(outputURL.path)")
  228. try output.write(to: outputURL)
  229. output = try encoder.encode(iobInputs)
  230. sharedDir = FileManager.default.temporaryDirectory
  231. outputURL = sharedDir.appendingPathComponent("js_iob_input_error.json")
  232. print("Writing to: \(outputURL.path)")
  233. try output.write(to: outputURL)
  234. checkHistoryConsistency(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  235. checkRunningBasal(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  236. timeZoneForTests.resetTimezone()
  237. }
  238. }