Tests/OrgEditorAppKitTests/GateTests.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Tests/OrgEditorAppKitTests/GateTests.swift history · blame · raw

141 lines · 6737 bytes

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