Responsiveness logging !196

merged merged by cmc on 2026-10-10 03:45 UTC · krz/orgstar:perf-logging into main

10 files changed, +126 −1

Layout: unified · split

Sources/OrgApp/AgendaModel.swift +4
@@ -52,6 +52,8 @@ public final class AgendaModel {
5252
5353 /// Recomputes the days. `open` is the open buffers' text by path.
5454 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") }
5557 generation += 1
5658 let id = generation
5759 isComputing = true
@@ -113,6 +115,8 @@ public final class AgendaModel {
113115 /// The agenda files' sources: the open file's from its text, the others from the cache
114116 /// while their modification date and size are unchanged.
115117 private func sources(open: [String: String]) async -> [AgendaSource] {
118 let interval = Perf.begin("agenda.sources")
119 defer { interval.end("\(files.count) files") }
116120 let defaults = workspace.settings.org
117121 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
118122 var reads: [(path: String, cached: AgendaSource?, mtime: Date, size: Int, text: String?)] = []
Sources/OrgApp/AgendaViews.swift +2
@@ -47,6 +47,8 @@ public enum AgendaViewLoader {
4747
4848 /// The built-in views followed by the user's, and the problems found in the file.
4949 public static func load(userFile: URL = userFile) -> (views: [AgendaViewDefinition], problems: [String]) {
50 let interval = Perf.begin("views.load")
51 defer { interval.end() }
5052 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) }
5153 let tables: [TOML.Table]
5254 do {
Sources/OrgApp/DocumentSession.swift +8
@@ -196,6 +196,8 @@ public final class DocumentSession {
196196
197197 /// Shows the buffer of `path`, opening the file if it isn't open.
198198 public func open(_ path: String) {
199 let interval = Perf.begin("session.open")
200 defer { interval.end((path as NSString).lastPathComponent) }
199201 if let existing = entry(path) {
200202 activate(existing)
201203 return
@@ -293,6 +295,8 @@ public final class DocumentSession {
293295 }
294296
295297 private func refresh(outline updateOutline: Bool = true) {
298 let interval = Perf.begin("session.refresh")
299 defer { interval.end() }
296300 refreshLists()
297301 guard let buffer else { return }
298302 let state = buffer.document
@@ -349,6 +353,8 @@ public final class DocumentSession {
349353
350354 @discardableResult
351355 private func save(_ entry: Entry) -> Bool {
356 let interval = Perf.begin("session.save")
357 defer { interval.end((entry.path as NSString).lastPathComponent) }
352358 entry.autosave?.cancel()
353359 let name = (entry.path as NSString).lastPathComponent
354360 guard entry.buffer.document.isDirty else { return true }
@@ -869,6 +875,8 @@ public final class DocumentSession {
869875 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
870876 /// change in.
871877 public func fileChanged(_ path: String) {
878 let interval = Perf.begin("session.fileChanged")
879 defer { interval.end((path as NSString).lastPathComponent) }
872880 guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
873881 let buffer = entry.buffer
874882 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 {
140140
141141 /// Reconciles every root off the main thread, then reloads the file list.
142142 public func refresh() async {
143 let interval = Perf.begin("workspace.refresh")
144 defer { interval.end() }
143145 isIndexing = true
144146 defer { isIndexing = false }
145147 let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
@@ -323,6 +325,8 @@ public final class WorkspaceModel {
323325 /// Brings the index up to date for the root holding `path` now, rather than when the
324326 /// file events arrive.
325327 private func rescan(containing path: String) async {
328 let interval = Perf.begin("workspace.rescan")
329 defer { interval.end() }
326330 guard let root = rootURL(containing: path) else { return }
327331 await filesChanged([], rescan: [root])
328332 }
Sources/OrgstarMobile/AgendaScreen.swift +1 −1
@@ -76,7 +76,7 @@ struct AgendaScreen: View {
7676 if workspace.rootPaths.isEmpty {
7777 } else if case .agenda = agenda.mode {
7878 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
8080 Section {
8181 day(group)
8282 } header: {
Sources/OrgstarMobile/MobileEditor.swift +11
@@ -1,4 +1,5 @@
11#if os(iOS)
2import OrgApp
23import OrgCore
34import OrgDocument
45import OrgHighlight
@@ -442,6 +443,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
442443
443444 /// Applies `edits` (against the current text) through the text view as one undo step.
444445 func applyEdits(_ edits: [TextEdit]) {
446 let interval = Perf.begin("editor.applyEdits")
447 defer { interval.end() }
445448 guard !edits.isEmpty else { return }
446449 applyingEdits = true
447450 defer { applyingEdits = false }
@@ -473,6 +476,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
473476 /// The storage changed (typing, a command, undo): the document takes the same edit, and
474477 /// folds and styles follow.
475478 fileprivate func storageEdited(range: NSRange, delta: Int) {
479 let interval = Perf.begin("editor.edit")
480 defer { interval.end() }
476481 guard !loading else { return }
477482 let old = range.location..<(range.location + range.length - delta)
478483 let replacement = (textView.textStorage.string as NSString).substring(with: range)
@@ -570,6 +575,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
570575
571576 /// Styles the whole file again.
572577 private func restyleAll() {
578 let interval = Perf.begin("editor.restyleAll")
579 defer { interval.end() }
573580 restyle(0..<textView.textStorage.length)
574581 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
575582 }
@@ -600,6 +607,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
600607
601608 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
602609 private func restyle(_ range: Range<Int>) {
610 let interval = Perf.begin("editor.restyle")
611 defer { interval.end() }
603612 let storage = textView.textStorage
604613 let ns = storage.string as NSString
605614 guard ns.length > 0 else { return }
@@ -858,6 +867,8 @@ final class MobileEditor: NSObject, DocumentBuffer {
858867
859868 /// The caret left hidden text (a tap past a fold): what hides it opens.
860869 fileprivate func selectionChanged() {
870 let interval = Perf.begin("editor.selection")
871 defer { interval.end() }
861872 redrawSelectedBlocks()
862873 let caret = textView.selectedRange.location
863874 if hidden.containing(caret) != nil { unfold(around: caret) }
Sources/OrgstarMobile/MobileModel.swift +6
@@ -100,6 +100,8 @@ final class MobileModel {
100100 }
101101
102102 func reloadConfig() {
103 let interval = Perf.begin("config.reload")
104 defer { interval.end() }
103105 UserConfig.directoryOverride = configFolder
104106 let (problems, colors) = Self.readConfig(configFolder)
105107 configProblems = problems
@@ -227,6 +229,8 @@ final class MobileModel {
227229
228230 /// Notifications for the next week's timed entries, at most 64, as iOS allows.
229231 func updateReminders() async {
232 let interval = Perf.begin("reminders.update")
233 defer { interval.end() }
230234 guard let workspace else { return }
231235 guard OrgPreferences.reminders() else {
232236 await scheduler.clear()
@@ -242,6 +246,8 @@ final class MobileModel {
242246 /// The widgets' agenda: today and the next days in the app group's container, with the
243247 /// widgets reloaded when it changed.
244248 func updateWidgets() async {
249 let interval = Perf.begin("widgets.update")
250 defer { interval.end() }
245251 guard let workspace, let file = AgendaSnapshot.file() else { return }
246252 let days = AgendaModel(workspace: workspace)
247253 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
Sources/OrgstarMobile/OrgstarMobileApp.swift +3
@@ -12,6 +12,9 @@ struct OrgstarMobileApp: App {
1212 @State private var model = MobileModel.shared
1313
1414 init() {
15 #if DEBUG
16 Perf.watchMainThread()
17 #endif
1518 LiveClock.install()
1619 }
1720
Sources/OrgstarMobile/SpotlightIndexer.swift +2
@@ -29,6 +29,8 @@ final class SpotlightIndexer {
2929 }
3030
3131 func update(_ files: [FileEntry]) async {
32 let interval = Perf.begin("spotlight.update")
33 defer { interval.end("\(files.count) files") }
3234 guard !running else { return waiting = files }
3335 running = true
3436 defer { running = false }