From 8ec7a45908c1254a30700f28804451e18e48bab7 Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:51:57 +0000 Subject: [PATCH 1/6] CC-390: cache parsed snapshot segments across refresh cycles (f6) --- Sources/QuotaCore/MuseCodeSessionReader.swift | 54 +++++++++++++++++++ .../MuseCodeSessionReaderTests.swift | 37 +++++++++++++ 2 files changed, 91 insertions(+) diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift index 078d9fcc..d6bafaf0 100644 --- a/Sources/QuotaCore/MuseCodeSessionReader.swift +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -171,6 +171,51 @@ public struct MuseCodeSessionResult: Equatable, Sendable { /// snapshot files directly (the newest snapshot in a directory is the one /// HEAD.json names), which covers both the latest-segment and the /// segment-summed views the fleet's surveys validated. +/// A process-wide parse cache for snapshot segments. The session stores +/// write each snapshot once and rotate by replacement, so (path, mtime, size) +/// pins the content: an unchanged snapshot never needs a second read and +/// parse across the one-minute refresh cycles. +final class MuseCodeSnapshotSegmentCache: @unchecked Sendable { + private let lock = NSLock() + private var entries: [String: MuseCodeTokenSegment] = [:] + private let cap = 8_192 + private var hits = 0 + private var misses = 0 + + func segment(sessionId: String, url: URL, modified: Date, size: Int, + parse: () -> MuseCodeTokenSegment?) -> MuseCodeTokenSegment? { + let key = url.path + "|" + String(modified.timeIntervalSince1970) + "|" + String(size) + lock.lock() + if let cached = entries[key] { + hits += 1 + lock.unlock() + return cached + } + misses += 1 + lock.unlock() + guard let parsed = parse() else { return nil } + lock.lock() + if entries.count >= cap { entries.removeAll(keepingCapacity: true) } + entries[key] = parsed + lock.unlock() + return parsed + } + + func reset() { + lock.lock() + entries.removeAll() + hits = 0 + misses = 0 + lock.unlock() + } + + func stats() -> (hits: Int, misses: Int) { + lock.lock() + defer { lock.unlock() } + return (hits, misses) + } +} + public struct MuseCodeSessionReader: Sendable { public static let storeRelativePath = ".local/share/muse/sessions/.msp-view-g6" public static let windowMinutes = [60, 90] @@ -180,6 +225,9 @@ public struct MuseCodeSessionReader: Sendable { private static let maxSnapshotBytes = 33_554_432 private static let futureTolerance: TimeInterval = 120 + /// Shared across readers so the one-minute refresh reuses parses. + static let snapshotSegmentCache = MuseCodeSnapshotSegmentCache() + private let homeDirectory: URL private let now: @Sendable () -> Date @@ -324,6 +372,12 @@ public struct MuseCodeSessionReader: Sendable { } private static func segment(sessionId: String, url: URL, modified: Date, size: Int) -> MuseCodeTokenSegment? { + snapshotSegmentCache.segment(sessionId: sessionId, url: url, modified: modified, size: size) { + parseSegment(sessionId: sessionId, url: url, modified: modified, size: size) + } + } + + private static func parseSegment(sessionId: String, url: URL, modified: Date, size: Int) -> MuseCodeTokenSegment? { guard size > 0, size <= maxSnapshotBytes, let data = try? Data(contentsOf: url), let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift index 78caa4d7..4cfa7f31 100644 --- a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -181,6 +181,43 @@ final class MuseCodeSessionReaderTests: XCTestCase { XCTAssertEqual(observation?.segmentKey, "a3") } + func testReaderServesUnchangedSnapshotsFromParseCache() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 2_000, first: "a1", last: "b1"), + modified: now.addingTimeInterval(-10 * 60)) + let cache = MuseCodeSessionReader.snapshotSegmentCache + cache.reset() + let reader = MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + _ = reader.read() + let missesAfterFirst = cache.stats().misses + XCTAssertGreaterThan(missesAfterFirst, 0) + let again = reader.read() + XCTAssertEqual(cache.stats().misses, missesAfterFirst, + "a second read of an unchanged store parses nothing again") + XCTAssertNil(again.issue) + } + + func testReaderReparsesASnapshotRewrittenInPlace() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 2_000, first: "a1", last: "b1"), + modified: now.addingTimeInterval(-10 * 60)) + let cache = MuseCodeSessionReader.snapshotSegmentCache + cache.reset() + let reader = MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + let first = try XCTUnwrap(reader.read().report) + XCTAssertEqual(first.window(minutes: 90)?.totalTokens, 2_000) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 5_000, first: "a1", last: "b1"), + modified: now.addingTimeInterval(-5 * 60)) + let second = try XCTUnwrap(reader.read().report) + XCTAssertEqual(second.window(minutes: 90)?.totalTokens, 5_000, + "a rewritten snapshot has a new cache key, so the new content is parsed") + } + func testCurrentModelUsesNullHeadWithoutBackfillingAndPreservesHistoricalUsage() throws { let home = try makeHome() defer { try? FileManager.default.removeItem(at: home) } From ff9084974a388be826581b8530098c79314c1e34 Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:34:29 +0000 Subject: [PATCH 2/6] CC-390: evict one parse-cache entry on overflow instead of clearing all (Kody round 1) --- Sources/QuotaCore/MuseCodeSessionReader.swift | 7 ++++- .../MuseCodeSessionReaderTests.swift | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift index d6bafaf0..21b95411 100644 --- a/Sources/QuotaCore/MuseCodeSessionReader.swift +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -195,7 +195,12 @@ final class MuseCodeSnapshotSegmentCache: @unchecked Sendable { lock.unlock() guard let parsed = parse() else { return nil } lock.lock() - if entries.count >= cap { entries.removeAll(keepingCapacity: true) } + // Overflow evicts a single entry rather than clearing the map: a + // working set over the cap then degrades to partial misses instead + // of turning the next scan into all misses and full re-parses. + if entries[key] == nil && entries.count >= cap, let victim = entries.keys.first { + entries.removeValue(forKey: victim) + } entries[key] = parsed lock.unlock() return parsed diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift index 4cfa7f31..81c4be0d 100644 --- a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -199,6 +199,33 @@ final class MuseCodeSessionReaderTests: XCTestCase { XCTAssertNil(again.issue) } + func testParseCacheOverflowEvictsOneEntryInsteadOfClearingAll() { + let cache = MuseCodeSessionReader.snapshotSegmentCache + cache.reset() + defer { cache.reset() } + let cap = 8_192 + let stamp = Date(timeIntervalSince1970: 1_700_000_000) + let parse: () -> MuseCodeTokenSegment? = { + MuseCodeTokenSegment(sessionId: "s", modelId: "m", totalTokens: 1, observedAt: stamp) + } + for i in 0.. Date: Tue, 10 Nov 2026 06:37:48 +0000 Subject: [PATCH 3/6] CC-390: pin parse-cache key with file resource identity (Kody cache-key finding) --- Sources/QuotaCore/MuseCodeSessionReader.swift | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift index 21b95411..67c6cb83 100644 --- a/Sources/QuotaCore/MuseCodeSessionReader.swift +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -172,8 +172,10 @@ public struct MuseCodeSessionResult: Equatable, Sendable { /// HEAD.json names), which covers both the latest-segment and the /// segment-summed views the fleet's surveys validated. /// A process-wide parse cache for snapshot segments. The session stores -/// write each snapshot once and rotate by replacement, so (path, mtime, size) -/// pins the content: an unchanged snapshot never needs a second read and +/// write each snapshot once under a fresh UUID name and rotate by replacement +/// (no reused snapshot names in the live store), and the key also carries the +/// file's resource identity, so even a path reused after replacement cannot +/// serve stale content: an unchanged snapshot never needs a second read and /// parse across the one-minute refresh cycles. final class MuseCodeSnapshotSegmentCache: @unchecked Sendable { private let lock = NSLock() @@ -184,7 +186,13 @@ final class MuseCodeSnapshotSegmentCache: @unchecked Sendable { func segment(sessionId: String, url: URL, modified: Date, size: Int, parse: () -> MuseCodeTokenSegment?) -> MuseCodeTokenSegment? { - let key = url.path + "|" + String(modified.timeIntervalSince1970) + "|" + String(size) + // The resource identifier is inode-based on APFS: rotation by + // replacement yields a new identity even if a reused path kept the + // same size and mtime, so the key pins content identity, not just + // metadata. One extra stat per call, far cheaper than a re-parse. + let fileId = (try? url.resourceValues(forKeys: [.fileResourceIdentifierKey])) + .flatMap { $0.fileResourceIdentifier.map { String(describing: $0) } } ?? "" + let key = url.path + "|" + fileId + "|" + String(modified.timeIntervalSince1970) + "|" + String(size) lock.lock() if let cached = entries[key] { hits += 1 From da8c42e5993139da8fb131caed0bb4c2a9c8627f Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:44:08 +0000 Subject: [PATCH 4/6] CC-390: regression-test parse-cache replacement identity; uncached inode+birthtime key --- Sources/QuotaCore/MuseCodeSessionReader.swift | 17 ++++++---- .../MuseCodeSessionReaderTests.swift | 34 +++++++++++++++++++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift index 67c6cb83..998bca0f 100644 --- a/Sources/QuotaCore/MuseCodeSessionReader.swift +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -186,12 +186,17 @@ final class MuseCodeSnapshotSegmentCache: @unchecked Sendable { func segment(sessionId: String, url: URL, modified: Date, size: Int, parse: () -> MuseCodeTokenSegment?) -> MuseCodeTokenSegment? { - // The resource identifier is inode-based on APFS: rotation by - // replacement yields a new identity even if a reused path kept the - // same size and mtime, so the key pins content identity, not just - // metadata. One extra stat per call, far cheaper than a re-parse. - let fileId = (try? url.resourceValues(forKeys: [.fileResourceIdentifierKey])) - .flatMap { $0.fileResourceIdentifier.map { String(describing: $0) } } ?? "" + // Inode number plus creation date distinguish a replacement from + // the file it replaced even when the path, size, and mtime are + // identical. attributesOfItem is used instead of URL resource + // values because a URL instance caches its values, which could pin + // the replaced file's identity. One extra stat per call, far + // cheaper than a re-parse. + let attrs = try? FileManager.default.attributesOfItem(atPath: url.path) + let fileId = attrs.map { + String(describing: $0[.systemFileNumber] ?? 0) + "@" + + String((($0[.creationDate] as? Date) ?? .distantPast).timeIntervalSince1970) + } ?? "" let key = url.path + "|" + fileId + "|" + String(modified.timeIntervalSince1970) + "|" + String(size) lock.lock() if let cached = entries[key] { diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift index 81c4be0d..69f72c83 100644 --- a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -226,6 +226,40 @@ final class MuseCodeSessionReaderTests: XCTestCase { "overflow evicts one entry, keeping the rest of the working set cached") } + func testParseCacheReparseesReplacedFileWithIdenticalMetadata() throws { + // Rotation by replacement with a reused path, same size, and the same + // mtime: the creation-date component in the key must still force a + // re-parse. mtime is set to a FUTURE stamp on both files, because + // backdating mtime on macOS also drags birthtime down with it, which + // would make the files genuinely indistinguishable by metadata. + let cache = MuseCodeSessionReader.snapshotSegmentCache + cache.reset() + defer { cache.reset() } + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("cache-replacement-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + let url = dir.appendingPathComponent("snapshot-1.json") + let stamp = Date(timeIntervalSince1970: 2_000_000_000) + var parses = 0 + let parse: () -> MuseCodeTokenSegment? = { + parses += 1 + return MuseCodeTokenSegment(sessionId: "s", modelId: "m", + totalTokens: parses, observedAt: stamp) + } + try Data(repeating: 0x61, count: 64).write(to: url) + try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: url.path) + let first = cache.segment(sessionId: "s", url: url, modified: stamp, size: 64, parse: parse) + XCTAssertEqual(first?.totalTokens, 1) + // Replace the file at the same path, then set the same mtime. + try FileManager.default.removeItem(at: url) + try Data(repeating: 0x62, count: 64).write(to: url) + try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: url.path) + let second = cache.segment(sessionId: "s", url: url, modified: stamp, size: 64, parse: parse) + XCTAssertEqual(parses, 2, "a replacement with identical path/size/mtime must not hit the old entry") + XCTAssertEqual(second?.totalTokens, 2, "the replacement's own content is returned, not the stale entry") + } + func testReaderReparsesASnapshotRewrittenInPlace() throws { let home = try makeHome() defer { try? FileManager.default.removeItem(at: home) } From c5d0c62e996f5894298d5a425a5290b31f57c412 Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:47:05 +0000 Subject: [PATCH 5/6] CC-390: collect snapshot file identity in the enumeration pass (Kody hot-loop stat finding) --- Sources/QuotaCore/MuseCodeSessionReader.swift | 42 ++++++++++--------- .../MuseCodeSessionReaderTests.swift | 20 ++++++--- 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift index 998bca0f..01cc0cfd 100644 --- a/Sources/QuotaCore/MuseCodeSessionReader.swift +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -184,19 +184,13 @@ final class MuseCodeSnapshotSegmentCache: @unchecked Sendable { private var hits = 0 private var misses = 0 + /// `fileId` carries the caller's inode@birthtime identity for the file, + /// collected in the same enumeration pass as its mtime and size so the + /// hot loop stats each snapshot once. It distinguishes a replacement + /// from the file it replaced even when path, size, and mtime collide. func segment(sessionId: String, url: URL, modified: Date, size: Int, + fileId: String, parse: () -> MuseCodeTokenSegment?) -> MuseCodeTokenSegment? { - // Inode number plus creation date distinguish a replacement from - // the file it replaced even when the path, size, and mtime are - // identical. attributesOfItem is used instead of URL resource - // values because a URL instance caches its values, which could pin - // the replaced file's identity. One extra stat per call, far - // cheaper than a re-parse. - let attrs = try? FileManager.default.attributesOfItem(atPath: url.path) - let fileId = attrs.map { - String(describing: $0[.systemFileNumber] ?? 0) + "@" + - String((($0[.creationDate] as? Date) ?? .distantPast).timeIntervalSince1970) - } ?? "" let key = url.path + "|" + fileId + "|" + String(modified.timeIntervalSince1970) + "|" + String(size) lock.lock() if let cached = entries[key] { @@ -280,10 +274,15 @@ public struct MuseCodeSessionReader: Sendable { let sessionId = directory.lastPathComponent guard let files = try? FileManager.default.contentsOfDirectory( at: directory, - includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey]) else { continue } - let dated: [(url: URL, modified: Date, size: Int)] = files.map { url in - let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey]) - return (url, values?.contentModificationDate ?? .distantPast, values?.fileSize ?? 0) + includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey, + .fileResourceIdentifierKey, .creationDateKey]) else { continue } + let dated: [(url: URL, modified: Date, size: Int, fileId: String)] = files.map { url in + let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey, + .fileResourceIdentifierKey, .creationDateKey]) + let fileId = values?.fileResourceIdentifier.map { String(describing: $0) } ?? "" + let birth = values?.creationDate.map { String($0.timeIntervalSince1970) } ?? "" + return (url, values?.contentModificationDate ?? .distantPast, values?.fileSize ?? 0, + fileId + "@" + birth) } // A session counts as active in a window when any of its files — // HEAD.json included — was written inside it, the same activity @@ -309,7 +308,7 @@ public struct MuseCodeSessionReader: Sendable { selected.append(headSnapshot) } let snapshots = selected.sorted { $0.modified < $1.modified } - let currentSnapshot: (url: URL, modified: Date, size: Int)? + let currentSnapshot: (url: URL, modified: Date, size: Int, fileId: String)? if let headId { // A valid HEAD id is authoritative. If its file is absent, the // current model is unknown; never substitute an older model. @@ -329,7 +328,8 @@ public struct MuseCodeSessionReader: Sendable { var parsed: [(snapshotId: String?, segment: MuseCodeTokenSegment)] = [] for snapshot in snapshots { if let segment = Self.segment(sessionId: sessionId, url: snapshot.url, - modified: snapshot.modified, size: snapshot.size) { + modified: snapshot.modified, size: snapshot.size, + fileId: snapshot.fileId) { segments.append(segment) parsed.append((Self.snapshotId(from: snapshot.url), segment)) } @@ -362,7 +362,7 @@ public struct MuseCodeSessionReader: Sendable { return String(name.dropFirst("snapshot-".count).dropLast(".json".count)) } - private static func headSnapshotId(in files: [(url: URL, modified: Date, size: Int)]) -> String? { + private static func headSnapshotId(in files: [(url: URL, modified: Date, size: Int, fileId: String)]) -> String? { guard let head = files.first(where: { $0.url.lastPathComponent == "HEAD.json" }), head.size > 0, head.size <= 1_048_576, let data = try? Data(contentsOf: head.url), @@ -389,8 +389,10 @@ public struct MuseCodeSessionReader: Sendable { ?? .distantPast } - private static func segment(sessionId: String, url: URL, modified: Date, size: Int) -> MuseCodeTokenSegment? { - snapshotSegmentCache.segment(sessionId: sessionId, url: url, modified: modified, size: size) { + private static func segment(sessionId: String, url: URL, modified: Date, size: Int, + fileId: String) -> MuseCodeTokenSegment? { + snapshotSegmentCache.segment(sessionId: sessionId, url: url, modified: modified, + size: size, fileId: fileId) { parseSegment(sessionId: sessionId, url: url, modified: modified, size: size) } } diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift index 69f72c83..a90a4c78 100644 --- a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -210,15 +210,15 @@ final class MuseCodeSessionReaderTests: XCTestCase { } for i in 0.. String { + let attrs = try? FileManager.default.attributesOfItem(atPath: url.path) + return attrs.map { + String(describing: $0[.systemFileNumber] ?? 0) + "@" + + String((($0[.creationDate] as? Date) ?? .distantPast).timeIntervalSince1970) + } ?? "" + } + func testParseCacheReparseesReplacedFileWithIdenticalMetadata() throws { // Rotation by replacement with a reused path, same size, and the same // mtime: the creation-date component in the key must still force a @@ -249,13 +257,15 @@ final class MuseCodeSessionReaderTests: XCTestCase { } try Data(repeating: 0x61, count: 64).write(to: url) try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: url.path) - let first = cache.segment(sessionId: "s", url: url, modified: stamp, size: 64, parse: parse) + let first = cache.segment(sessionId: "s", url: url, modified: stamp, size: 64, + fileId: Self.snapshotFileId(at: url), parse: parse) XCTAssertEqual(first?.totalTokens, 1) // Replace the file at the same path, then set the same mtime. try FileManager.default.removeItem(at: url) try Data(repeating: 0x62, count: 64).write(to: url) try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: url.path) - let second = cache.segment(sessionId: "s", url: url, modified: stamp, size: 64, parse: parse) + let second = cache.segment(sessionId: "s", url: url, modified: stamp, size: 64, + fileId: Self.snapshotFileId(at: url), parse: parse) XCTAssertEqual(parses, 2, "a replacement with identical path/size/mtime must not hit the old entry") XCTAssertEqual(second?.totalTokens, 2, "the replacement's own content is returned, not the stale entry") } From 358895f3f20b8142192191c282150ba5472724ff Mon Sep 17 00:00:00 2001 From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:48:37 +0000 Subject: [PATCH 6/6] CC-390: e2e regression - reader reparses a same-metadata snapshot replacement --- .../MuseCodeSessionReaderTests.swift | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift index a90a4c78..04feb4e9 100644 --- a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -270,6 +270,38 @@ final class MuseCodeSessionReaderTests: XCTestCase { XCTAssertEqual(second?.totalTokens, 2, "the replacement's own content is returned, not the stale entry") } + func testReaderReparsesASnapshotReplacedWithIdenticalMetadata() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + let stamp = now.addingTimeInterval(-10 * 60) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 2_000, first: "a1", last: "b1"), + modified: stamp) + let cache = MuseCodeSessionReader.snapshotSegmentCache + cache.reset() + let reader = MuseCodeSessionReader(homeDirectory: home, now: { self.now }) + let first = try XCTUnwrap(reader.read().report) + XCTAssertEqual(first.window(minutes: 90)?.totalTokens, 2_000) + let url = home.appendingPathComponent( + ".local/share/muse/sessions/.msp-view-g6/session-a/snapshot-1.json") + let sizeBefore = try XCTUnwrap( + (try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? Int) + // Rotation by replacement: a new file at the same path with identical + // size and mtime - only the file identity in the cache key + // distinguishes it, and the identity must arrive through the reader's + // own enumeration, not a caller bypass. + try FileManager.default.removeItem(at: url) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 5_000, first: "a1", last: "b1"), + modified: stamp) + let sizeAfter = try XCTUnwrap( + (try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? Int) + XCTAssertEqual(sizeBefore, sizeAfter, "test precondition: the replacement has identical size") + let second = try XCTUnwrap(reader.read().report) + XCTAssertEqual(second.window(minutes: 90)?.totalTokens, 5_000, + "a replacement with identical path/size/mtime is re-parsed through the reader's own enumeration") + } + func testReaderReparsesASnapshotRewrittenInPlace() throws { let home = try makeHome() defer { try? FileManager.default.removeItem(at: home) }