Tests/OrgEditorAppKitTests/GateTests.swift
150 lines · 7291 bytes
1import AppKit
2import Foundation
3import OrgCore
4import OrgDocument
5import Testing
6@testable import OrgEditorAppKit
7
8/// The phase 1 performance gates (design, "Phases"). Skipped unless `ORGSTAR_GATES` is set;
9/// run in a release build on the reference machine:
10///
11/// ORGSTAR_GATES=1 swift test -c release --filter GateTests
12///
13/// `ORGSTAR_GATE_FILE` adds a real file to the synthetic ones. Memory limits follow the design:
14/// 10x the file size for typical documents, 45x for the synthetic worst cases. The 10 MB and
15/// workspace budgets are what the code did when they were set, plus headroom. The tests run one
16/// at a time so their timings don't overlap.
17@MainActor
18@Suite(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_GATES"] != nil), .serialized)
19struct GateTests {
20 /// About 1 MB of body text under a single top-level heading.
21 /// Entries with property and LOGBOOK drawers, all folded when the file opens.
22 static let drawers: String = {
23 var text = ""
24 for n in 0..<3_000 {
25 text += "* TODO Entry \(n) :tag:\n:PROPERTIES:\n:ID: \(n)-uuid\n:CREATED: [2026-10-04 Sun]\n:END:\n"
26 text += ":LOGBOOK:\n- State \"DONE\" from \"TODO\" [2026-10-04 Sun 10:00]\nCLOCK: [2026-10-04 Sun 09:00]--[2026-10-04 Sun 10:00] => 1:00\n:END:\n"
27 text += "Body of entry \(n), a paragraph of text.\n\n"
28 }
29 return text
30 }()
31
32 static let singleSection: String = {
33 var text = "* One big section\n"
34 var n = 0
35 while text.utf8.count < 1_000_000 {
36 text += "Paragraph \(n) with *bold*, /italic/, a [[https://example.com/\(n)][link]] and <2026-10-04 Sun>.\n"
37 text += "It continues on a second line with =code= and ~more~.\n\n"
38 text += "- item \(n)\n - nested [ ] task\n\n"
39 n += 1
40 }
41 return text
42 }()
43
44 /// A 5,000-row table.
45 static let bigTable: String = {
46 var text = "* Table\n| id | name | note |\n|----+------+------|\n"
47 for n in 0..<5_000 { text += "| \(n) | row \(n) | *bold* and [[https://example.com][link]] |\n" }
48 return text
49 }()
50
51 /// About 10 MB of headings with planning lines and drawers, paragraphs with markup, lists,
52 /// tables, source blocks and footnotes.
53 static let tenMegabytes: String = {
54 var text = ""
55 var n = 0
56 while text.utf8.count < 10_000_000 {
57 text += "* TODO Heading \(n) :tag:\nSCHEDULED: <2026-10-04 Sun>\n:PROPERTIES:\n:ID: \(n)-uuid\n:END:\n"
58 text += "Paragraph \(n) with *bold*, /italic/, =code=, a [[https://example.com/\(n)][link]] and a footnote[fn:\(n)].\n\n"
59 text += "- item \(n)\n - nested [ ] task\n\n"
60 text += "| id | name |\n|----+------|\n| \(n) | row \(n) |\n\n"
61 text += "#+begin_src swift\nlet n = \(n)\n#+end_src\n\n"
62 text += "[fn:\(n)] Footnote \(n).\n\n"
63 n += 1
64 }
65 return text
66 }()
67
68 struct Result: CustomStringConvertible {
69 var name: String
70 var bytes: Int
71 var open: Duration
72 var typingP95: Duration
73 var newlineP95: Duration
74 var memoryRatio: Double
75
76 var description: String {
77 "\(name) (\(bytes / 1000) kB): open \(open), typing p95 \(typingP95), blank line p95 \(newlineP95), memory \(String(format: "%.1f", memoryRatio))x"
78 }
79 }
80
81 /// Heap bytes in use, which unlike resident size isn't hidden by memory freed earlier.
82 static func heapBytes() -> Int {
83 var stats = malloc_statistics_t()
84 malloc_zone_statistics(nil, &stats)
85 return Int(stats.size_in_use)
86 }
87
88 func measure(_ name: String, _ text: String) -> Result {
89 let clock = ContinuousClock()
90 let bytes = Array(text.utf8)
91 let before = Self.heapBytes()
92 var harness: Harness!
93 let open = clock.measure {
94 harness = Harness(DocumentState(bytes: bytes), layout: false)
95 }
96 harness.drainStyling()
97 let memoryRatio = Double(Self.heapBytes() - before) / Double(bytes.count)
98
99 var timings: [Duration] = []
100 harness.editor.onEditTiming = { timings.append($0) }
101 let paragraphs = harness.editor.document.tree.root.descendants().filter { $0.kind == .paragraph || $0.kind == .tableCell }
102 harness.caret(at: paragraphs[paragraphs.count / 2].range.lowerBound + 1)
103 for _ in 0..<100 { harness.textView.insertText("x", replacementRange: harness.textView.selectedRange()) }
104 let typing = timings.sorted()[95]
105
106 timings = []
107 for _ in 0..<20 {
108 harness.textView.insertNewline(nil)
109 harness.textView.insertNewline(nil)
110 harness.textView.deleteBackward(nil)
111 harness.textView.deleteBackward(nil)
112 }
113 let sorted = timings.sorted()
114 return Result(name: name, bytes: bytes.count, open: open, typingP95: typing, newlineP95: sorted[sorted.count * 95 / 100], memoryRatio: memoryRatio)
115 }
116
117 @Test func gates() throws {
118 // The first text view, and the first text loaded into one, set up the text system once
119 // per process; an app pays that at launch, not per file.
120 NSTextView(usingTextLayoutManager: true).textStorage?.setAttributedString(NSAttributedString(string: "warm up"))
121 // Memory limits: worst-case dense markup for the synthetic files, typical for real ones.
122 var inputs = [("single 1 MB section", Self.singleSection, 45.0), ("5,000-row table", Self.bigTable, 45.0), ("3,000 entries with drawers", Self.drawers, 45.0)]
123 if let path = ProcessInfo.processInfo.environment["ORGSTAR_GATE_FILE"] {
124 inputs.append((URL(fileURLWithPath: path).lastPathComponent, try String(contentsOfFile: path, encoding: .utf8), 10.0))
125 }
126 for (name, text, memoryLimit) in inputs {
127 let result = measure(name, text)
128 print("GATE \(result)")
129 let perMegabyte = Double(result.bytes) / 1_000_000
130 #expect(result.open < .milliseconds(100) * max(1, perMegabyte), "\(name): open")
131 #expect(result.typingP95 < .milliseconds(16), "\(name): typing")
132 #expect(result.newlineP95 < .milliseconds(16), "\(name): blank line")
133 #expect(result.memoryRatio < memoryLimit, "\(name): memory")
134 }
135 // Lint File, which runs off the main thread: the fastest of three runs on a parsed file.
136 for (name, text, _) in inputs {
137 let tree = OrgParser.parse(text)
138 let clock = ContinuousClock()
139 let lint = (0..<3).map { _ in clock.measure { _ = OrgLint.lint(text, tree: tree, path: nil) } }.min()!
140 print("GATE \(name) (\(text.utf8.count / 1000) kB): lint \(lint)")
141 #expect(lint < .milliseconds(500) * max(1, Double(text.utf8.count) / 1_000_000), "\(name): lint")
142 }
143 let large = measure("10 MB mixed document", Self.tenMegabytes)
144 print("GATE \(large)")
145 #expect(large.open < .milliseconds(1_500), "10 MB: open")
146 #expect(large.typingP95 < .milliseconds(400), "10 MB: typing")
147 #expect(large.newlineP95 < .milliseconds(400), "10 MB: blank line")
148 #expect(large.memoryRatio < 40, "10 MB: memory")
149 }
150}