Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Sources/CodeCaps/MuseCodePluginView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,12 @@ struct MuseCodeMonitorPage: View {
if let report = model.museCodeReport {
row("Last Read", report.generatedAt.formatted(date: .omitted, time: .standard))
}
// Burn and standard-session alerts are independent findings:
// both stay visible when both are present.
if let alert = model.museCodeBurnAlert {
row("Burn Alert", alert.body)
} else if let alert = model.museCodeStandardSessionAlert {
}
if let alert = model.museCodeStandardSessionAlert {
row("Standard Session Alert", alert.body)
}
}
Expand Down
68 changes: 67 additions & 1 deletion Sources/QuotaCore/MuseCodeStandardSessionDetector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,29 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable {
/// here has never been observed with a model.
public private(set) var lastKnownModels: [String: String]

public init(lastKnownModels: [String: String] = [:]) {
/// When each tracked session was last observed, for staleness eviction.
/// Blobs persisted before the cap existed carry no stamps; those sessions
/// are kept and stamped on their next observation.
public private(set) var lastObservedAt: [String: Date]

/// A session not observed for this long is no longer live: the reader's
/// window is ninety minutes, so a full day absent means it ended.
public static let sessionStateTTL: TimeInterval = 24 * 3_600
/// Backstop bound on tracked sessions; the least recently observed are
/// evicted first.
public static let maxTrackedSessions = 512

public init(lastKnownModels: [String: String] = [:], lastObservedAt: [String: Date] = [:]) {
self.lastKnownModels = lastKnownModels
self.lastObservedAt = lastObservedAt
}

private enum CodingKeys: String, CodingKey { case lastKnownModels, lastObservedAt }

public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
lastKnownModels = try container.decode([String: String].self, forKey: .lastKnownModels)
lastObservedAt = try container.decodeIfPresent([String: Date].self, forKey: .lastObservedAt) ?? [:]
}

/// A contributor model is a model id ending in `-contributor`.
Expand Down Expand Up @@ -121,8 +142,10 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable {
public mutating func observe(
_ observations: [MuseCodeSessionModelObservation]
) -> [MuseCodeStandardSessionEvent] {
evictExpiredSessions(relativeTo: observations.map(\.observedAt).max())
Comment thread
swu-wise[bot] marked this conversation as resolved.
Resolved
var events: [MuseCodeStandardSessionEvent] = []
for observation in observations {
lastObservedAt[observation.sessionId] = observation.observedAt
Comment thread
swu-wise[bot] marked this conversation as resolved.
Resolved
guard let modelId = observation.modelId, !modelId.isEmpty else { continue }
let previous = lastKnownModels[observation.sessionId]
let wasContributor = previous.map { Self.isContributor(modelId: $0) } ?? false
Expand All @@ -133,9 +156,52 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable {
}
lastKnownModels[observation.sessionId] = modelId
}
trimToCap()
return events
}

/// Drops sessions whose last observation is older than the TTL. Runs
/// before the poll so an evicted session that returns fires once as
/// first-observed, which a day-long absence warrants. An empty poll
/// falls back to the wall clock so idle periods still advance expiry.
private mutating func evictExpiredSessions(relativeTo newest: Date?) {
let cutoff = (newest ?? Date()).addingTimeInterval(-Self.sessionStateTTL)
for (sessionId, observedAt) in lastObservedAt where observedAt < cutoff {
lastKnownModels.removeValue(forKey: sessionId)
lastObservedAt.removeValue(forKey: sessionId)
}
}

/// Trims the state to the cap by evicting the least recently observed.
/// Sessions without a liveness stamp predate the stamp field: any session
/// still live after the first poll of this version has been stamped, so
/// an unstamped entry is stale and sorts oldest, evicted first.
private mutating func trimToCap() {
if lastKnownModels.count > Self.maxTrackedSessions {
let overflow = lastKnownModels.count - Self.maxTrackedSessions
let oldest = lastKnownModels.keys.sorted {
(lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast)
}.prefix(overflow)
for sessionId in oldest {
lastKnownModels.removeValue(forKey: sessionId)
lastObservedAt.removeValue(forKey: sessionId)
}
}
// Model-less sessions never enter lastKnownModels, so without this
// their liveness stamps would accumulate unbounded until the TTL.
// Evict the oldest orphan stamps once the map itself passes the cap;
// stamps that back a tracked session are left alone.
let orphanOverflow = lastObservedAt.count - Self.maxTrackedSessions
if orphanOverflow > 0 {
let orphans = lastObservedAt.keys
.filter { lastKnownModels[$0] == nil }
.sorted { (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) }
for sessionId in orphans.prefix(orphanOverflow) {
lastObservedAt.removeValue(forKey: sessionId)
}
}
Comment thread
swu-wise[bot] marked this conversation as resolved.
Resolved
}
Comment thread
swu-wise[bot] marked this conversation as resolved.
Resolved

/// The sessions in one poll whose current model is standard, as events
/// with no firing semantics: the presence test the burn rule uses. A
/// standard session that has been running for an hour still counts here
Expand Down
15 changes: 15 additions & 0 deletions Tests/CodeCapsTests/MuseCodePluginTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,24 @@ private final class SpyAlertChannel: CodeCapsAlertChannel {

@MainActor
final class MuseCodePluginTests: XCTestCase {
private static var repoRoot: URL {
URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
}

private var suiteName = ""
private var defaults: UserDefaults!

func testBothMuseAlertsStayVisibleTogether() throws {
let source = try String(
contentsOf: Self.repoRoot.appendingPathComponent("Sources/CodeCaps/MuseCodePluginView.swift"),
encoding: .utf8)
XCTAssertFalse(source.contains("} else if let alert = model.museCodeStandardSessionAlert"),
"the standard-session alert must not hide behind a burn alert; both stay visible")
}

override func setUp() {
super.setUp()
suiteName = "MuseCodePluginTests." + UUID().uuidString
Expand Down
81 changes: 81 additions & 0 deletions Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,85 @@ final class MuseCodeStandardSessionDetectorTests: XCTestCase {
XCTAssertEqual(present.map(\.sessionId), ["s2"])
XCTAssertEqual(present.first?.modelId, standardModel)
}

func testSessionUnobservedPastTTLIsEvictedAndRefiresAsNew() {
var detector = MuseCodeStandardSessionDetector()
XCTAssertEqual(detector.observe([observation("s1", contributorModel)]).count, 0)
let later = MuseCodeStandardSessionDetector.sessionStateTTL + 600
let events = detector.observe([observation("s2", contributorModel, at: later),
observation("s1", standardModel, at: later)])
XCTAssertEqual(events.map(\.sessionId), ["s1"],
"a session silent past the TTL is evicted, so returning on a standard model fires as first-observed")
}

func testTrackedStateIsCappedByEvictingLeastRecentlyObserved() {
var detector = MuseCodeStandardSessionDetector()
for i in 0..<MuseCodeStandardSessionDetector.maxTrackedSessions {
_ = detector.observe([observation("s\(i)", contributorModel, at: TimeInterval(i))])
}
_ = detector.observe([observation("overflow", contributorModel,
at: TimeInterval(MuseCodeStandardSessionDetector.maxTrackedSessions + 1))])
XCTAssertEqual(detector.lastKnownModels.count, MuseCodeStandardSessionDetector.maxTrackedSessions)
XCTAssertNil(detector.lastKnownModels["s0"], "the least recently observed session is evicted first")
XCTAssertNotNil(detector.lastKnownModels["overflow"])
}

func testModelLessOrphanStampsAreCappedToo() {
var detector = MuseCodeStandardSessionDetector()
let cap = MuseCodeStandardSessionDetector.maxTrackedSessions
for i in 0..<(cap + 100) {
_ = detector.observe([observation("orphan\(i)", nil, at: TimeInterval(i))])
}
XCTAssertEqual(detector.lastKnownModels.count, 0,
"model-less sessions still record no model state")
XCTAssertEqual(detector.lastObservedAt.count, cap,
"orphan liveness stamps are capped like tracked sessions")
XCTAssertNil(detector.lastObservedAt["orphan0"],
"the least recently observed orphan stamp is evicted first")
XCTAssertNotNil(detector.lastObservedAt["orphan\(cap + 99)"])
}

func testModelLessPollsKeepASessionAlive() {
var detector = MuseCodeStandardSessionDetector()
XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1)
let ttl = MuseCodeStandardSessionDetector.sessionStateTTL
// Model-less polls every ten minutes for over a day: the session is
// present, so its liveness advances even without a model reading.
var t = TimeInterval(600)
while t <= ttl + 600 {
XCTAssertTrue(detector.observe([observation("s1", nil, at: t)]).isEmpty)
t += 600
}
XCTAssertTrue(detector.observe([observation("s1", standardModel, at: t)]).isEmpty,
"a session kept alive by model-less polls is not evicted, so its model returning does not refire")
}

func testEmptyPollStillEvictsSessionsPastTTL() {
var detector = MuseCodeStandardSessionDetector()
let stale = Date().addingTimeInterval(-MuseCodeStandardSessionDetector.sessionStateTTL - 600)
_ = detector.observe([MuseCodeSessionModelObservation(sessionId: "s1", modelId: contributorModel,
observedAt: stale)])
XCTAssertEqual(detector.lastKnownModels.count, 1)
_ = detector.observe([])
XCTAssertEqual(detector.lastKnownModels.count, 0,
"an idle poll still advances expiry against the wall clock")
}

func testUnstampedLegacySessionsEvictBeforeStampedOnesAtCap() throws {
let legacy = try JSONSerialization.data(withJSONObject: ["lastKnownModels": ["old": standardModel]])
var detector = try JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: legacy)
for i in 0..<MuseCodeStandardSessionDetector.maxTrackedSessions {
_ = detector.observe([observation("s\(i)", contributorModel, at: TimeInterval(i + 1))])
}
XCTAssertEqual(detector.lastKnownModels.count, MuseCodeStandardSessionDetector.maxTrackedSessions)
XCTAssertNil(detector.lastKnownModels["old"],
"the unstamped legacy session sorts oldest and is evicted first")
XCTAssertNotNil(detector.lastKnownModels["s0"])
}

func testLegacyPersistedStateWithoutTimestampsStillDecodes() throws {
let legacy = try JSONSerialization.data(withJSONObject: ["lastKnownModels": ["s1": standardModel]])
let detector = try JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: legacy)
XCTAssertEqual(detector.lastKnownModels["s1"], standardModel)
}
}
Loading