Skip to content

Commit f4601f2

Browse files
committed
Bound validation calls and benchmark scalable conversation checkpoints
1 parent 083d511 commit f4601f2

20 files changed

Lines changed: 395 additions & 28 deletions

‎GUI-VALIDATION.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,11 @@ See V2-IMPLEMENTATION.md for the verified flow table, isolation controls, exact
55
Executed built binary with CODEBASIC_V2_OFFLINE=1 and CODEBASIC_V2_TEST_ROOT=/tmp/codebasic-v2-gui-review. CUA verified startup, image attachment, message send, mock response, explicit playback/stop, slow-generation cancellation, conversation selection, settings round trip, normal quit and restart restoration. V1 was simultaneously running throughout; its UI and data were not operated on. Both V2 process sessions exited 0 after normal GUI quit.
66

77
Test data remains in /tmp/codebasic-v2-gui-review for inspection. It contains synthetic text/images only. Playback was a state mock with fake bytes, not sound-device output. No paid provider or ElevenLabs requests were made.
8+
9+
## Final post-performance-patch rerun
10+
11+
The final app built and signed successfully, and all 38 chat mock checks, offline/permit checks, production Gemini transport mock and original regressions passed. It was launched with CODEBASIC_V2_OFFLINE=1 and CODEBASIC_V2_TEST_ROOT=/tmp/codebasic-v2-bench-300, containing only generated synthetic history (300 seed conversations, 6,000 seed messages and approximately 83 MB of synthetic PNGs, plus a few benchmark turns).
12+
13+
CUA could not inspect or operate the app because the Mac was locked and automatic unlock was unavailable. A manual-unlock request was issued; no lock bypass was attempted. Therefore the full flow on this final revision and actual large-list GUI responsiveness remain BLOCKED, not passed. The prior complete GUI sequence above was on 0bfb8f4; it must not be presented as the final post-cache-patch rerun. The offline app remained running for the unlock/resume step. Startup logged one nonfatal NSTableView reentrant-operation warning; its user-visible effect could not be checked while locked.
14+
15+
The authorized real Google/ElevenLabs check was completed separately through production V2 components while GUI access was blocked; see LIVE-VALIDATION.md. That check does not establish the live GUI flow.

‎LIVE-VALIDATION.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Authorized minimal Google / ElevenLabs verification — 2026-11-17
2+
3+
The user explicitly authorized read-only use of the existing app's authentication information for one short, harmless synthetic Google response and playback of that response with the existing ElevenLabs voice/model. No existing conversation, document or image was submitted. No credential value was printed, copied to a new file or added to a report.
4+
5+
The Mac was locked, so this was a production-component integration probe rather than an observed live GUI flow. The probe uses the same EndpointGenerator, provider-neutral conversation, ChatSession, ElevenLabsBackend, TextSplitter/ChatSpeechPlan and QueuePlayer as V2. It ran with CODEBASIC_V2_LIVE_VALIDATION=1, CODEBASIC_V2_OFFLINE unset and CODEBASIC_V2_TEST_ROOT=a dedicated temporary folder. Offline URLProtocol blocking was not bypassed; it is only installed by offline mode, in a different process. There was no account login, subscription, billing setting or installation change.
6+
7+
## Controls
8+
9+
Live-validation mode suppresses automatic provider/model discovery, refuses plan transports and non-Google generation endpoints in the UI, uses a dedicated /tmp data root, caps Gemini output at 64 tokens, and persists a one-use permit per authorized provider. Failed attempts also consume the permit. The audio check accepts a single response below 300 characters. The manual probe requires an explicit --authorized-single-probe argument, checks the selected original model/endpoint, and is never run by build.sh test. Keys are read through the explicit V1 fallback marker; only that empty marker is created, not key files.
10+
11+
Before the actual request, URLProtocol mock tests verified the production Gemini streaming payload had the 64-token cap and provider-neutral conversation. Permit/isolation checks and all normal regression tests passed without real requests.
12+
13+
## Actual result
14+
15+
| Item | Observed result |
16+
|---|---|
17+
| Google logical requests | 1, no application retry |
18+
| Selected Google model | gemini-flash-lite-latest, original selected model |
19+
| Submitted user text | 39 synthetic characters requesting only the sentence “음성 연결 테스트입니다.” |
20+
| Other submitted content | A short synthetic system instruction; no previous messages or images |
21+
| Generated response | 13 characters |
22+
| Returned Google usage | 34 prompt tokens, 6 candidate tokens, 40 total; serviceTier standard |
23+
| ElevenLabs logical requests | 1, no application retry |
24+
| Voice/model | Original selected voice and eleven_v4; original tuning read-only |
25+
| ElevenLabs input | The 13-character generated response only |
26+
| ElevenLabs response | HTTP 200, 30,137 MP3 bytes |
27+
| Playback | AVQueuePlayer reached end-of-item: completed_chunks=1, expected_chunks=1; no failure event or timeout |
28+
| Physical audibility | Not independently recorded/heard through a measurement device; the completion event verifies the software playback path |
29+
| Billing | No balance, invoice or exact charge was queried. Token/character counts above are known; monetary cost/credit debit remains unverified |
30+
31+
Non-secret evidence is under build/validation/live. The synthetic conversation/audio and one-use markers remain in the dedicated /tmp live root. Do not re-run a paid probe merely to reproduce this report; another live run requires its own authorization. The reproduction benchmark and build.sh test use synthetic/local mocks only.
32+
33+
## V1 preservation
34+
35+
Before/after checks found the original settings JSON and installed app executable SHA-256 digests unchanged. Metadata for five settings/credential files (size, modification time and inode) was unchanged; credential contents were not read for this comparison. V1 checkout remained clean at aba918365ea9a7dc19fa27b9652a0f6bbe84df24. No V1 history or attachments were read. The only credential reads were those required by the expressly authorized Google/ElevenLabs probe.

