Commit 3a5c6a6f0e

3a5c6a6f0e1b65f57e3697195747679128581b57

parent: 2d7bde2d9a

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-10 03:45 UTC

Log slow work and main-thread stalls to the debug console

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +4
@@ -52,6 +52,8 @@ public final class AgendaModel {
52 52
53 /// Recomputes the days. `open` is the open buffers' text by path. 53 /// Recomputes the days. `open` is the open buffers' text by path.
54 public func refresh(open: [String: String], now: Date = Date(), calendar: Calendar = .current) async { 54 public func refresh(open: [String: String], now: Date = Date(), calendar: Calendar = .current) async {
55 let interval = Perf.begin("agenda.refresh")
56 defer { interval.end("\(files.count) files") }
55 generation += 1 57 generation += 1
56 let id = generation 58 let id = generation
57 isComputing = true 59 isComputing = true
@@ -113,6 +115,8 @@ public final class AgendaModel {
113 /// The agenda files' sources: the open file's from its text, the others from the cache 115 /// The agenda files' sources: the open file's from its text, the others from the cache
114 /// while their modification date and size are unchanged. 116 /// while their modification date and size are unchanged.
115 private func sources(open: [String: String]) async -> [AgendaSource] { 117 private func sources(open: [String: String]) async -> [AgendaSource] {
118 let interval = Perf.begin("agenda.sources")
119 defer { interval.end("\(files.count) files") }
116 let defaults = workspace.settings.org 120 let defaults = workspace.settings.org
117 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies) 121 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
118 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = [] 122 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
Sources/OrgApp/AgendaViews.swift +2
@@ -47,6 +47,8 @@ public enum AgendaViewLoader {
47 47
48 /// The built-in views followed by the user's, and the problems found in the file. 48 /// The built-in views followed by the user's, and the problems found in the file.
49 public static func load(userFile: URL = userFile) -> (views: [AgendaViewDefinition], problems: [String]) { 49 public static func load(userFile: URL = userFile) -> (views: [AgendaViewDefinition], problems: [String]) {
50 let interval = Perf.begin("views.load")
51 defer { interval.end() }
50 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) } 52 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) }
51 let tables: [TOML.Table] 53 let tables: [TOML.Table]
52 do { 54 do {
Sources/OrgApp/DocumentSession.swift +8
@@ -196,6 +196,8 @@ public final class DocumentSession {
196 196
197 /// Shows the buffer of `path`, opening the file if it isn't open. 197 /// Shows the buffer of `path`, opening the file if it isn't open.
198 public func open(_ path: String) { 198 public func open(_ path: String) {
199 let interval = Perf.begin("session.open")
200 defer { interval.end((path as NSString).lastPathComponent) }
199 if let existing = entry(path) { 201 if let existing = entry(path) {
200 activate(existing) 202 activate(existing)
201 return 203 return
@@ -293,6 +295,8 @@ public final class DocumentSession {
293 } 295 }
294 296
295 private func refresh(outline updateOutline: Bool = true) { 297 private func refresh(outline updateOutline: Bool = true) {
298 let interval = Perf.begin("session.refresh")
299 defer { interval.end() }
296 refreshLists() 300 refreshLists()
297 guard let buffer else { return } 301 guard let buffer else { return }
298 let state = buffer.document 302 let state = buffer.document
@@ -349,6 +353,8 @@ public final class DocumentSession {
349 353
350 @discardableResult 354 @discardableResult
351 private func save(_ entry: Entry) -> Bool { 355 private func save(_ entry: Entry) -> Bool {
356 let interval = Perf.begin("session.save")
357 defer { interval.end((entry.path as NSString).lastPathComponent) }
352 entry.autosave?.cancel() 358 entry.autosave?.cancel()
353 let name = (entry.path as NSString).lastPathComponent 359 let name = (entry.path as NSString).lastPathComponent
354 guard entry.buffer.document.isDirty else { return true } 360 guard entry.buffer.document.isDirty else { return true }
@@ -869,6 +875,8 @@ public final class DocumentSession {
869 /// Called when the workspace sees a file change on disk: an open buffer of it takes the 875 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
870 /// change in. 876 /// change in.
871 public func fileChanged(_ path: String) { 877 public func fileChanged(_ path: String) {
878 let interval = Perf.begin("session.fileChanged")
879 defer { interval.end((path as NSString).lastPathComponent) }
872 guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return } 880 guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
873 let buffer = entry.buffer 881 let buffer = entry.buffer
874 guard bytes != buffer.document.mergeBase else { return } 882 guard bytes != buffer.document.mergeBase else { return }
Sources/OrgApp/Perf.swift added +85
@@ -0,0 +1,85 @@
1import Foundation
2import os
3
4/// Responsiveness messages for the debug console (subsystem `sh.krz.orgstar`, category
5/// `perf`): work that took longer than `threshold`, and stalls of the main thread. Times are
6/// wall-clock, so async work includes its waits. Measured work is also an interval in
7/// Instruments' os_signpost track.
8public enum Perf {
9 public static let log = Logger(subsystem: "sh.krz.orgstar", category: "perf")
10 static let signposter = OSSignposter(logger: log)
11 /// Work faster than this, about one frame, isn't logged.
12 public static let threshold = Duration.milliseconds(16)
13
14 @discardableResult
15 public static func measure<T>(_ name: StaticString, _ detail: @autoclosure () -> String = "", _ work: () throws -> T) rethrows -> T {
16 let state = signposter.beginInterval(name)
17 let start = ContinuousClock.now
18 defer {
19 signposter.endInterval(name, state)
20 report(name, ContinuousClock.now - start, detail())
21 }
22 return try work()
23 }
24
25 @discardableResult
26 public static func measure<T>(
27 _ name: StaticString, _ detail: @autoclosure () -> String = "", _ work: () async throws -> T
28 ) async rethrows -> T {
29 let state = signposter.beginInterval(name)
30 let start = ContinuousClock.now
31 defer {
32 signposter.endInterval(name, state)
33 report(name, ContinuousClock.now - start, detail())
34 }
35 return try await work()
36 }
37
38 /// Work timed from `Perf.begin` to `end`, for a function's whole body: `defer { interval.end() }`.
39 public struct Interval {
40 let name: StaticString
41 let state: OSSignpostIntervalState
42 let start = ContinuousClock.now
43
44 public func end(_ detail: @autoclosure () -> String = "") {
45 Perf.signposter.endInterval(name, state)
46 Perf.report(name, ContinuousClock.now - start, detail())
47 }
48 }
49
50 public static func begin(_ name: StaticString) -> Interval {
51 Interval(name: name, state: signposter.beginInterval(name))
52 }
53
54 static func report(_ name: StaticString, _ elapsed: Duration, _ detail: String) {
55 guard elapsed >= threshold else { return }
56 log.notice("\(String(describing: name), privacy: .public) took \(milliseconds(elapsed)) ms \(detail, privacy: .public)")
57 }
58
59 static func milliseconds(_ duration: Duration) -> Int {
60 Int(duration.components.seconds * 1000 + duration.components.attoseconds / 1_000_000_000_000_000)
61 }
62
63 nonisolated(unsafe) private static var watching = false
64
65 /// Logs each time the main thread takes `limit` or longer to run a block sent to it: a
66 /// tap or a frame waited that long. The messages before it say what ran.
67 public static func watchMainThread(limit: Duration = .milliseconds(100)) {
68 guard !watching else { return }
69 watching = true
70 let thread = Thread {
71 while true {
72 let sent = ContinuousClock.now
73 let done = DispatchSemaphore(value: 0)
74 DispatchQueue.main.async { done.signal() }
75 done.wait()
76 let waited = ContinuousClock.now - sent
77 if waited >= limit { log.error("main thread blocked for \(milliseconds(waited)) ms") }
78 Thread.sleep(forTimeInterval: 0.05)
79 }
80 }
81 thread.name = "Perf.watchMainThread"
82 thread.qualityOfService = .utility
83 thread.start()
84 }
85}
Sources/OrgApp/WorkspaceModel.swift +4
@@ -140,6 +140,8 @@ public final class WorkspaceModel {
140 140
141 /// Reconciles every root off the main thread, then reloads the file list. 141 /// Reconciles every root off the main thread, then reloads the file list.
142 public func refresh() async { 142 public func refresh() async {
143 let interval = Perf.begin("workspace.refresh")
144 defer { interval.end() }
143 isIndexing = true 145 isIndexing = true
144 defer { isIndexing = false } 146 defer { isIndexing = false }
145 let reconciler = Reconciler(index: index, settings: settings, rules: scanRules) 147 let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
@@ -323,6 +325,8 @@ public final class WorkspaceModel {
323 /// Brings the index up to date for the root holding `path` now, rather than when the 325 /// Brings the index up to date for the root holding `path` now, rather than when the
324 /// file events arrive. 326 /// file events arrive.
325 private func rescan(containing path: String) async { 327 private func rescan(containing path: String) async {
328 let interval = Perf.begin("workspace.rescan")
329 defer { interval.end() }
326 guard let root = rootURL(containing: path) else { return } 330 guard let root = rootURL(containing: path) else { return }
327 await filesChanged([], rescan: [root]) 331 await filesChanged([], rescan: [root])
328 } 332 }
Sources/OrgstarMobile/AgendaScreen.swift +1 −1
@@ -76,7 +76,7 @@ struct AgendaScreen: View {
76 if workspace.rootPaths.isEmpty { 76 if workspace.rootPaths.isEmpty {
77 } else if case .agenda = agenda.mode { 77 } else if case .agenda = agenda.mode {
78 let _ = model.settingsVersion 78 let _ = model.settingsVersion
79 ForEach(agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), keep: filter.keeps)) { group in 79 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), keep: filter.keeps) }) { group in
80 Section { 80 Section {
81 day(group) 81 day(group)
82 } header: { 82 } header: {
Sources/OrgstarMobile/MobileEditor.swift +11
@@ -1,4 +1,5 @@
1#if os(iOS) 1#if os(iOS)
2import OrgApp
2import OrgCore 3import OrgCore
3import OrgDocument 4import OrgDocument
4import OrgHighlight 5import OrgHighlight
@@ -442,6 +443,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
442 443
443 /// Applies `edits` (against the current text) through the text view as one undo step. 444 /// Applies `edits` (against the current text) through the text view as one undo step.
444 func applyEdits(_ edits: [TextEdit]) { 445 func applyEdits(_ edits: [TextEdit]) {
446 let interval = Perf.begin("editor.applyEdits")
447 defer { interval.end() }
445 guard !edits.isEmpty else { return } 448 guard !edits.isEmpty else { return }
446 applyingEdits = true 449 applyingEdits = true
447 defer { applyingEdits = false } 450 defer { applyingEdits = false }
@@ -473,6 +476,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
473 /// The storage changed (typing, a command, undo): the document takes the same edit, and 476 /// The storage changed (typing, a command, undo): the document takes the same edit, and
474 /// folds and styles follow. 477 /// folds and styles follow.
475 fileprivate func storageEdited(range: NSRange, delta: Int) { 478 fileprivate func storageEdited(range: NSRange, delta: Int) {
479 let interval = Perf.begin("editor.edit")
480 defer { interval.end() }
476 guard !loading else { return } 481 guard !loading else { return }
477 let old = range.location..<(range.location + range.length - delta) 482 let old = range.location..<(range.location + range.length - delta)
478 let replacement = (textView.textStorage.string as NSString).substring(with: range) 483 let replacement = (textView.textStorage.string as NSString).substring(with: range)
@@ -570,6 +575,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
570 575
571 /// Styles the whole file again. 576 /// Styles the whole file again.
572 private func restyleAll() { 577 private func restyleAll() {
578 let interval = Perf.begin("editor.restyleAll")
579 defer { interval.end() }
573 restyle(0..<textView.textStorage.length) 580 restyle(0..<textView.textStorage.length)
574 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) } 581 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
575 } 582 }
@@ -600,6 +607,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
600 607
601 /// Sets attributes for the whole lines in `range`, as the Mac editor does. 608 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
602 private func restyle(_ range: Range<Int>) { 609 private func restyle(_ range: Range<Int>) {
610 let interval = Perf.begin("editor.restyle")
611 defer { interval.end() }
603 let storage = textView.textStorage 612 let storage = textView.textStorage
604 let ns = storage.string as NSString 613 let ns = storage.string as NSString
605 guard ns.length > 0 else { return } 614 guard ns.length > 0 else { return }
@@ -858,6 +867,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
858 867
859 /// The caret left hidden text (a tap past a fold): what hides it opens. 868 /// The caret left hidden text (a tap past a fold): what hides it opens.
860 fileprivate func selectionChanged() { 869 fileprivate func selectionChanged() {
870 let interval = Perf.begin("editor.selection")
871 defer { interval.end() }
861 redrawSelectedBlocks() 872 redrawSelectedBlocks()
862 let caret = textView.selectedRange.location 873 let caret = textView.selectedRange.location
863 if hidden.containing(caret) != nil { unfold(around: caret) } 874 if hidden.containing(caret) != nil { unfold(around: caret) }
Sources/OrgstarMobile/MobileModel.swift +6
@@ -100,6 +100,8 @@ final class MobileModel {
100 } 100 }
101 101
102 func reloadConfig() { 102 func reloadConfig() {
103 let interval = Perf.begin("config.reload")
104 defer { interval.end() }
103 UserConfig.directoryOverride = configFolder 105 UserConfig.directoryOverride = configFolder
104 let (problems, colors) = Self.readConfig(configFolder) 106 let (problems, colors) = Self.readConfig(configFolder)
105 configProblems = problems 107 configProblems = problems
@@ -227,6 +229,8 @@ final class MobileModel {
227 229
228 /// Notifications for the next week's timed entries, at most 64, as iOS allows. 230 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
229 func updateReminders() async { 231 func updateReminders() async {
232 let interval = Perf.begin("reminders.update")
233 defer { interval.end() }
230 guard let workspace else { return } 234 guard let workspace else { return }
231 guard OrgPreferences.reminders() else { 235 guard OrgPreferences.reminders() else {
232 await scheduler.clear() 236 await scheduler.clear()
@@ -242,6 +246,8 @@ final class MobileModel {
242 /// The widgets' agenda: today and the next days in the app group's container, with the 246 /// The widgets' agenda: today and the next days in the app group's container, with the
243 /// widgets reloaded when it changed. 247 /// widgets reloaded when it changed.
244 func updateWidgets() async { 248 func updateWidgets() async {
249 let interval = Perf.begin("widgets.update")
250 defer { interval.end() }
245 guard let workspace, let file = AgendaSnapshot.file() else { return } 251 guard let workspace, let file = AgendaSnapshot.file() else { return }
246 let days = AgendaModel(workspace: workspace) 252 let days = AgendaModel(workspace: workspace)
247 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0) 253 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
Sources/OrgstarMobile/OrgstarMobileApp.swift +3
@@ -12,6 +12,9 @@ struct OrgstarMobileApp: App {
12 @State private var model = MobileModel.shared 12 @State private var model = MobileModel.shared
13 13
14 init() { 14 init() {
15 #if DEBUG
16 Perf.watchMainThread()
17 #endif
15 LiveClock.install() 18 LiveClock.install()
16 } 19 }
17 20
Sources/OrgstarMobile/SpotlightIndexer.swift +2
@@ -29,6 +29,8 @@ final class SpotlightIndexer {
29 } 29 }
30 30
31 func update(_ files: [FileEntry]) async { 31 func update(_ files: [FileEntry]) async {
32 let interval = Perf.begin("spotlight.update")
33 defer { interval.end("\(files.count) files") }
32 guard !running else { return waiting = files } 34 guard !running else { return waiting = files }
33 running = true 35 running = true
34 defer { running = false } 36 defer { running = false }