Tests/OrgEditorAppKitTests/GateTests.swift
170 lines · 8467 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 /// About 1 MB of Markdown: front matter, headings, paragraphs with emphasis, code and
69 /// links, lists, block quotes and fenced code.
70 static let markdown: String = {
71 var text = "---\ntitle: Gate\n---\n"
72 var n = 0
73 while text.utf8.count < 1_000_000 {
74 text += "## Section \(n)\n\nParagraph \(n) with **bold**, *italic*, `code`, a [link](https://example.com/\(n)) and https://example.com.\n"
75 text += "It continues on a second line with ~~struck~~ and _more_.\n\n"
76 text += "- item \(n)\n - [ ] nested task\n\n> quoted \(n)\n\n```swift\nlet n = \(n)\n```\n\n"
77 n += 1
78 }
79 return text
80 }()
81
82 struct Result: CustomStringConvertible {
83 var name: String
84 var bytes: Int
85 var open: Duration
86 var typingP95: Duration
87 var newlineP95: Duration
88 var memoryRatio: Double
89
90 var description: String {
91 "\(name) (\(bytes / 1000) kB): open \(open), typing p95 \(typingP95), blank line p95 \(newlineP95), memory \(String(format: "%.1f", memoryRatio))x"
92 }
93 }
94
95 /// Heap bytes in use, which unlike resident size isn't hidden by memory freed earlier.
96 static func heapBytes() -> Int {
97 var stats = malloc_statistics_t()
98 malloc_zone_statistics(nil, &stats)
99 return Int(stats.size_in_use)
100 }
101
102 func measure(_ name: String, _ text: String, mode: OrgEditor.Mode = .org) -> Result {
103 let clock = ContinuousClock()
104 let bytes = Array(text.utf8)
105 let before = Self.heapBytes()
106 var harness: Harness!
107 let open = clock.measure {
108 harness = Harness(DocumentState(bytes: bytes), layout: false, mode: mode)
109 }
110 harness.drainStyling()
111 let memoryRatio = Double(Self.heapBytes() - before) / Double(bytes.count)
112
113 var timings: [Duration] = []
114 harness.editor.onEditTiming = { timings.append($0) }
115 let paragraphs = harness.editor.document.tree.root.descendants().filter { $0.kind == .paragraph || $0.kind == .tableCell }
116 harness.caret(at: paragraphs[paragraphs.count / 2].range.lowerBound + 1)
117 for _ in 0..<100 { harness.textView.insertText("x", replacementRange: harness.textView.selectedRange()) }
118 let typing = timings.sorted()[95]
119
120 timings = []
121 for _ in 0..<20 {
122 harness.textView.insertNewline(nil)
123 harness.textView.insertNewline(nil)
124 harness.textView.deleteBackward(nil)
125 harness.textView.deleteBackward(nil)
126 }
127 let sorted = timings.sorted()
128 return Result(name: name, bytes: bytes.count, open: open, typingP95: typing, newlineP95: sorted[sorted.count * 95 / 100], memoryRatio: memoryRatio)
129 }
130
131 @Test func gates() throws {
132 // The first text view, and the first text loaded into one, set up the text system once
133 // per process; an app pays that at launch, not per file.
134 NSTextView(usingTextLayoutManager: true).textStorage?.setAttributedString(NSAttributedString(string: "warm up"))
135 // Memory limits: worst-case dense markup for the synthetic files, typical for real ones.
136 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)]
137 if let path = ProcessInfo.processInfo.environment["ORGSTAR_GATE_FILE"] {
138 inputs.append((URL(fileURLWithPath: path).lastPathComponent, try String(contentsOfFile: path, encoding: .utf8), 10.0))
139 }
140 for (name, text, memoryLimit) in inputs {
141 let result = measure(name, text)
142 print("GATE \(result)")
143 let perMegabyte = Double(result.bytes) / 1_000_000
144 #expect(result.open < .milliseconds(100) * max(1, perMegabyte), "\(name): open")
145 #expect(result.typingP95 < .milliseconds(16), "\(name): typing")
146 #expect(result.newlineP95 < .milliseconds(16), "\(name): blank line")
147 #expect(result.memoryRatio < memoryLimit, "\(name): memory")
148 }
149 // Lint File, which runs off the main thread: the fastest of three runs on a parsed file.
150 for (name, text, _) in inputs {
151 let tree = OrgParser.parse(text)
152 let clock = ContinuousClock()
153 let lint = (0..<3).map { _ in clock.measure { _ = OrgLint.lint(text, tree: tree, path: nil) } }.min()!
154 print("GATE \(name) (\(text.utf8.count / 1000) kB): lint \(lint)")
155 #expect(lint < .milliseconds(500) * max(1, Double(text.utf8.count) / 1_000_000), "\(name): lint")
156 }
157 let markdown = measure("1 MB Markdown", Self.markdown, mode: .markdown)
158 print("GATE \(markdown)")
159 #expect(markdown.open < .milliseconds(100) * max(1, Double(markdown.bytes) / 1_000_000), "Markdown: open")
160 #expect(markdown.typingP95 < .milliseconds(16), "Markdown: typing")
161 #expect(markdown.newlineP95 < .milliseconds(16), "Markdown: blank line")
162 #expect(markdown.memoryRatio < 45, "Markdown: memory")
163 let large = measure("10 MB mixed document", Self.tenMegabytes)
164 print("GATE \(large)")
165 #expect(large.open < .milliseconds(1_500), "10 MB: open")
166 #expect(large.typingP95 < .milliseconds(400), "10 MB: typing")
167 #expect(large.newlineP95 < .milliseconds(400), "10 MB: blank line")
168 #expect(large.memoryRatio < 40, "10 MB: memory")
169 }
170}