Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Tests/DocLocalModelsTests/EditorMemoryGovernorTests.swift10// Description : Tests of the editor-aware memory governor: the pure budget11// and decision rules (editor reserve, heavy document work,12// memory pressure), the heavy-work hook and its waiters, and13// the unloading on pressure.14// Module : DocLocalModelsTests15// Repository : https://git.spboucher.ai/orix-docs16// Created : 2026-11-2217// Last Modified : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AstraCore92@testable import AstraLocal93@testable import DocLocalModels94import Foundation95import Testing9697private let gb: Int64 = 1 << 3098private let base = MemoryGovernor(platform: .macOS)99private let policy = EditorMemoryPolicy.standard100private func reading(_ physical: Int64 = 48, available: Int64? = 30) -> MemoryReading {101 MemoryReading(physicalBytes: physical * gb, availableBytes: available.map { $0 * gb })102}103private func profile(_ weightsGB: Double, context: Int = 32_768) -> ModelMemoryProfile {104 ModelMemoryProfile(weightsBytes: Int64(weightsGB * Double(gb)), kvBytesPerToken: 50_000, modelContextLength: context)105}106private func decide(_ weightsGB: Double, reading r: MemoryReading = reading(), pressure: MemoryPressureLevel = .normal, heavy: Bool = false) -> ModelLoadDecision {107 EditorMemoryGovernor.decide(profile: profile(weightsGB), context: 8_192, policy: policy, base: base, reading: r, pressure: pressure, heavyWork: heavy, modelName: "Test model")108}109110@Suite struct EditorMemoryPolicyTests {111 @Test func theEditorReserveIsAFloorOrAShare() {112 #expect(policy.editorReserve(physicalBytes: 16 * gb) == 3 * gb) // floor113 #expect(policy.editorReserve(physicalBytes: 48 * gb) == Int64(4.8 * Double(gb))) // 10 %114 #expect(policy.editorReserve(physicalBytes: 96 * gb) == Int64(9.6 * Double(gb)))115 }116117 @Test func theBudgetIsAstrasBudgetMinusTheReserve() {118 let r = reading(48, available: 40)119 let astra = base.budget(r) // min(48 × 0.70, 40 × 0.85) = 33.6 GB120 let ours = EditorMemoryGovernor.modelBudget(policy: policy, base: base, reading: r, pressure: .normal, heavyWork: false)121 #expect(ours < astra)122 // physical side: 33.6 − 4.8 = 28.8 ; available side: (40 − 4.8) × 0.85 = 29.92 → 28.8123 #expect(abs(Double(ours) / Double(gb) - 28.8) < 0.01)124 // little available memory: that side wins125 let tight = EditorMemoryGovernor.modelBudget(policy: policy, base: base, reading: reading(48, available: 10), pressure: .normal, heavyWork: false)126 #expect(abs(Double(tight) / Double(gb) - (10 - 4.8) * 0.85) < 0.01)127 // no figure for available memory: the physical side alone128 let unknown = EditorMemoryGovernor.modelBudget(policy: policy, base: base, reading: reading(48, available: nil), pressure: .normal, heavyWork: false)129 #expect(abs(Double(unknown) / Double(gb) - 28.8) < 0.01)130 }131132 @Test func heavyWorkAndPressureReduceTheBudgetAndCriticalZeroesIt() {133 let r = reading(48, available: 40)134 func budget(_ p: MemoryPressureLevel, _ heavy: Bool) -> Int64 { EditorMemoryGovernor.modelBudget(policy: policy, base: base, reading: r, pressure: p, heavyWork: heavy) }135 #expect(budget(.normal, true) == budget(.normal, false) - 2 * gb)136 #expect(budget(.warning, false) == budget(.normal, false) / 2)137 #expect(budget(.critical, false) == 0 && budget(.critical, true) == 0)138 // never negative, even on a Mac smaller than the reserve139 #expect(EditorMemoryGovernor.modelBudget(policy: policy, base: base, reading: reading(4, available: 1), pressure: .normal, heavyWork: true) == 0)140 }141142 @Test func aSmallModelIsAllowedWithTheNumbers() {143 let d = decide(1)144 #expect(d.verdict == .allow && d.mayLoadNow && d.fit.mayLoad)145 #expect(d.reason.contains("Test model") && d.reason.contains("estimate"))146 #expect(d.editorReserveBytes == policy.editorReserve(physicalBytes: 48 * gb))147 #expect(d.fit.budgetBytes == d.budgetBytes)148 #expect(d.fit.estimatedNeedBytes == Int64(1 * gb) + 50_000 * 8_192 + base.overheadBytes)149 }150151 @Test func aModelThatFitsAstraButNotNextToTheEditorIsRefused() {152 let r = reading(48, available: 40)153 // 30 GB of weights: inside Astra's 33.6 GB budget for this Mac, outside the 28.8 GB the editor leaves.154 #expect(base.verdict(for: profile(30), context: 8_192, reading: r).mayLoad)155 let d = decide(30, reading: r)156 #expect(d.verdict == .refuse && !d.mayLoadNow)157 #expect(d.reason.contains("is kept for it"))158 }159160 @Test func heavyWorkDefersWhatWouldOtherwiseFit() {161 let r = reading(48, available: 40)162 // 27.5 GB: fits in 28.8 GB, not in 26.8 GB while an export runs163 #expect(decide(27.5, reading: r, heavy: false).verdict == .allow)164 let d = decide(27.5, reading: r, heavy: true)165 #expect(d.verdict == .deferUntilDocumentWorkEnds && !d.mayLoadNow && d.heavyDocumentWork)166 #expect(d.reason.contains("deferred"))167 // a small model is not held back by an export168 #expect(decide(1, reading: r, heavy: true).verdict == .allow)169 // a model that would not fit anyway is refused, not deferred170 #expect(decide(40, reading: r, heavy: true).verdict == .refuse)171 }172173 @Test func pressureRefuses() {174 #expect(decide(1, pressure: .critical).verdict == .refuse)175 #expect(decide(1, pressure: .critical).reason.contains("critically low"))176 #expect(decide(20, pressure: .normal).verdict == .allow)177 let warned = decide(20, pressure: .warning)178 #expect(warned.verdict == .refuse && warned.reason.contains("under memory pressure"))179 #expect(decide(1, pressure: .warning).verdict == .allow)180 }181182 @Test func pressureLevelsAreOrdered() {183 #expect(MemoryPressureLevel.normal < .warning && MemoryPressureLevel.warning < .critical)184 }185186 @Test func theSystemReadingHasAnAvailableFigureOnMacOS() {187 let r = EditorMemoryGovernor.systemReading()188 #expect(r.physicalBytes == Int64(ProcessInfo.processInfo.physicalMemory))189 let available = r.availableBytes190 #expect(available != nil)191 if let available { #expect(available > 0 && available <= r.physicalBytes) }192 }193}194195@Suite struct EditorMemoryGovernorActorTests {196 func governor(_ r: MemoryReading = reading(48, available: 40)) -> EditorMemoryGovernor { EditorMemoryGovernor(memory: { r }) }197198 @Test func heavyWorkIsTrackedByToken() async {199 let g = governor()200 let idle = await g.modelBudgetBytes()201 let a = await g.noteHeavyDocumentWork(.begin, label: "PDF export")202 let b = await g.noteHeavyDocumentWork(.begin, label: "Import")203 #expect(await g.isHeavyDocumentWorkInProgress)204 #expect(await g.state().heavyWork == ["PDF export", "Import"])205 #expect(await g.modelBudgetBytes() == idle - 2 * gb)206 await g.noteHeavyDocumentWork(.end, token: a)207 #expect(await g.state().heavyWork == ["Import"])208 await g.noteHeavyDocumentWork(.end, token: a) // ending twice changes nothing209 #expect(await g.isHeavyDocumentWorkInProgress)210 await g.noteHeavyDocumentWork(.end, token: b)211 #expect(await g.isHeavyDocumentWorkInProgress == false)212 #expect(await g.modelBudgetBytes() == idle)213 }214215 @Test func endingByLabelWorksWhenTheTokenWasLost() async {216 let g = governor()217 await g.noteHeavyDocumentWork(.begin, label: "PDF export")218 await g.noteHeavyDocumentWork(.end, label: "Something else")219 #expect(await g.isHeavyDocumentWorkInProgress)220 await g.noteHeavyDocumentWork(.end, label: "PDF export")221 #expect(await g.isHeavyDocumentWorkInProgress == false)222 }223224 @Test func waitersResumeWhenTheLastWorkEnds() async throws {225 let g = governor()226 await g.waitForDocumentWork() // nothing in progress: returns at once227 let a = await g.noteHeavyDocumentWork(.begin, label: "PDF export")228 let b = await g.noteHeavyDocumentWork(.begin, label: "Import")229 let waiter = Task { await g.waitForDocumentWork(); return await g.isHeavyDocumentWorkInProgress }230 try await Task.sleep(nanoseconds: 30_000_000)231 await g.noteHeavyDocumentWork(.end, token: a)232 try await Task.sleep(nanoseconds: 30_000_000)233 #expect(!waiter.isCancelled)234 await g.noteHeavyDocumentWork(.end, token: b)235 #expect(await waiter.value == false)236 }237238 @Test func withHeavyDocumentWorkEndsAlsoWhenTheWorkThrows() async {239 let g = governor()240 struct Boom: Error {}241 let value = await g.withHeavyDocumentWork("Export") { 42 }242 #expect(value == 42)243 await #expect(throws: Boom.self) { try await g.withHeavyDocumentWork("Export") { throw Boom() } }244 #expect(await g.isHeavyDocumentWorkInProgress == false)245 }246247 @Test func pressureIsRememberedAndUnloadersAreCalled() async {248 let g = governor()249 let calls = Calls()250 await g.onPressure { critical in await calls.add(critical) }251 await g.handlePressure(.warning)252 #expect(await g.currentPressure == .warning)253 #expect(await calls.values == [false])254 #expect(await g.decision(for: profile(20)).verdict == .refuse)255 await g.handlePressure(.critical)256 #expect(await calls.values == [false, true])257 #expect(await g.modelBudgetBytes() == 0)258 #expect(await g.state().lastUnloadReason?.contains("critical") == true)259 await g.handlePressure(.normal)260 #expect(await calls.values == [false, true]) // going back to normal unloads nothing261 #expect(await g.decision(for: profile(20)).verdict == .allow)262 }263264 @Test func statesAreBroadcast() async {265 let g = governor()266 var iterator = await g.states().makeAsyncIterator()267 #expect(await iterator.next()?.pressure == .normal)268 await g.handlePressure(.warning)269 #expect(await iterator.next()?.pressure == .warning)270 }271272 @Test func recommendedContextShrinksWithTheBudget() async {273 let roomy = governor(reading(48, available: 40))274 let p = ModelMemoryProfile(weightsBytes: 20 * gb, kvBytesPerToken: 300_000, modelContextLength: 32_768)275 #expect(await roomy.recommendedContext(for: p) == 16_384) // 20 + 0.3 MB × 16k = 24.9 GB fits in 28.8; 32k (29.8 GB) does not276 let tight = governor(reading(48, available: 31))277 #expect(await tight.recommendedContext(for: p) == 4_096)278 let none = governor(reading(16, available: 6))279 #expect(await none.recommendedContext(for: p) == nil)280 }281282 @Test func monitoringStartsAndStopsWithoutIncident() async {283 let g = governor()284 await g.startMonitoring(); await g.startMonitoring()285 await g.stopMonitoring()286 #expect(await g.currentPressure == .normal)287 }288}289290actor Calls {291 var values: [Bool] = []292 func add(_ v: Bool) { values.append(v) }293}294