‎PERFORMANCE-VALIDATION.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Synthetic history performance
2+
3+
Measured on macOS 27.0.1 arm64, optimized swiftc build, local filesystem, 2026-11-17. This is an informal warm-filesystem measurement, not a cold-cache or controlled-system benchmark. Other Mac apps remained running. App build/unit compilation had finished before the final sequential comparison.
4+
5+
All data is synthetic. Seed sizes: 50/300/1000 threads, 20 messages per thread, approximately 500 text characters per message; 10/80/80 valid PNG attachments of 1,033,018 bytes each (10,330,180 / 82,641,440 / 82,641,440 bytes). Initial metadata sizes: 771,215 / 4,633,045 / 15,440,345 bytes. Each timed run appends one small benchmark thread/two messages. Exact loaded counts are in the JSON logs; this drift is small relative to seed message count.
6+
7+
Baseline: ChatSession extracted read-only from 0bfb8f4. Final: cached unchanged-thread metadata, one new-thread flush. Baseline is one run per scale; final entries are medians of three fresh-process runs. No filesystem cache flush was attempted.
8+
9+
| Seed threads/messages | Load ms before → final | New-thread flush ms before → final | Send flush ms before → final | Shutdown flush ms before → final | Main actor max tick gap ms before → final | Final loaded / end RSS MiB | Peak RSS MiB range |
10+
|---|---|---|---|---|---|---|---|
11+
| 50 / 1000 | 18.91 → 14.21 | 21.22 → 10.09 | 8.69 → 0.90 | 14.90 → 4.47 | 21.00 → 11.87 | 18.72 / 22.27 | 24.08–24.17 |
12+
| 300 / 6000 | 69.53 → 63.28 | 86.83 → 42.57 | 41.19 → 2.90 | 45.41 → 9.42 | 69.94 → 14.39 | 104.09 / 119.92 | 121.44–130.59 |
13+
| 1000 / 20000 | 158.02 → 150.06 | 288.68 → 135.83 | 137.62 → 7.91 | 146.38 → 29.15 | 149.16 → 22.26 | 142.58 / 237.64 | 237.34–240.34 |
14+
15+
Load includes synchronous archive decode and image file loading, measured from a fresh process with potentially warm OS cache. New-thread time includes its first full cache fill. Send and shutdown measure synchronous durability flush. The stream emits 120 synthetic chunks at 10 ms intervals, with a 1 ms MainActor ticker; the maximum observed tick gap measures scheduling stalls, not display frame rate or human-perceived latency. Resident memory uses Mach task_info; peak uses /usr/bin/time -l and includes the entire benchmark process. These are not GUI-app memory measurements.
16+
17+
The former repeated full JSON encoding was a measurable bottleneck. Caching unchanged thread JSON and removing the duplicate new-thread save reduced steady-state flush and main-actor scheduling gaps. The cache increases resident memory, especially for 20,000 messages. First save/initial load still scale with total history; this prototype is not a lazy-loading database.
18+
19+
Reproduce from the repository with `bash Tests/run-chat-benchmark.sh /tmp/codebasic-v2-benchmark-repro-UNIQUE`. It generates its own deterministic synthetic PNG and archives, compiles baseline/final harnesses, performs one baseline and three final runs per scale, and leaves JSON/time/fixture records in that dedicated /tmp root. Use a new root for each reproduction. No credentials or provider transports are compiled into this harness.
20+
21+
Actual GUI responsiveness on the final 300-thread dataset is recorded separately in GUI-VALIDATION.md; the ticker above is not a substitute for that observation.

