IobJsonTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. #expect(Bool(false), "Swift exception on IoB")
  58. }
  59. continue
  60. }
  61. // The JS implementation of IoB when the pump is suspend is so fundamentally
  62. // broken that I wasn't able to fix it in JS. So we'll just skip these, but I
  63. // verified them by hand and the Swift implementation appears to be correct
  64. if let mostRecentPumpEvent = iobInputs.history.filter({ $0.isExternal != true }).first {
  65. if mostRecentPumpEvent.type == .pumpSuspend
  66. {
  67. print("Skipping, known issue with JS and currently suspended pumps")
  68. continue
  69. }
  70. }
  71. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  72. try await checkFixedJsAgainstSwift(iobInputs: iobInputs)
  73. // try await checkBundleJsAgainstSwift(iobInputs: iobInputs)
  74. timeZoneForTests.resetTimezone()
  75. }
  76. }
  77. func checkFixedJsAgainstSwift(iobInputs: IobInputs) async throws {
  78. let openAps = OpenAPSFixed()
  79. let (iobResultSwift, _) = OpenAPSSwift.iob(
  80. pumphistory: iobInputs.history,
  81. profile: try JSONBridge.to(iobInputs.profile),
  82. clock: iobInputs.clock,
  83. autosens: try JSONBridge.to(iobInputs.autosens)
  84. )
  85. let iobResultJavascript = await openAps.iobJavascript(
  86. pumphistory: iobInputs.history,
  87. profile: try JSONBridge.to(iobInputs.profile),
  88. clock: iobInputs.clock,
  89. autosens: try JSONBridge.to(iobInputs.autosens)
  90. )
  91. let comparison = JSONCompare.createComparison(
  92. function: .iob,
  93. swift: iobResultSwift,
  94. swiftDuration: 0.1,
  95. javascript: iobResultJavascript,
  96. javascriptDuration: 0.1,
  97. iobInputs: nil,
  98. mealInputs: nil,
  99. autosensInputs: nil,
  100. determineBasalInputs: nil
  101. )
  102. if comparison.resultType == .valueDifference {
  103. print(comparison.differences!.prettyPrintedJSON!)
  104. }
  105. if comparison.resultType != .matching {
  106. print("REPLAY ERROR: Fixed JS didn't match")
  107. }
  108. #expect(comparison.resultType == .matching)
  109. }
  110. func checkBundleJsAgainstSwift(iobInputs: IobInputs) async throws {
  111. let openAps = OpenAPS(storage: BaseFileStorage(), tddStorage: MockTDDStorage())
  112. let (iobResultSwift, _) = OpenAPSSwift.iob(
  113. pumphistory: iobInputs.history,
  114. profile: try JSONBridge.to(iobInputs.profile),
  115. clock: iobInputs.clock,
  116. autosens: try JSONBridge.to(iobInputs.autosens)
  117. )
  118. let iobResultJavascript = await openAps.iobJavascript(
  119. pumphistory: iobInputs.history,
  120. profile: try JSONBridge.to(iobInputs.profile),
  121. clock: iobInputs.clock,
  122. autosens: try JSONBridge.to(iobInputs.autosens)
  123. )
  124. let comparison = JSONCompare.createComparison(
  125. function: .iob,
  126. swift: iobResultSwift,
  127. swiftDuration: 0.1,
  128. javascript: iobResultJavascript,
  129. javascriptDuration: 0.1,
  130. iobInputs: nil,
  131. mealInputs: nil,
  132. autosensInputs: nil,
  133. determineBasalInputs: nil
  134. )
  135. if comparison.resultType != .valueDifference {
  136. print("REPLAY ERROR: bundle JS did't produce value difference")
  137. }
  138. #expect(comparison.resultType == .valueDifference)
  139. }
  140. func checkHistoryConsistency(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  141. let swiftNetBolus = swiftTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  142. let jsNetBolus = jsTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  143. let swiftNetBasal = swiftTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  144. let jsNetBasal = jsTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  145. #expect(swiftNetBasal == jsNetBasal)
  146. #expect(swiftNetBolus == jsNetBolus)
  147. }
  148. func checkRunningBasal(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  149. let swiftBasals = swiftTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  150. let jsBasals = jsTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  151. #expect(swiftBasals.count == jsBasals.count)
  152. for (swift, js) in zip(swiftBasals, jsBasals) {
  153. #expect(Decimal(swift.date) == js.date!)
  154. #expect(swift.duration!.isWithin(0.01, of: js.duration!))
  155. #expect(swift.rate == js.rate)
  156. let start = js.date!
  157. let end = js.date! + js.duration! * 60 * 1000
  158. let swiftTempBolus = swiftTreatments
  159. .filter({ Decimal($0.date) >= start && Decimal($0.date) < end && $0.insulin != nil && $0.insulin! < 0.1 })
  160. .map({ $0.insulin! }).reduce(0, +)
  161. let jsTempBolus = jsTreatments
  162. .filter({ $0.date! >= start && $0.date! < end && $0.insulin != nil && $0.insulin! < 0.1 }).map({ $0.insulin! })
  163. .reduce(0, +)
  164. if swiftTempBolus != jsTempBolus {
  165. print("temp bolus @ \(swift.timestamp) mismatch swift: \(swiftTempBolus) js: \(jsTempBolus)")
  166. }
  167. #expect(swiftTempBolus == jsTempBolus)
  168. }
  169. }
  170. @Test("Debug utility for checking one IOB error", .enabled(if: false)) func debugSignleIobError() async throws {
  171. let algorithmComparison = try await HttpFiles.downloadFile(at: "/files/dd31e618-5023-40ca-ab7e-0fdd2475fbd9.2.json")
  172. let iobInputs = algorithmComparison.iobInput!
  173. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  174. try await checkFixedJsAgainstSwift(iobInputs: iobInputs)
  175. timeZoneForTests.resetTimezone()
  176. }
  177. @Test("Debug utility for checking iob-history", .enabled(if: false)) func debugIobHistory() async throws {
  178. let algorithmComparison = try await HttpFiles.downloadFile(at: "/files/dd31e618-5023-40ca-ab7e-0fdd2475fbd9.2.json")
  179. let iobInputs = algorithmComparison.iobInput!
  180. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  181. let swiftIobHistory = try IobHistory.calcTempTreatments(
  182. history: iobInputs.history.map { $0.computedEvent() },
  183. profile: iobInputs.profile,
  184. clock: iobInputs.clock,
  185. autosens: iobInputs.autosens,
  186. zeroTempDuration: nil
  187. )
  188. let openAps = OpenAPSFixed()
  189. let jsIobHistoryRaw = try await openAps.iobHistory(
  190. pumphistory: iobInputs.history,
  191. profile: JSONBridge.to(iobInputs.profile),
  192. clock: iobInputs.clock,
  193. autosens: JSONBridge.to(iobInputs.autosens),
  194. zeroTempDuration: RawJSON.null
  195. )
  196. let jsIobHistory = try JSONDecoder().decode([IobHistoryResult].self, from: jsIobHistoryRaw.rawJSON.data(using: .utf8)!)
  197. let encoder = JSONCoding.encoder
  198. var output = try encoder.encode(swiftIobHistory)
  199. var sharedDir = FileManager.default.temporaryDirectory
  200. var outputURL = sharedDir.appendingPathComponent("swift_treatments.json")
  201. print("Writing to: \(outputURL.path)")
  202. try output.write(to: outputURL)
  203. output = try encoder.encode(jsIobHistory)
  204. sharedDir = FileManager.default.temporaryDirectory
  205. outputURL = sharedDir.appendingPathComponent("js_treatments.json")
  206. print("Writing to: \(outputURL.path)")
  207. try output.write(to: outputURL)
  208. output = try encoder.encode(iobInputs)
  209. sharedDir = FileManager.default.temporaryDirectory
  210. outputURL = sharedDir.appendingPathComponent("js_iob_input_error.json")
  211. print("Writing to: \(outputURL.path)")
  212. try output.write(to: outputURL)
  213. checkHistoryConsistency(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  214. checkRunningBasal(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  215. timeZoneForTests.resetTimezone()
  216. }
  217. }