‎Sources/App/AppState.swift‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -224,11 +224,11 @@ final class AppState: ObservableObject {
224224
}
225225

226226
func refreshAllModels() {
227-
guard !V2Runtime.offline else { return }
227+
guard !V2Runtime.suppressDiscovery else { return }
228228
for e in endpoints where e.isEnabled { refreshEndpointModels(e) }
229229
}
230230
func refreshAllModelsIfNeeded() {
231-
guard !V2Runtime.offline else { return }
231+
guard !V2Runtime.suppressDiscovery else { return }
232232
for e in endpoints
233233
where e.isEnabled && (endpointModels[e.id.uuidString] ?? []).isEmpty {
234234
// Fetching a keyed endpoint without a key just errors — wait for the key.
@@ -711,7 +711,7 @@ final class AppState: ObservableObject {
711711
/// gemini=`GET /models`, ollama=`GET /api/tags`) and swap it into the picker.
712712
/// Reuses the existing per-style helpers — no new network code.
713713
func refreshEndpointModels(_ endpoint: CustomEndpoint) {
714-
guard !V2Runtime.offline else { return }
714+
guard !V2Runtime.suppressDiscovery else { return }
715715
let e = endpoint
716716
let id = e.id.uuidString
717717
if !e.usesPlan && (e.apiStyle == .gemini || e.apiStyle == .anthropic) && endpointKey(e).isEmpty {
@@ -1394,7 +1394,7 @@ final class AppState: ObservableObject {
13941394
}
13951395

13961396
func refreshVoices() {
1397-
guard !V2Runtime.offline else { return }
1397+
guard !V2Runtime.suppressDiscovery else { return }
13981398
refreshModels()
13991399
guard let key = Secrets.elevenLabsKey else { connectionStatus = "키 없음"; return }
14001400
connectionStatus = "연결 확인 중…"
@@ -1415,7 +1415,7 @@ final class AppState: ObservableObject {
14151415

14161416
/// Keep the last successful catalog and selected model through all failures.
14171417
func refreshModels() {
1418-
guard !V2Runtime.offline else { return }
1418+
guard !V2Runtime.suppressDiscovery else { return }
14191419
guard !refreshingModels else { return }
14201420
guard let key = Secrets.elevenLabsKey else { modelStatus = "모델 조회: 키 없음"; return }
14211421
refreshingModels = true

‎Sources/App/Secrets.swift‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,32 @@ enum Secrets {
3737
/// Explicit test-only runtime. Activation precedes AppState construction.
3838
enum V2Runtime {
3939
static let offline = ProcessInfo.processInfo.environment["CODEBASIC_V2_OFFLINE"] == "1"
40+
static let liveValidation = !offline && ProcessInfo.processInfo.environment["CODEBASIC_V2_LIVE_VALIDATION"] == "1"
41+
static var suppressDiscovery: Bool { offline || liveValidation }
4042
static let dataRoot: String = {
41-
if offline {
43+
if offline || liveValidation {
4244
let path = ProcessInfo.processInfo.environment["CODEBASIC_V2_TEST_ROOT"] ?? "/tmp/codebasic-v2-offline"
4345
let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
44-
precondition(resolved.hasPrefix("/private/tmp/") || resolved.hasPrefix("/tmp/"), "Offline test root must be inside /tmp")
46+
precondition(resolved.hasPrefix("/private/tmp/") || resolved.hasPrefix("/tmp/"), "Validation root must be inside /tmp")
4547
return resolved
4648
}
4749
return ("~/Library/Application Support/Codebasic TTS V2" as NSString).expandingTildeInPath
4850
}()
51+
/// One request per provider per isolated validation root, including failed attempts.
52+
static func consumeLivePermit(_ provider: String) -> Bool {
53+
guard liveValidation, ["google", "elevenlabs"].contains(provider) else { return !liveValidation }
54+
let url = URL(fileURLWithPath: dataRoot).appendingPathComponent("live-" + provider + "-used")
55+
do {
56+
try FileManager.default.createDirectory(atPath: dataRoot, withIntermediateDirectories: true)
57+
try Data("one synthetic validation request".utf8).write(to: url, options: .withoutOverwriting)
58+
return true
59+
} catch { return false }
60+
}
61+
static func recordLiveEvidence(_ name: String, _ object: [String: Any]) {
62+
guard liveValidation, ["google-usage", "elevenlabs-response", "playback"].contains(name),
63+
let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else { return }
64+
try? data.write(to: URL(fileURLWithPath: dataRoot).appendingPathComponent("live-" + name + ".json"), options: .atomic)
65+
}
4966
static func installOfflineNetworkBlock() {
5067
if offline { URLProtocol.registerClass(V2OfflineURLProtocol.self) }
5168
}

‎Sources/Core/ChatSession.swift‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ private final class ChatDiskStore {
1111
private let queue = DispatchQueue(label: "com.seongjoo.CodebasicTTSV2.chat-storage", qos: .utility)
1212
private var writes = 0
1313
private var attachmentWrites = 0
14+
// Existing messages are immutable; only the last response text/state changes.
15+
private struct Revision: Equatable {
16+
let title: String; let count: Int; let lastID: UUID?; let text: String?; let state: String?
17+
}
18+
private var encodedThreads: [UUID: (Revision, Data)] = [:]
1419
var writeCount: Int { queue.sync { writes } }
1520
var attachmentWriteCount: Int { queue.sync { attachmentWrites } }
1621
init(root: URL) { self.root = root }
@@ -36,7 +41,9 @@ private final class ChatDiskStore {
3641
private func write(_ threads: [ChatThread]) throws {
3742
let directory = root.appendingPathComponent("attachments")
3843
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
39-
let records = try threads.map { thread in
44+
let records: [Data] = try threads.map { thread in
45+
let revision = Revision(title: thread.title, count: thread.messages.count, lastID: thread.messages.last?.id, text: thread.messages.last?.text, state: thread.messages.last?.state)
46+
if let cached = encodedThreads[thread.id], cached.0 == revision { return cached.1 }
4047
let messages = try thread.messages.map { message in
4148
var metadata = message; metadata.images = []
4249
let names = try message.images.enumerated().map { index, data in
@@ -49,9 +56,15 @@ private final class ChatDiskStore {
4956
}
5057
return StoredMessage(message: metadata, attachments: names)
5158
}
52-
return StoredThread(id: thread.id, title: thread.title, createdAt: thread.createdAt, messages: messages)
59+
let record = StoredThread(id: thread.id, title: thread.title, createdAt: thread.createdAt, messages: messages)
60+
let data = try JSONEncoder().encode(record)
61+
encodedThreads[thread.id] = (revision, data)
62+
return data
5363
}
54-
try JSONEncoder().encode(Archive(threads: records)).write(to: root.appendingPathComponent("conversations.json"), options: .atomic)
64+
var archive = Data("{\"version\":1,\"threads\":[".utf8)
65+
for (index, record) in records.enumerated() { if index > 0 { archive.append(44) }; archive.append(record) }
66+
archive.append(contentsOf: "]}".utf8)
67+
try archive.write(to: root.appendingPathComponent("conversations.json"), options: .atomic)
5568
writes += 1
5669
}
5770
func save(_ threads: [ChatThread]) throws { try queue.sync { try write(threads) } }
@@ -144,9 +157,10 @@ enum ChatSpeechPlan {
144157
/// The serial disk queue drains any older asynchronous checkpoint before this save.
145158
func shutdown() { cancelGeneration(); stop() }
146159
func newThread() {
147-
guard persist() else { return }
160+
guard storageAvailable else { return }
161+
let previous = selected
148162
let thread = ChatThread(); threads.insert(thread, at: 0); selected = thread.id
149-
_ = persist()
163+
if !persist() { threads.removeFirst(); selected = previous }
150164
}
151165
@discardableResult private func persist() -> Bool {
152166
checkpointTask?.cancel(); checkpointTask = nil

‎Sources/TTS/ElevenLabsBackend.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ struct ElevenLabsBackend: TTSBackend {
6868
throw NSError(domain: "ElevenLabs", code: http.statusCode,
6969
userInfo: [NSLocalizedDescriptionKey: msg])
7070
}
71+
V2Runtime.recordLiveEvidence("elevenlabs-response", ["http_status": http.statusCode, "input_characters": segment.count, "audio_bytes": buffer.count])
7172
continuation.yield(buffer)
7273
continuation.finish()
7374
} catch {

‎Sources/TTS/EndpointGenerator.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ struct EndpointGenerator: Normalizing, Explaining {
3636
return AnthropicAPI.stream(baseURL: endpoint.baseURL, key: apiKey, model: model, prompt: prompt, images: images, conversation: conversation)
3737
case .gemini:
3838
return LLM.geminiStream(baseURL: endpoint.baseURL, apiKey: apiKey, model: model, prompt: prompt,
39-
images: images, temperature: temperature, reasoningLevel: reasoningLevel, conversation: conversation)
39+
images: images, temperature: temperature, reasoningLevel: reasoningLevel, conversation: conversation, maxOutputTokens: V2Runtime.liveValidation ? 64 : nil)
4040
case .openAICompatible:
4141
return LLM.openAIChatStream(baseURL: endpoint.baseURL, model: model, apiKey: apiKey, prompt: prompt,
4242
images: images, temperature: temperature, reasoningLevel: reasoningLevel,

0 commit comments

Comments
 (0)