diff --git a/app/application.ml b/app/application.ml index 058b29b4..4de5890e 100644 --- a/app/application.ml +++ b/app/application.ml @@ -442,6 +442,26 @@ let select_destination state destination = ;; let feed_day_limit = 7 +let startup_boot_time = Unix.gettimeofday () +let startup_feed_load_time = ref None +let startup_timeline_presented = ref false + +let log_startup_stage ~stage ?(extra = "") () = + let now = Unix.gettimeofday () in + let since_boot_ms = (now -. startup_boot_time) *. 1000. in + let since_feed_ms = + match !startup_feed_load_time with + | None -> "" + | Some started -> Printf.sprintf ",\"since_feed_start_ms\":%.2f" ((now -. started) *. 1000.) + in + (try + Printf.eprintf + "journal-startup: {\"stage\":%S,\"since_boot_ms\":%.2f%s%s}\n%!" + stage since_boot_ms since_feed_ms extra + with Sys_error _ -> ()) +;; + +let initial_feed_root_limit = 30 let feed_root_limit = 30 let sync_error_card_lifetime = 5. @@ -918,7 +938,11 @@ let apply_manager_state ~discard state (manager_state : Graph_service.state) = ;; let worker_request generation = function - | Journal_timeline_state.Feed { cursor } -> + | Journal_timeline_state.Feed { cursor = None } -> + Journal_graph_request.Load_feed + { cursor = None; root_limit = initial_feed_root_limit; day_limit = feed_day_limit + ; request_generation = generation } + | Journal_timeline_state.Feed { cursor = Some _ as cursor } -> Journal_graph_request.Load_feed { cursor; root_limit = feed_root_limit; day_limit = feed_day_limit ; request_generation = generation } @@ -1441,9 +1465,23 @@ let rec apply_worker_response ?(settling=false) ~discard state (response : Journ ~generation:request_generation (Feed { cursor = None }) in + let next_feed_loaded = state.feed_loaded || complete in + if (not state.feed_loaded) && next_feed_loaded + then ( + let day_count = List.length feed.Journal_graph_projection.days in + let entry_count = + List.fold_left + (fun acc (day : Journal_graph_projection.day_feed) -> acc + List.length day.entries) + 0 + feed.days + in + log_startup_stage + ~stage:"app.feed_loaded" + ~extra:(Printf.sprintf ",\"days\":%d,\"entries\":%d" day_count entry_count) + ()); { state with timeline - ; feed_loaded = state.feed_loaded || complete + ; feed_loaded = next_feed_loaded ; presented_feed_context = Some refresh.context ; feed_refresh = (if complete then None else state.feed_refresh) }) @@ -1470,9 +1508,23 @@ let rec apply_worker_response ?(settling=false) ~discard state (response : Journ ~generation:request_generation (Feed { cursor = None }) in + let next_feed_loaded = state.feed_loaded || (accepted_initial_feed && complete) in + if (not state.feed_loaded) && next_feed_loaded + then ( + let day_count = List.length feed.Journal_graph_projection.days in + let entry_count = + List.fold_left + (fun acc (day : Journal_graph_projection.day_feed) -> acc + List.length day.entries) + 0 + feed.days + in + log_startup_stage + ~stage:"app.feed_loaded" + ~extra:(Printf.sprintf ",\"days\":%d,\"entries\":%d" day_count entry_count) + ()); { state with timeline - ; feed_loaded = state.feed_loaded || (accepted_initial_feed && complete) + ; feed_loaded = next_feed_loaded ; presented_feed_context = (if accepted_initial_feed then Option.map feed_projection_context state.calendar @@ -5228,6 +5280,8 @@ let start then Effect.ignore else ( started_graph_generation := Some (graph_key, graph_state.generation); + startup_feed_load_time := Some (Unix.gettimeofday ()); + log_startup_stage ~stage:"app.graph_open.load_feed_start" (); retire_graph_scope (); let current = !state_ref in let graph_info = Journal_graph_runtime.start (!graph_runtime_cell) in @@ -5243,7 +5297,7 @@ let start ~tags:(Timeline_filter.tags criteria) ~statuses:(Timeline_filter.statuses criteria) ~days; submit (Journal_graph_request.Load_feed - { cursor = None; root_limit = feed_root_limit + { cursor = None; root_limit = initial_feed_root_limit ; day_limit = feed_day_limit ; request_generation = feed_generation }) @@ -6146,7 +6200,7 @@ let start let output = submit (Journal_graph_request.Load_feed - { cursor = None; root_limit = feed_root_limit + { cursor = None; root_limit = initial_feed_root_limit ; day_limit = feed_day_limit ; request_generation = generation }) @@ -6405,7 +6459,10 @@ let start let output=Journal_graph_runtime.resume_insertion_recovery (!graph_runtime_cell) ~root recovery in let delivery=deliver_output output in Effect.run(apply_graph_responses set_state_and_effect delivery.responses))); - let startup_loading_key state = Journal_startup.Presentation.loading_request state.startup_presentation in + let startup_loading_key state = + if platform_code = 2 && Journal_startup.Presentation.initial_attempt state.startup_presentation + then None else Journal_startup.Presentation.loading_request state.startup_presentation + in let prev_startup_loading_key = ref None in let arm_startup_loading_timer key = let started = Mtime_clock.counter () in @@ -8372,8 +8429,11 @@ let start ~store:timeline_store ~media_store ~dispatch state |> fun content -> V.of_lui (Lui_elements.stack ~grow:1. ~on_appear:(fun _ -> Option.iter (fun scope -> - if model_key !state_ref=Some(owner_key scope) then - Effect.run (send_manager (Graph_service.Acknowledge_timeline_presented scope))) (timeline_scope state)) + if model_key !state_ref=Some(owner_key scope) then ( + if not !startup_timeline_presented then ( + startup_timeline_presented := true; + log_startup_stage ~stage:"app.timeline_presented" ()); + Effect.run (send_manager (Graph_service.Acknowledge_timeline_presented scope)))) (timeline_scope state)) [Ui.mount content])) in let capture_adapter = @@ -8836,6 +8896,7 @@ let start if model_key state=Some source then ( if action="presented" then Option.iter (fun scope-> Effect.run(send_manager(Graph_service.Acknowledge_timeline_presented scope))) (timeline_scope state) + else if action="choose-graph" && show_graphs state then dispatch.send Switch_graph else let target=member "target" event |> to_string in match action with | "cancel" when !preview_owner=Some target -> dispatch.send Graph_swipe_cancel diff --git a/app/journal_graph_feed_plan.ml b/app/journal_graph_feed_plan.ml index 680cad8e..01d06f85 100644 --- a/app/journal_graph_feed_plan.ml +++ b/app/journal_graph_feed_plan.ml @@ -73,11 +73,15 @@ type root_batch = ; root_next : Projection.root_cursor option ; root_members : Projection.tree_member Rrbvec.t ; root_proofs : proofs - ; root_todo : Projection.tree_member Rrbvec.t + ; mutable root_pending_previews : int + ; mutable root_preview_results : Projection.tree_member Rrbvec.t array + ; mutable root_preview_queue : (int * Projection.tree_member) list + ; mutable root_batch_aborted : bool } type root_preview = { preview_batch : root_batch + ; preview_index : int ; preview_root : Projection.tree_member ; preview_members : Projection.tree_member Rrbvec.t ; preview_cursor : Worker_pure_data.child_member Paging.cursor option @@ -218,7 +222,8 @@ let root_owner_current t = function ;; let root_batch_current t batch = - root_owner_current t batch.root_owner + (not batch.root_batch_aborted) + && root_owner_current t batch.root_owner && Hashtbl.find_opt t.root_page_epochs batch.root_page.Projection.id = Some batch.root_epoch ;; @@ -230,6 +235,7 @@ let scan_failure scan message = ;; let root_failure batch message = + batch.root_batch_aborted <- true; match batch.root_owner with | Feed_roots scan -> scan_failure scan message | Changed_roots _ -> reject message @@ -258,7 +264,10 @@ let make_root_batch t ~ports owner ~page_uuid (page : Projection.page) cursor li ; root_next = None ; root_members = Rrbvec.empty ; root_proofs = Hashtbl.create 8 - ; root_todo = Rrbvec.empty + ; root_pending_previews = 0 + ; root_preview_results = [||] + ; root_preview_queue = [] + ; root_batch_aborted = false } ;; @@ -745,22 +754,44 @@ let read_root_preview t ~ports preview = request ;; -let next_root_preview t ~ports batch = +let max_concurrent_root_previews = 8 + +let start_root_previews t ~ports batch todo = if not (root_batch_current t batch) then empty else ( - match Rrbvec.pop_front batch.root_todo with - | None -> check t ~ports (Assemble batch) - | Some (root, rest) -> - let preview = - { preview_batch = { batch with root_todo = rest } - ; preview_root = root - ; preview_members = Rrbvec.empty - ; preview_cursor = None - ; preview_limit = 3 - } + let count = Rrbvec.length todo in + if count = 0 + then check t ~ports (Assemble batch) + else ( + batch.root_pending_previews <- count; + batch.root_preview_results <- Array.make count Rrbvec.empty; + let indexed = + Rrbvec.to_seq todo |> Seq.mapi (fun index root -> index, root) |> List.of_seq + in + let rec split n acc = function + | rest when n <= 0 -> List.rev acc, rest + | [] -> List.rev acc, [] + | head :: tail -> split (n - 1) (head :: acc) tail + in + let initial, queued = split max_concurrent_root_previews [] indexed in + batch.root_preview_queue <- queued; + let planned = + List.map + (fun (index, root) -> + read_root_preview + t + ~ports + { preview_batch = batch + ; preview_index = index + ; preview_root = root + ; preview_members = Rrbvec.empty + ; preview_cursor = None + ; preview_limit = 3 + }) + initial in - requests [ read_root_preview t ~ports preview ]) + requests planned)) ;; let start_feed_scan t ~ports ~cursor ~root_limit ~day_limit ~request_generation ?(reuse=false) ?after () = @@ -857,8 +888,10 @@ let start_feed_scan t ~ports ~cursor ~root_limit ~day_limit ~request_generation ;; let superseded_root_batch t ~ports batch = match batch.root_owner with - | Feed_roots scan when root_owner_current t batch.root_owner + | Feed_roots scan when (not batch.root_batch_aborted) + && root_owner_current t batch.root_owner && Hashtbl.mem t.root_page_limits batch.root_page.id -> + batch.root_batch_aborted <- true; (match scan.root_start_day with | None -> (* A canonical local completion can invalidate a page while startup is @@ -921,8 +954,8 @@ let receive_root_tree t ~ports batch (packet : Worker_pure_data.tree_member Pagi Hashtbl.replace t.root_page_limits id (max batch.root_limit (Option.value ~default:1 (Hashtbl.find_opt t.root_page_limits id))); ports.retain_root_interest batch.root_page ~minimum_limit:batch.root_limit); - next_root_preview t ~ports - {batch with root_members=members;root_todo=todo;root_next=next_cursor}) + start_root_previews t ~ports + {batch with root_members=members;root_next=next_cursor} todo) ;; let receive_root_preview t ~ports preview (packet : Worker_pure_data.child_member Paging.packet) = @@ -990,8 +1023,32 @@ let receive_root_preview t ~ports preview (packet : Worker_pure_data.child_membe ; preview_cursor = next_cursor } ] - else - next_root_preview t ~ports { batch with root_members = Rrbvec.append batch.root_members selected })) + else ( + batch.root_preview_results.(preview.preview_index) <- selected; + batch.root_pending_previews <- batch.root_pending_previews - 1; + if batch.root_pending_previews = 0 + then ( + let all_members = + Array.fold_left Rrbvec.append batch.root_members batch.root_preview_results + in + check t ~ports (Assemble { batch with root_members = all_members })) + else ( + match batch.root_preview_queue with + | [] -> empty + | (next_index, next_root) :: rest -> + batch.root_preview_queue <- rest; + requests + [ read_root_preview + t + ~ports + { preview_batch = batch + ; preview_index = next_index + ; preview_root = next_root + ; preview_members = Rrbvec.empty + ; preview_cursor = None + ; preview_limit = 3 + } + ])))) ;; let stale_continuation scan = @@ -1001,6 +1058,7 @@ let stale_continuation scan = ;; let restart_batch t ~ports batch = + batch.root_batch_aborted <- true; let proofs = owner_proofs batch.root_owner in Hashtbl.filter_map_inplace (fun scope proof -> if scope_page scope = Some batch.root_page.id then None else Some proof) proofs; @@ -1183,7 +1241,12 @@ let failure_scope = function | Root_dates (scan, _) | Root_today (scan, _) -> (match scan.root_start_day with None -> Feed scan.root_generation | Some day -> Day {day;request_generation=scan.root_generation}) - | Root_tree batch | Root_preview {preview_batch=batch;_} -> + | Root_tree batch -> + (match batch.root_owner with Changed_roots _ -> Reconciliation + | Feed_roots scan -> match scan.root_start_day with None -> Feed scan.root_generation + | Some day -> Day {day;request_generation=scan.root_generation}) + | Root_preview {preview_batch=batch;_} -> + batch.root_preview_queue <- []; (match batch.root_owner with Changed_roots _ -> Reconciliation | Feed_roots scan -> match scan.root_start_day with None -> Feed scan.root_generation | Some day -> Day {day;request_generation=scan.root_generation}) @@ -1360,7 +1423,9 @@ let failed t ~ports operation ~code = read_root_dates t ~ports scan | Root_tree batch, Logseq_db_worker.Error.Response_too_large when batch.root_limit>1 -> let limit=max 1 (batch.root_limit/2) in - (match batch.root_owner with Feed_roots scan->scan.root_page_size<-limit | _->()); + (match batch.root_owner with + | Feed_roots scan -> scan.root_page_size <- limit + | _ -> ()); continue_root_batch t ~ports batch.root_owner batch.root_page batch.root_cursor limit | Root_preview preview, Logseq_db_worker.Error.Response_too_large when preview.preview_limit>1 -> requests [read_root_preview t ~ports {preview with preview_limit=max 1 (preview.preview_limit/2); diff --git a/app/journal_header.ml b/app/journal_header.ml index 8ae4016d..3e3d4f4c 100644 --- a/app/journal_header.ml +++ b/app/journal_header.ml @@ -23,12 +23,12 @@ module Json = struct type props = { mode : string; title : string option [@default None]; connecting : bool option [@default None]; controls : bool option [@default None] ; text : string option [@default None]; id : string option [@default None]; level : int option [@default None] - ; loading : bool option [@default None]; initial : bool option [@default None]; active : bool option [@default None]; value : float option [@default None]; message : string option [@default None] } + ; canChoose : bool option [@default None]; loading : bool option [@default None]; initial : bool option [@default None]; active : bool option [@default None]; value : float option [@default None]; message : string option [@default None] } [@@deriving yojson] end -let props ~mode ?title ?connecting ?controls ?text ?id ?level ?loading ?initial ?active ?value ?message () : Json.props = - { mode; title; connecting; controls; text; id; level; loading; initial; active; value; message } +let props ~mode ?title ?connecting ?controls ?text ?id ?level ?canChoose ?loading ?initial ?active ?value ?message () : Json.props = + { mode; title; connecting; controls; text; id; level; canChoose; loading; initial; active; value; message } ;; let chrome = @@ -39,6 +39,7 @@ let chrome = match Journal_ids.Native_widget.Event_id.to_int event_id, Bytes.to_string bytes with | 1, "journals" -> Ok `Journals | 1, "favorites" -> Ok `Favorites + | 1, "choose-graph" -> Ok `Choose_graph | 1, "capture" -> Ok `Capture | _ -> Error "Unknown Journal chrome event") () @@ -80,11 +81,11 @@ let date_header ?relative_label ~title () = () ;; -let startup ~loading ~initial ~active ?value ~message action = +let startup ?on_choose ~loading ~initial ~active ?value ~message action = Ui.Native_widget.widget chrome ~key:(Ui.Key.string "journal-startup-surface") - ~props:(props ~mode:"startup" ~loading ~initial ~active ~message ?value ()) - ~on_event:(fun _ -> ()) ~children:[V.column [action]] () |> V.Body.static + ~props:(props ~mode:"startup" ~canChoose:(Option.is_some on_choose) ~loading ~initial ~active ~message ?value ()) + ~on_event:(function `Choose_graph -> Option.iter (fun choose -> choose ()) on_choose | _ -> ()) ~children:[V.column [action]] () |> V.Body.static ;; let capture_control ~enabled ~on_capture = @@ -480,6 +481,7 @@ let view_impl in match action with | `Journals -> invoke on_journals + | `Choose_graph -> () | `Favorites -> invoke on_favorites | `Capture -> let current = Option.fold ~none:initial ~some:Signal.sample presentation_signal in diff --git a/app/journal_header.mli b/app/journal_header.mli index b41d2030..35113087 100644 --- a/app/journal_header.mli +++ b/app/journal_header.mli @@ -83,7 +83,7 @@ val detail -> Journal_view.View.Body.t (** Stable native startup surface; action remains reachable during waiting. *) -val startup : loading:bool -> initial:bool -> active:bool -> ?value:float +val startup : ?on_choose:(unit -> unit) -> loading:bool -> initial:bool -> active:bool -> ?value:float -> message:string -> Journal_view.View.t -> Journal_view.View.Body.t (** Full-canvas native list with floating close and catalog controls. *) diff --git a/app/journal_manager_view.ml b/app/journal_manager_view.ml index 05e8c8f1..d8e02f3a 100644 --- a/app/journal_manager_view.ml +++ b/app/journal_manager_view.ml @@ -167,7 +167,8 @@ let view ?picker_signal props ~on_action = "folder" in let busy ({ loading; initial; active; value; message; choose_graph = choose } : busy) = - Journal_header.startup ~loading ~initial ~active ?value ~message + Journal_header.startup ?on_choose:(if choose then Some (fun () -> on_action Switch_graph) else None) + ~loading ~initial ~active ?value ~message (if choose then choose_graph else V.empty ()) in let graph_picker snapshot = diff --git a/app/journal_startup.ml b/app/journal_startup.ml index d2e20511..204a7674 100644 --- a/app/journal_startup.ml +++ b/app/journal_startup.ml @@ -208,6 +208,7 @@ module Presentation = struct type account = Discovering | Local_available | User_available | User_required type t = { screen : screen + ; initial : bool ; serial : int64 ; account_serial : int64 ; indicator : bool @@ -227,7 +228,7 @@ module Presentation = struct | Elapsed of ticket * float let create () = - { screen = Waiting; serial = 0L; account_serial = 0L; indicator = false + { screen = Waiting; initial = true; serial = 0L; account_serial = 0L; indicator = false ; foreground = true; account = Discovering; local_available = false ; account_failed = false; observed = None } let foreground t = t.foreground @@ -236,7 +237,7 @@ module Presentation = struct let loading_request t = if t.foreground && t.screen = Waiting && not t.indicator then Some t.serial else None let account_ticket t = t.account_serial - let initial_attempt t = t.serial = 0L + let initial_attempt t = t.initial let equal_presentation left right = left.screen = right.screen && (left.screen <> Waiting || @@ -269,7 +270,7 @@ module Presentation = struct let next = classify t in if next = t.screen then t else if next = Waiting then - {t with screen=next;serial=Int64.succ t.serial;indicator=false} + {t with screen=next;initial=false;serial=Int64.succ t.serial;indicator=false} else {t with screen=next;indicator=false} let step t event = @@ -296,7 +297,7 @@ module Presentation = struct project {t with account;local_available;account_failed=false} | Account_error key when key=t.account_serial -> project {t with account_failed=true} | Retry -> - {t with screen=Waiting;serial=Int64.succ t.serial;account_serial=Int64.succ t.account_serial; + {t with screen=Waiting;initial=false;serial=Int64.succ t.serial;account_serial=Int64.succ t.account_serial; indicator=false;account=Discovering;local_available=false;account_failed=false;observed=None} | Signed_out -> {t with screen=required Signed_out;indicator=false;account=User_required; diff --git a/apple-tests/application-platform/JournalApplicationPlatformTests.swift b/apple-tests/application-platform/JournalApplicationPlatformTests.swift index 599bdaed..933048ae 100644 --- a/apple-tests/application-platform/JournalApplicationPlatformTests.swift +++ b/apple-tests/application-platform/JournalApplicationPlatformTests.swift @@ -16,6 +16,15 @@ struct JournalEnvironmentSample: Equatable, Codable {} } @main struct JournalApplicationPlatformTests { @MainActor static func main() async throws { + let clock = JournalStartupClock() + clock.begin(after: .zero) + while clock.phase == .waitingBeforeDeadline { await Task.yield() } + clock.requestPicker() + clock.deliverPicker {} + precondition(clock.phase == .pickerRequested, "dispatch is not presentation") + var retried = false + clock.deliverPicker { retried = true } + precondition(retried) func packet(_ tag: UInt8) -> Data { var bytes = Data("LJP2".utf8); bytes.append(contentsOf: [2,0,tag,0]); bytes.append(Data(repeating:0,count:24)); return bytes } diff --git a/apple-tests/warm-start/JournalWarmStartAcceptance.swift b/apple-tests/warm-start/JournalWarmStartAcceptance.swift index 4c34d9ac..0dc8d964 100644 --- a/apple-tests/warm-start/JournalWarmStartAcceptance.swift +++ b/apple-tests/warm-start/JournalWarmStartAcceptance.swift @@ -206,6 +206,7 @@ private struct WarmFixture: Decodable { @State private var probe: WarmProbe @State private var activeScene = true private let registry: LUIAppleExtensionRegistry + private let prestartedRuntime: JournalRuntime? init() { // This executable is test-only; never access the user's native secrets. @@ -241,7 +242,22 @@ private struct WarmFixture: Decodable { missing: arguments.contains("--missing-key"), report: path.appendingPathExtension("observations.jsonl")) probe.observePlatform() _probe = State(initialValue: probe) - self.registry = try JournalExtensions.registry() + let registry = try JournalExtensions.registry() + self.registry = registry + if !arguments.contains("--pump-only"), + let runtime = try? JournalRuntime( + platform: probe.platform, + startupPayload: probe.payload, + extensionRegistry: registry) { + if (try? runtime.start()) != nil { + self.prestartedRuntime = runtime + } else { + runtime.stop() + self.prestartedRuntime = nil + } + } else { + self.prestartedRuntime = nil + } } catch { fatalError("Fixture setup failed: \(error)") } } @@ -291,7 +307,7 @@ private struct WarmFixture: Decodable { Text("Inspecting the public native runtime").task { await probe.inspectFirstFrame() } } else { JournalRuntimeHost(platform: probe.platform, payload: probe.payload, - extensions: registry) + extensions: registry, prestarted: prestartedRuntime) .font(.body) .preferredColorScheme(ProcessInfo.processInfo.arguments.contains("--dark-appearance") ? .dark : ProcessInfo.processInfo.arguments.contains("--light-appearance") ? .light : nil) diff --git a/logseq_db_storage/lib/logseq_sqlite_storage.ml b/logseq_db_storage/lib/logseq_sqlite_storage.ml index 59753384..1159ce51 100644 --- a/logseq_db_storage/lib/logseq_sqlite_storage.ml +++ b/logseq_db_storage/lib/logseq_sqlite_storage.ml @@ -60,6 +60,7 @@ type connection = { sqlite : Sqlite3.db ; storage : Datascript.storage ; callbacks : callbacks + ; active_restore_cache : (string, Datascript.storage_payload) Hashtbl.t option ref } type startup_metadata = @@ -374,8 +375,7 @@ let open_database path = Sqlite3.Rc.check (Sqlite3.exec sqlite - "SELECT CAST(addr AS TEXT) FROM kvs WHERE typeof(addr) <> 'integer' OR addr < \ - 0 LIMIT 1" + "SELECT CAST(addr AS TEXT) FROM kvs WHERE addr < 0 LIMIT 1" ~cb:(fun row _ -> invalid_address := row.(0))); match !invalid_address with | Some address -> @@ -385,35 +385,62 @@ let open_database path = let capture : (string, Datascript.storage_payload) Hashtbl.t option ref = ref None in + let restore_statement = + Sqlite3.prepare sqlite "SELECT content, addresses FROM kvs WHERE addr = ?" + in + let active_restore_cache : (string, Datascript.storage_payload) Hashtbl.t option ref = + ref None + in + let decode_addresses statement = + if Sqlite3.column_is_null statement 1 + then [] + else ( + match + storage_addresses_of_yojson + (Yojson.Safe.from_string (Sqlite3.column_text statement 1)) + with + | Ok values -> List.map Int64.to_string values + | Error message -> invalid_arg ("invalid addresses JSON: " ^ message)) + in + let read_raw_row address = + match Int64.of_string_opt address with + | None -> None + | Some addr_int -> + Fun.protect + ~finally:(fun () -> + ignore (Sqlite3.reset restore_statement); + ignore (Sqlite3.clear_bindings restore_statement)) + (fun () -> + Sqlite3.Rc.check (Sqlite3.bind_int64 restore_statement 1 addr_int); + match Sqlite3.step restore_statement with + | Sqlite3.Rc.ROW -> + let content = Sqlite3.column_text restore_statement 0 in + let addresses = decode_addresses restore_statement in + Some (content, addresses) + | DONE -> None + | rc -> + Sqlite3.Rc.check rc; + None) + in let restore_sqlite address = - prepared - sqlite - "SELECT content, addresses FROM kvs WHERE addr = ?" - (fun statement -> Sqlite3.Rc.check (Sqlite3.bind_text statement 1 address)) - (fun statement -> - match Sqlite3.step statement with - | Sqlite3.Rc.ROW -> - let content = Sqlite3.column_text statement 0 in - let addresses = - if Sqlite3.column_is_null statement 1 - then [] - else ( - match - storage_addresses_of_yojson - (Yojson.Safe.from_string (Sqlite3.column_text statement 1)) - with - | Ok values -> List.map Int64.to_string values - | Error message -> invalid_arg ("invalid addresses JSON: " ^ message)) - in - (match - Logseq_sqlite_codec.decode_physical_payload ~content ~addresses - with - | Ok payload -> Some payload - | Error error -> invalid_arg (Logseq_sqlite_codec.diagnostic_error error)) - | DONE -> None - | rc -> - Sqlite3.Rc.check rc; - None) + let cached = + Option.bind !active_restore_cache (fun cache -> Hashtbl.find_opt cache address) + in + match cached with + | Some payload -> Some payload + | None -> + (match read_raw_row address with + | None -> None + | Some (content, addresses) -> + (match + Logseq_sqlite_codec.decode_physical_payload ~content ~addresses + with + | Ok payload -> + Option.iter + (fun cache -> Hashtbl.replace cache address payload) + !active_restore_cache; + Some payload + | Error error -> invalid_arg (Logseq_sqlite_codec.diagnostic_error error))) in let list_addresses () = let addresses = ref [] in @@ -540,30 +567,23 @@ let open_database path = ; terminal_batch_receipts = None }) in - let initial_root_metadata = - prepared - sqlite - "SELECT content FROM kvs WHERE addr = 0" - (fun _ -> ()) - (fun statement -> - match Sqlite3.step statement with - | Sqlite3.Rc.ROW -> - (match - Logseq_sqlite_codec.decode_root_index_metadata - (Sqlite3.column_text statement 0) - with - | Ok metadata -> Some metadata - | Error _ -> None) - | DONE -> None - | rc -> - Sqlite3.Rc.check rc; - None) - in - let initial_root_addresses = - match restore_sqlite Datascript.Storage.root_address with - | Some (Datascript.Storage_root root) -> - Some [ root.storage_eavt; root.storage_aevt; root.storage_avet ] - | Some (Storage_node _ | Storage_tail _) | None -> None + let initial_root_metadata, initial_root_addresses = + match read_raw_row Datascript.Storage.root_address with + | None -> None, None + | Some (content, addresses) -> + let metadata = + match Logseq_sqlite_codec.decode_root_index_metadata content with + | Ok metadata -> Some metadata + | Error _ -> None + in + let root_addresses = + match Logseq_sqlite_codec.decode_physical_payload ~content ~addresses with + | Ok (Datascript.Storage_root root) -> + Some [ root.storage_eavt; root.storage_aevt; root.storage_avet ] + | Ok (Storage_node _ | Storage_tail _) -> None + | Error error -> invalid_arg (Logseq_sqlite_codec.diagnostic_error error) + in + metadata, root_addresses in let unreachable_address_count_sql = Option.map @@ -630,10 +650,12 @@ let open_database path = ; checkpoint = exec "PRAGMA wal_checkpoint(TRUNCATE)" ; close = (fun () -> + active_restore_cache := None; + ignore (Sqlite3.finalize restore_statement); if Sqlite3.db_close sqlite then Ok () else Error (Sqlite3.errmsg sqlite)) } in - Ok { sqlite; storage; callbacks }) + Ok { sqlite; storage; callbacks; active_restore_cache }) with | exn -> Error (Begin_failed (exception_source exn)) ;; @@ -692,7 +714,10 @@ let validate_storage_header connection = ( Logseq_sqlite_codec.decode_physical_payload ~content ~addresses:[] , Logseq_sqlite_codec.decode_root_index_metadata content ) with - | Ok (Datascript.Storage_root root), Ok _metadata -> + | Ok (Datascript.Storage_root root as payload), Ok _metadata -> + Option.iter + (fun cache -> Hashtbl.replace cache Datascript.Storage.root_address payload) + !(connection.active_restore_cache); let require_index label address = match connection.storage.storage_restore address with | Some (Datascript.Storage_node _) -> Ok () @@ -718,14 +743,19 @@ let validate_storage_header connection = let restore_database connection = let corrupt message = Error (Corrupt_storage message) in - match validate_storage_header connection with - | Error _ as error -> error - | Ok () -> - (try - match Datascript.restore connection.storage with - | Some db -> Ok db - | None -> corrupt "DataScript restore returned no database" - with - | Invalid_argument message -> corrupt message - | exn -> corrupt (Printexc.to_string exn)) + let previous = !(connection.active_restore_cache) in + connection.active_restore_cache := Some (Hashtbl.create 8); + Fun.protect + ~finally:(fun () -> connection.active_restore_cache := previous) + (fun () -> + match validate_storage_header connection with + | Error _ as error -> error + | Ok () -> + (try + match Datascript.restore connection.storage with + | Some db -> Ok db + | None -> corrupt "DataScript restore returned no database" + with + | Invalid_argument message -> corrupt message + | exn -> corrupt (Printexc.to_string exn))) ;; diff --git a/logseq_db_storage/lib/mutation_receipt_store.ml b/logseq_db_storage/lib/mutation_receipt_store.ml index 3f1e24c0..7ed60909 100644 --- a/logseq_db_storage/lib/mutation_receipt_store.ml +++ b/logseq_db_storage/lib/mutation_receipt_store.ml @@ -12,20 +12,39 @@ let valid_key key = ;; let initialize_database db = - Result.bind - (rc_result - db - (Sqlite3.exec - db - "CREATE TABLE IF NOT EXISTS overlay_mutation_receipts (receipt_key TEXT \ - PRIMARY KEY CHECK(length(receipt_key) = 64), receipt TEXT NOT NULL)")) - (fun () -> - rc_result + let existing = ref 0 in + let check = + rc_result + db + (Sqlite3.exec + db + "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name IN \ + ('overlay_mutation_receipts', 'overlay_terminal_batch_receipts')" + ~cb:(fun row _ -> + match row.(0) with + | Some count -> + (match int_of_string_opt count with + | Some n -> existing := n + | None -> ()) + | None -> ())) + in + match check with + | Ok () when !existing = 2 -> Ok () + | _ -> + Result.bind + (rc_result db (Sqlite3.exec db - "CREATE TABLE IF NOT EXISTS overlay_terminal_batch_receipts (batch_key TEXT \ - PRIMARY KEY CHECK(length(batch_key) = 64), receipt TEXT NOT NULL)")) + "CREATE TABLE IF NOT EXISTS overlay_mutation_receipts (receipt_key TEXT \ + PRIMARY KEY CHECK(length(receipt_key) = 64), receipt TEXT NOT NULL)")) + (fun () -> + rc_result + db + (Sqlite3.exec + db + "CREATE TABLE IF NOT EXISTS overlay_terminal_batch_receipts (batch_key TEXT \ + PRIMARY KEY CHECK(length(batch_key) = 64), receipt TEXT NOT NULL)")) ;; let read_database db = diff --git a/logseq_db_worker/lib/effect_runner/effect_runner.ml b/logseq_db_worker/lib/effect_runner/effect_runner.ml index 6251750b..d55b29b0 100644 --- a/logseq_db_worker/lib/effect_runner/effect_runner.ml +++ b/logseq_db_worker/lib/effect_runner/effect_runner.ml @@ -1531,6 +1531,7 @@ let read_typed | _ -> Ok version) in match query with |Read.Timeline_read {query=timeline_query;after}->with_snapshot(fun snapshot record _ -> + let t_query_start = Unix.gettimeofday () in let module Timeline=Read.Timeline in let source_error error = match error with |Overlay.Read_limit_exceeded->Timeline.Limit_exceeded "Timeline source exceeded its structural bound" @@ -1604,6 +1605,19 @@ let read_typed else if limit>1 then bounded(max 1(limit/2)) else Error(Timeline.Limit_exceeded "Timeline packet exceeds its final encoded byte bound")) in bounded limit))) in + (let elapsed_ms = (Unix.gettimeofday () -. t_query_start) *. 1000. in + if elapsed_ms >= 2. then + let kind = match timeline_query with + | Timeline.Dates _ -> "dates" + | Roots _ -> "roots" + | Roots_through_grandchildren _ -> "roots_filtered" + | Preview_children _ -> "preview_children" + in + (try + Printf.eprintf + "journal-startup: {\"stage\":\"worker.timeline_read\",\"kind\":%S,\"elapsed_ms\":%.2f}\n%!" + kind elapsed_ms + with Sys_error _ -> ())); Ok value) |Read.Timeline_check receipts->with_snapshot(fun snapshot _ _ -> let module Timeline=Read.Timeline in @@ -2641,7 +2655,9 @@ let release_host_copy t ~registration =match t.host_copy with let handle_sync_worker_effect t = function | Sync.Inspect_mirror request -> + let t0 = Unix.gettimeofday () in let recovery = with_staging_lock t (fun () -> recover_local_retirements t request.scope) in + let t1 = Unix.gettimeofday () in (match recovery with | Error message -> Error (effect_error message) | Ok () -> @@ -2653,15 +2669,25 @@ let handle_sync_worker_effect t = function with | Error error -> Error (mirror_error error) | Ok inspection -> + let t2 = Unix.gettimeofday () in Hashtbl.replace t.inspections (Graph.Uuid.to_string request.graph.graph_id) inspection; - (match Database.mirror_presence inspection with - | Overlay.Absent _ -> - Ok (sync_result ~event:(Sync.Mirror_inspected (Mirror_absent request.scope)) ()) - | Available _ -> - Ok (sync_result ~event:(Sync.Mirror_inspected (Mirror_available request)) ())))) + let presence_label, event = + match Database.mirror_presence inspection with + | Overlay.Absent _ -> "absent", Sync.Mirror_inspected (Mirror_absent request.scope) + | Available _ -> "available", Sync.Mirror_inspected (Mirror_available request) + in + (try + Printf.eprintf + "journal-startup: {\"stage\":\"worker.inspect_mirror\",\"presence\":%S,\"recover_ms\":%.2f,\"inspect_ms\":%.2f,\"total_ms\":%.2f}\n%!" + presence_label + ((t1 -. t0) *. 1000.) + ((t2 -. t1) *. 1000.) + ((t2 -. t0) *. 1000.) + with Sys_error _ -> ()); + Ok (sync_result ~event ()))) | Activate_snapshot request -> let key = Graph.Uuid.to_string (Sync.snapshot_activation_scope request).graph_id in (match Hashtbl.find_opt t.inspections key with @@ -2830,6 +2856,7 @@ let handle_sync_worker_effect t = function in Ok (sync_result ~event:(Sync.Mirror_deleted (request, result)) ()) | Attach_graph request -> + let t0 = Unix.gettimeofday () in (match t.latest_snapshot with | Some snapshot when snapshot.resident_graphs<>[] -> () | _ -> ignore (close_attached t)); @@ -2837,11 +2864,13 @@ let handle_sync_worker_effect t = function (match Hashtbl.find_opt t.inspections key with | None -> Error (effect_error "The graph attachment inspection is stale.") | Some inspection -> + let t_open_start = Unix.gettimeofday () in (match Database.open_ ~sw:t.sw t.dependencies.overlay inspection ~graph_name:request.graph.name with | Error error -> Error (open_error error) | Ok database -> + let t_open_end = Unix.gettimeofday () in (match Database.listen database with | Error error -> ignore (Database.close database); @@ -2873,7 +2902,9 @@ let handle_sync_worker_effect t = function ignore (close_database_by_id t database_id); Error (listen_error error) | Ok () -> + let t_listen_end = Unix.gettimeofday () in let sync = Database.inspect_sync database in + let t_sync_end = Unix.gettimeofday () in let opened = Core.database_opened ~database_id ~graph_id:request.graph.graph_id in @@ -2882,6 +2913,14 @@ let handle_sync_worker_effect t = function ignore (close_database_by_id t database_id); Error (sync_read_error error) | Ok sync -> + (try + Printf.eprintf + "journal-startup: {\"stage\":\"worker.attach_graph\",\"open_ms\":%.2f,\"listen_ms\":%.2f,\"inspect_sync_ms\":%.2f,\"total_ms\":%.2f}\n%!" + ((t_open_end -. t_open_start) *. 1000.) + ((t_listen_end -. t_open_end) *. 1000.) + ((t_sync_end -. t_listen_end) *. 1000.) + ((t_sync_end -. t0) *. 1000.) + with Sys_error _ -> ()); Ok (sync_result ~event:(Sync.Graph_attached { scope = request.scope; sync }) diff --git a/logseq_overlay_db/lib/database.ml b/logseq_overlay_db/lib/database.ml index 97525b02..c8dd36f2 100644 --- a/logseq_overlay_db/lib/database.ml +++ b/logseq_overlay_db/lib/database.ml @@ -2019,32 +2019,28 @@ let decode_outbox records = loop [] [] 0 0 records ;; -let read_outbox path = - let sqlite = Sqlite3.db_open ~mode:`NO_CREATE path in - Fun.protect - ~finally:(fun () -> (if not (Sqlite3.db_close sqlite) then report_warning "journal: phase=cleanup operation=closeSqlite scope=temporaryStorageHandle code=closePending recovery=reopen\n" )) - (fun () -> - let exec sql = - let rc = Sqlite3.exec sqlite sql in - if Sqlite3.Rc.is_success rc then Ok () else Error (Sqlite3.errmsg sqlite) - in - Result.bind (exec "BEGIN") (fun () -> - let result = - try - Result.bind (Logseq_db_storage.Sync_outbox_store.read_database sqlite) - (fun records -> - Result.map - (fun revision -> records, revision) - (Logseq_db_storage.Sync_outbox_store.read_revision sqlite)) - with - | exn -> Error (Printexc.to_string exn) - in - match result with - | Error _ as error -> ignore (exec "ROLLBACK"); error - | Ok _ -> - (match exec "COMMIT" with - | Ok () -> result - | Error _ as error -> ignore (exec "ROLLBACK"); error))) +let read_outbox_with_sqlite sqlite = + let exec sql = + let rc = Sqlite3.exec sqlite sql in + if Sqlite3.Rc.is_success rc then Ok () else Error (Sqlite3.errmsg sqlite) + in + Result.bind (exec "BEGIN") (fun () -> + let result = + try + Result.bind (Logseq_db_storage.Sync_outbox_store.read_database sqlite) + (fun records -> + Result.map + (fun revision -> records, revision) + (Logseq_db_storage.Sync_outbox_store.read_revision sqlite)) + with + | exn -> Error (Printexc.to_string exn) + in + match result with + | Error _ as error -> ignore (exec "ROLLBACK"); error + | Ok _ -> + (match exec "COMMIT" with + | Ok () -> result + | Error _ as error -> ignore (exec "ROLLBACK"); error)) ;; (* Global revision belongs to metadata. Frozen encodings are independent of it @@ -2093,21 +2089,6 @@ let outbox_write_set database ~revision records = , rows ) ;; -let migrate_outbox path ~revision ~expected_records rows = - let sqlite = Sqlite3.db_open ~mode:`NO_CREATE path in - Fun.protect ~finally:(fun () -> (if not (Sqlite3.db_close sqlite) then report_warning "journal: phase=cleanup operation=closeSqlite scope=temporaryStorageHandle code=closePending recovery=reopen\n" )) (fun () -> - Logseq_db_storage.Sync_outbox_store.migrate_database sqlite ~revision ~expected_records - (ordered_durable_rows rows)) -;; - -let initialize_durable_receipts path = - let sqlite = Sqlite3.db_open ~mode:`NO_CREATE path in - Fun.protect - ~finally:(fun () -> (if not (Sqlite3.db_close sqlite) then report_warning "journal: phase=cleanup operation=closeSqlite scope=temporaryStorageHandle code=closePending recovery=reopen\n" )) - (fun () -> - Logseq_db_storage.Mutation_receipt_store.initialize_database sqlite) -;; - let with_receipt_database path read = try let sqlite = Sqlite3.db_open ~mode:`NO_CREATE path in @@ -4277,20 +4258,37 @@ let authoritative_tree_candidate snapshot cache uuid = let database = Option.get snapshot.authoritative_database in let candidate = Option.bind (tree_entity snapshot cache uuid) (fun entity -> - let fields = - List.concat_map - (fun a -> - Datascript.datoms database Datascript.Eavt ~e:entity ~a () |> List.of_seq) - tree_identity_fields + let fields = ref [] in + let b_uuid = ref None and c_uuid = ref 0 in + let b_title = ref None and c_title = ref 0 in + let b_parent = ref None and c_parent = ref 0 in + let b_page = ref None and c_page = ref 0 in + let b_order = ref None and c_order = ref 0 in + let record_single cell count parse value = + incr count; + if !count = 1 then cell := parse value else cell := None in - Hashtbl.add cache.fields entity fields; - match - ( Option.bind (one_in_datoms fields "block/uuid") uuid_of_value - , Option.bind (one_in_datoms fields "block/title") string_of_value - , Option.bind (one_in_datoms fields "block/parent") reference_of_value - , Option.bind (one_in_datoms fields "block/page") reference_of_value - , Option.bind (one_in_datoms fields "block/order") string_of_value ) - with + Datascript.datoms database Datascript.Eavt ~e:entity () + |> Seq.iter (fun (datom : Datascript.datom) -> + match datom.a with + | "block/uuid" -> + fields := datom :: !fields; + record_single b_uuid c_uuid uuid_of_value datom.v + | "block/title" -> + fields := datom :: !fields; + record_single b_title c_title string_of_value datom.v + | "block/parent" -> + fields := datom :: !fields; + record_single b_parent c_parent reference_of_value datom.v + | "block/page" -> + fields := datom :: !fields; + record_single b_page c_page reference_of_value datom.v + | "block/order" -> + fields := datom :: !fields; + record_single b_order c_order string_of_value datom.v + | _ -> ()); + Hashtbl.add cache.fields entity (List.rev !fields); + match !b_uuid, !b_title, !b_parent, !b_page, !b_order with | Some tree_uuid, Some _, Some parent, Some page, Some tree_order -> (match ( cached_uuid_of_entity database cache.hydration parent @@ -4707,7 +4705,10 @@ let timeline_direct_candidates ?(charge = fun _ -> ()) ~truncate snapshot parent | Some entity -> Datascript.datoms database Datascript.Avet ~a:"block/parent" ~v:(Datascript.Ref entity) () |> Seq.iter (consume maximum_cursor_offset (fun (datom : Datascript.datom) -> - Option.iter remember (cached_uuid_of_entity database cache.hydration datom.e)))); + Option.iter (fun uuid -> + Hashtbl.replace cache.entities (Graph.Uuid.to_string uuid) (Some datom.e); + remember uuid) + (cached_uuid_of_entity database cache.hydration datom.e)))); Uuid_map.find_opt (Graph.Uuid.to_string parent) (Option.get snapshot.children_effects) |> Option.value ~default:[] |> List.iter (fun (record : outbox_record) -> @@ -4725,11 +4726,13 @@ let timeline_direct_candidates ?(charge = fun _ -> ()) ~truncate snapshot parent charge !examined; if not (complete || truncate) then None else Some (Hashtbl.to_seq_values identities |> Rrbvec.of_seq - |> Rrbvec.sort Graph.Uuid.compare |> Rrbvec.filter_map (fun uuid -> match logical_tree_candidate snapshot cache uuid with | Some candidate when Graph.Uuid.equal candidate.tree_parent parent -> Some candidate | _ -> None) - |> Rrbvec.sort (fun left right -> String.compare left.tree_order right.tree_order)) + |> Rrbvec.sort (fun left right -> + match String.compare left.tree_order right.tree_order with + | 0 -> Graph.Uuid.compare left.tree_uuid right.tree_uuid + | c -> c)) ;; let timeline_direct_members ?(preview_fallback=false) snapshot scope ~parent ~limit ~after = @@ -6615,27 +6618,59 @@ let mutation_has_logical_effect context mutation = ;; let open_owned ~sw dependencies inspection ~graph_name ownership = + let t0 = Unix.gettimeofday () in let current_generation = fresh_generation dependencies.monotonic_ns in let path = inspection.location.database_path in if not (Sys.file_exists path) then Error Types.Attachment_stale else ( - match read_outbox path, initialize_durable_receipts path with - | Error message, _ -> Error (Types.Corrupt_outbox message) - | _, Error message -> Error (Types.Corrupt_mutation_receipt message) - | Ok (encoded, durable_revision), Ok () -> - (match decode_outbox encoded with - | Error message -> Error (Types.Corrupt_outbox message) - | Ok (outbox, _) - when List.exists (fun record -> not (outbox_record_is_canonical record)) outbox - -> Error (Types.Corrupt_outbox "non-canonical overlay outbox record") - | Ok (outbox, legacy_revision) -> - let sync_revision = Option.value durable_revision ~default:legacy_revision in - let durable_outbox = durable_outbox_rows outbox in - (match migrate_outbox path ~revision:sync_revision ~expected_records:encoded durable_outbox with - | Error message -> Error (Types.Corrupt_outbox message) - | Ok () -> - (match Storage.open_database path with + let prep_result = + let sqlite = Sqlite3.db_open ~mode:`NO_CREATE path in + Fun.protect + ~finally:(fun () -> + if not (Sqlite3.db_close sqlite) + then + report_warning + "journal: phase=cleanup operation=closeSqlite scope=temporaryStorageHandle code=closePending recovery=reopen\n") + (fun () -> + let r_outbox = read_outbox_with_sqlite sqlite in + let t_outbox = Unix.gettimeofday () in + let r_receipts = + Logseq_db_storage.Mutation_receipt_store.initialize_database sqlite + in + let t_receipts = Unix.gettimeofday () in + match r_outbox, r_receipts with + | Error message, _ -> Error (Types.Corrupt_outbox message) + | _, Error message -> Error (Types.Corrupt_mutation_receipt message) + | Ok (encoded, durable_revision), Ok () -> + (match decode_outbox encoded with + | Error message -> Error (Types.Corrupt_outbox message) + | Ok (outbox, _) + when List.exists (fun record -> not (outbox_record_is_canonical record)) outbox + -> Error (Types.Corrupt_outbox "non-canonical overlay outbox record") + | Ok (outbox, legacy_revision) -> + let sync_revision = Option.value durable_revision ~default:legacy_revision in + let durable_outbox = durable_outbox_rows outbox in + let r_migrate = + match durable_revision with + | Some _ -> Ok () + | None -> + Logseq_db_storage.Sync_outbox_store.migrate_database sqlite + ~revision:sync_revision ~expected_records:encoded + (ordered_durable_rows durable_outbox) + in + let t_migrate = Unix.gettimeofday () in + (match r_migrate with + | Error message -> Error (Types.Corrupt_outbox message) + | Ok () -> + Ok (outbox, sync_revision, durable_outbox, t_outbox, t_receipts, t_migrate)))) + in + match prep_result with + | Error _ as error -> error + | Ok (outbox, sync_revision, durable_outbox, t_outbox, t_receipts, t_migrate) -> + let r_open = Storage.open_database path in + let t_storage_open = Unix.gettimeofday () in + (match r_open with | Error error -> Error (Types.Restore_failed (Storage.diagnostic_error ~operation:"attachGraph" error)) | Ok connection -> let callbacks = Storage.connection_callbacks connection in @@ -6651,7 +6686,9 @@ let open_owned ~sw dependencies inspection ~graph_name ownership = !installed_listener; ignore (Storage.close callbacks))) (fun () -> - match Storage.restore_database connection with + let r_restore = Storage.restore_database connection in + let t_restore = Unix.gettimeofday () in + match r_restore with | Error error -> Error (Types.Restore_failed (Storage.diagnostic_error ~operation:"attachGraph" error)) | Ok authoritative_database -> @@ -6680,10 +6717,24 @@ let open_owned ~sw dependencies inspection ~graph_name ownership = (Storage.datascript_storage connection)) ~callbacks in + let t_tail = Unix.gettimeofday () in let release_slot = ref None in let checkpoint_metadata = Storage.sync_metadata connection |> Result.get_ok in + let t_meta = Unix.gettimeofday () in + (try + Printf.eprintf + "journal-startup: {\"stage\":\"overlay.open_owned\",\"outbox_ms\":%.2f,\"receipts_ms\":%.2f,\"migrate_ms\":%.2f,\"storage_open_ms\":%.2f,\"storage_restore_ms\":%.2f,\"tail_session_ms\":%.2f,\"sync_meta_ms\":%.2f,\"total_ms\":%.2f}\n%!" + ((t_outbox -. t0) *. 1000.) + ((t_receipts -. t_outbox) *. 1000.) + ((t_migrate -. t_receipts) *. 1000.) + ((t_storage_open -. t_migrate) *. 1000.) + ((t_restore -. t_storage_open) *. 1000.) + ((t_tail -. t_restore) *. 1000.) + ((t_meta -. t_tail) *. 1000.) + ((t_meta -. t0) *. 1000.) + with Sys_error _ -> ()); let checkpoint = match inspection.presence with | Types.Available { checkpoint; _ } -> checkpoint @@ -6798,7 +6849,7 @@ let open_owned ~sw dependencies inspection ~graph_name ownership = `Stop_daemon); transferred := true; installed_listener := None; - Ok database))))) + Ok database))) ;; let open_ ~sw dependencies inspection ~graph_name = diff --git a/logseq_sync/lib/effect_runner/effect_runner.ml b/logseq_sync/lib/effect_runner/effect_runner.ml index 5415390a..11dea680 100644 --- a/logseq_sync/lib/effect_runner/effect_runner.ml +++ b/logseq_sync/lib/effect_runner/effect_runner.ml @@ -1171,6 +1171,27 @@ let submit_request : type a. t -> a Core.effect_ticket -> a Core.runner_request |> Option.fold ~none:"none" ~some:string_of_int in unlock_log "op=%s request=%s phase=end result=%s failure_category=%s http_status=%s elapsed_ms=%.0f" id kind outcome category http_status (Float.max 0. ((Unix.gettimeofday () -. began) *. 1000.))) diagnostic_kind; + (let startup_stage = match request with + | Core.Load_catalog _ -> Some "sync.load_catalog" + | Core.Fetch_catalog _ -> Some "sync.fetch_catalog" + | Core.Load_and_unlock_graph_key _ -> Some "sync.load_and_unlock_graph_key" + | Core.Fetch_and_unlock_graph_key _ -> Some "sync.fetch_and_unlock_graph_key" + | Core.Unlock_private_key _ -> Some "sync.unlock_private_key" + | Core.Fetch_snapshot_metadata _ -> Some "sync.fetch_snapshot_metadata" + | Core.Download_snapshot _ -> Some "sync.download_snapshot" + | _ -> None + in + Option.iter (fun stage -> + let elapsed_ms = Float.max 0. ((Unix.gettimeofday () -. began) *. 1000.) in + let outcome = match result with + | None -> "cancelled" + | Some (Ok _) -> "ok" + | Some (Error _) -> "error" + in + (try + Printf.eprintf "journal-startup: {\"stage\":%S,\"outcome\":%S,\"elapsed_ms\":%.2f}\n%!" + stage outcome elapsed_ms + with Sys_error _ -> ())) startup_stage); match result with | Some result when (not t.closed) && not operation.cancelled -> t.post (Core.Runner_completed (Core.Completion (ticket, result))) diff --git a/swift/App.swift b/swift/App.swift index 38be7647..5077e93c 100644 --- a/swift/App.swift +++ b/swift/App.swift @@ -6,26 +6,55 @@ import AppKit #endif @main struct JournalApplication: App { - @State private var platform = JournalApplicationPlatform(services: JournalNativeServices.makePlatformServices()) + @State private var platform: JournalApplicationPlatform #if os(macOS) + @State private var initialSetup: Result @NSApplicationDelegateAdaptor(JournalApplicationDelegate.self) private var delegate #endif + init() { + let platform = JournalApplicationPlatform(services: JournalNativeServices.makePlatformServices()) + #if os(iOS) + platform.startupClock.begin() + #endif + _platform = State(initialValue: platform) + #if os(macOS) + let prepared: Result = Result { + let payload = try JournalNativeServices.startupPayload() + let extensions = try JournalExtensions.registry() + var setup = JournalRuntimeSetup(payload: payload, extensions: extensions) + // Overlap OCaml boot, local DB open, and initial feed loading with UIKit/AppKit window creation. + if let runtime = try? JournalRuntime( + platform: platform, + startupPayload: payload, + extensionRegistry: extensions) { + if (try? runtime.start()) != nil { + setup.prestartedRuntime = runtime + } else { + runtime.stop() + } + } + return setup + } + _initialSetup = State(initialValue: prepared) + #endif + } + var body: some Scene { #if os(macOS) Window("Logseq Journal", id: "journal") { JournalHost(platform: platform, prepare: { JournalRuntimeSetup(payload: try JournalNativeServices.startupPayload(), extensions: try JournalExtensions.registry()) - }, authentication: JournalCognitoNative.shared) + }, authentication: JournalCognitoNative.shared, initialSetup: initialSetup) .frame(minWidth: 320, minHeight: 360) .onAppear { delegate.platform = platform } } .defaultSize(width: 840, height: 720) #else WindowGroup("Logseq Journal") { JournalHost(platform: platform, prepare: { - JournalRuntimeSetup(payload: try JournalNativeServices.startupPayload(), - extensions: try JournalExtensions.registry()) + let payload = try await Task.detached { try JournalNativeServices.startupPayload() }.value + return JournalRuntimeSetup(payload: payload, extensions: try JournalExtensions.registry()) }, authentication: JournalCognitoNative.shared) } #endif } diff --git a/swift/JournalApplicationPlatform.swift b/swift/JournalApplicationPlatform.swift index af983437..f622ed2f 100644 --- a/swift/JournalApplicationPlatform.swift +++ b/swift/JournalApplicationPlatform.swift @@ -48,8 +48,64 @@ import AppKit } } +@Observable @MainActor final class JournalStartupClock { + enum Phase { case waitingBeforeDeadline, slow, pickerRequested, finished } + + #if os(iOS) + private(set) var layout = JournalGraphInitialPresentation() + + func invalidateLayout() { + guard phase != .finished else { return } + layout = JournalGraphInitialPresentation() + } + + func ready(page: String, nonce: UUID) { + guard phase != .pickerRequested, phase != .finished else { return } + layout.ready(page: page, nonce: nonce) + } + #endif + + func requestPicker() { + guard phase == .slow else { return } + phase = .pickerRequested + } + + private var managerPickerSent = false + + func deliverManagerPicker(_ send: () -> Bool) { + guard phase == .pickerRequested, !managerPickerSent else { return } + managerPickerSent = true + if !send() { managerPickerSent = false } + } + + func deliverPicker(_ open: () -> Void) { + guard phase == .pickerRequested else { return } + open() + } + private(set) var phase = Phase.waitingBeforeDeadline + @ObservationIgnored private var task: Task? + + func begin(after delay: Duration = .seconds(5)) { + guard phase == .waitingBeforeDeadline, task == nil else { return } + let deadline = ContinuousClock.now.advanced(by: delay) + task = Task { [weak self] in + do { try await ContinuousClock().sleep(until: deadline) } catch { return } + guard let self, phase == .waitingBeforeDeadline else { return } + phase = .slow + } + } + + func finish() { + guard phase != .finished else { return } + task?.cancel() + task = nil + phase = .finished + } +} + /// Connects native services to one OCaml runtime without owning graph state. @Observable @MainActor final class JournalApplicationPlatform { + let startupClock = JournalStartupClock() private(set) var authenticationRequired = false private(set) var localAccountAvailable: Bool? private(set) var accountIssue: JournalAccountIssue? @@ -94,6 +150,10 @@ import AppKit if let authListener { NotificationCenter.default.removeObserver(authListener) } authListener = nil connection = UUID() + #if os(iOS) + if startupClock.phase == .pickerRequested { startupClock.finish() } + startupClock.invalidateLayout() + #endif refresh?.cancel() refresh = nil shutdown?.cancel() @@ -140,7 +200,14 @@ import AppKit if [.timelinePresented,.onlineRequested,.onlineCancelled].contains(request) { guard let scope=try? JournalPlatformWire.startupScope(bytes), scope>=startupScope else {return nil} if request != .onlineCancelled, !pending.acceptsOnlinePermission(scope) { return nil } - if scope != startupScope { services.cancelAuthenticationPreparation(); startupScope=scope } + if scope != startupScope { + #if os(iOS) + if startupScope != .initial, scope.accountGeneration != startupScope.accountGeneration, + startupClock.phase == .pickerRequested { startupClock.finish() } + startupClock.invalidateLayout() + #endif + services.cancelAuthenticationPreparation(); startupScope=scope + } } let requestScope = startupScope failureScope = requestScope @@ -191,7 +258,9 @@ import AppKit onlineWaiter?.resume(); onlineWaiter=nil refreshAuthentication() } - if request == .timelinePresented { refreshAuthentication() } + if request == .timelinePresented { + refreshAuthentication() + } if request == .terminationReady { shutdown?.complete() } return encoded } catch JournalPlatformServices.Failure.authenticationRequired { diff --git a/swift/JournalChrome.swift b/swift/JournalChrome.swift index 4c18cedb..00171a69 100644 --- a/swift/JournalChrome.swift +++ b/swift/JournalChrome.swift @@ -282,6 +282,7 @@ struct JournalSheetDismissButton: SwiftUI.View { let level: Int? let loading: Bool? let initial: Bool? + let canChoose: Bool? let active: Bool? let value: Double? let message: String? @@ -842,7 +843,7 @@ struct JournalSheetDismissButton: SwiftUI.View { @Environment(\.accessibilityReduceTransparency) private var reduceTransparency @StateObject private var handoff=JournalGraphHandoff() @StateObject private var coldMotion=JournalGraphColdMotion() - @State private var initialPresentation=JournalGraphInitialPresentation() + @Environment(\.journalStartupClock) private var startupClock @Environment(\.scenePhase) private var scenePhase @Environment(\.journalGraphScrollOffsets) private var graphScrollOffsets @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -1017,9 +1018,9 @@ struct JournalSheetDismissButton: SwiftUI.View { } } private var initialCover:Bool { - initialPresentation.covers(page:properties.pageID,visible:properties.visible==true, + startupClock?.phase != .finished && startupClock?.layout.covers(page:properties.pageID,visible:properties.visible==true, loading:(properties.loadingPageIDs ?? []).contains(properties.pageID ?? ""), - cold:coldMotion.ticket != nil) + cold:coldMotion.ticket != nil) == true } private func emit(_ action:String,source:String?=nil,target:String?=nil) { guard let source=source ?? properties.pageID else {return} @@ -1040,8 +1041,18 @@ struct JournalSheetDismissButton: SwiftUI.View { } } private func acknowledge() { - if properties.visible==true,coldMotion.ticket?.target != properties.pageID, - slots.contains(where:{$0.owner==properties.pageID}) {emit("presented")} + if properties.visible == true, properties.pageID != nil, scenePhase == .active, + startupClock?.phase == .pickerRequested { + startupClock?.deliverPicker { emit("choose-graph") } + return + } + if !initialCover, scenePhase == .active, properties.visible==true,coldMotion.ticket?.target != properties.pageID, + slots.contains(where:{$0.owner==properties.pageID}) { + if !(properties.loadingPageIDs ?? []).contains(properties.pageID ?? ""), !settling, !committing { + startupClock?.finish() + } + emit("presented") + } } private func handle(_ pan:UIPanGestureRecognizer,width:CGFloat) { switch pan.state { @@ -1098,7 +1109,7 @@ struct JournalSheetDismissButton: SwiftUI.View { default:break } } - var body:some SwiftUI.View { + private var graphCanvas: some SwiftUI.View { GeometryReader { bounds in ZStack(alignment:.topLeading) { ForEach(slots,id:\.owner) { slot in @@ -1113,8 +1124,8 @@ struct JournalSheetDismissButton: SwiftUI.View { shown:shown, interactive:current && properties.visible==true && !(settling && committing) && !covered && !initialCover, coldMotion:coldMotion,coldNonce:coldNonce, - initialNonce:(current && initialCover) || covered ? initialPresentation.nonce : nil, - initialReady:{page,nonce in initialPresentation.ready(page:page,nonce:nonce)},loading:(properties.loadingPageIDs ?? []).contains(slot.owner)) + initialNonce:(current && initialCover) || covered ? startupClock?.layout.nonce : nil, + initialReady:{page,nonce in startupClock?.ready(page:page,nonce:nonce)},loading:(properties.loadingPageIDs ?? []).contains(slot.owner)) .frame(width:bounds.size.width,height:bounds.size.height) .offset(x:current ? (ownsMotion ? translation : 0) : incoming ? translation-bounds.size.width : -bounds.size.width) .opacity(shown ? 1 : 0) @@ -1128,7 +1139,7 @@ struct JournalSheetDismissButton: SwiftUI.View { if initialCover { ZStack(alignment:.topLeading) { Color(uiColor:.systemBackground) - JournalStartupLoadingSurface(loading:false,initial:true,active:true) + initialLoadingSurface() .frame(width:bounds.size.width, height:startupContainerFrame?.height ?? bounds.size.height) .offset(y:startupContainerFrame.map { @@ -1151,10 +1162,14 @@ struct JournalSheetDismissButton: SwiftUI.View { .gesture(RightGraphPan(enabled:properties.enabled==true && !settling && coldMotion.ticket==nil && !initialCover) {handle($0,width:bounds.size.width)}) .onChange(of:bounds.size) { _,_ in reset(notify:true) } } + } + private var residentCanvas: some SwiftUI.View { + graphCanvas // Each native hosting root owns the same window-sized canvas as the // original app root; its own UIKit safe area is applied exactly once. .ignoresSafeArea(.container) .onAppear {graphScrollOffsets?.retain(properties.residentPageIDs ?? []);acknowledge()} + .onChange(of:initialCover) { _,covered in if !covered {acknowledge()} } .onChange(of:properties.slotOwners) { _,_ in acknowledge() } .onChange(of:coldMotion.ticket?.id) { _,id in if id==nil {acknowledge()} } .onChange(of:properties.residentPageIDs) { _,ids in @@ -1166,7 +1181,7 @@ struct JournalSheetDismissButton: SwiftUI.View { .onChange(of:properties.pageID) { previous,page in // Initial nil -> owner is admission. Replacing that owner interrupts // startup; a retained Favorites/Detail route need not own a List handshake. - if previous != nil {initialPresentation.cancel(page:previous)} + if previous != nil {startupClock?.invalidateLayout()} graphName.focusChanged(page) let keepName = graphName.presentation?.phase == .confirmed let keepCold=committing && coldMotion.ticket?.target==page @@ -1177,6 +1192,9 @@ struct JournalSheetDismissButton: SwiftUI.View { if keepCold {coldMotion.focused(page)} acknowledge() } + } + var body: some SwiftUI.View { + residentCanvas .onChange(of:properties.targetGraphName) { _,name in graphName.updateName(target:properties.targetPageID,name:name) } @@ -1192,10 +1210,10 @@ struct JournalSheetDismissButton: SwiftUI.View { if prepared == nil && source==properties.pageID && (dragging || settling) {reset(notify:false)} } .onChange(of:properties.visible) { _,visible in - if visible != true {initialPresentation.cancel(page:properties.pageID);reset(notify:true)} else {acknowledge()} + if visible != true {startupClock?.invalidateLayout();reset(notify:true)} else {acknowledge()} } - .onChange(of:scenePhase) { _,phase in if phase != .active {initialPresentation.cancel(page:properties.pageID);reset(notify:true)} } - .onDisappear {initialPresentation.cancel(page:properties.pageID);reset(notify:false)} + .onChange(of:scenePhase) { _,phase in if phase != .active {startupClock?.invalidateLayout();reset(notify:true)} else {acknowledge()} } + .onDisappear {startupClock?.invalidateLayout();reset(notify:false)} .task(id:graphName.presentation?.id) { guard let name = graphName.presentation,name.phase == .confirmed else { return } if UIAccessibility.isVoiceOverRunning { @@ -1206,6 +1224,16 @@ struct JournalSheetDismissButton: SwiftUI.View { } } + private func initialLoadingSurface() -> JournalStartupLoadingSurface { + let choose = SwiftUI.Button("Choose other graph") { + startupClock?.requestPicker() + startupClock?.deliverPicker { emit("choose-graph") } + } + .buttonStyle(.bordered).accessibilityIdentifier("graph-picker-choose") + return JournalStartupLoadingSurface(loading:false,initial:true,active:scenePhase == .active, + action:AnyView(choose)) + } + private func nameLabel(_ name:String,font:Font) -> some SwiftUI.View { HStack(spacing:6) { Image(systemName:"square.stack").font(.system(size:12)).accessibilityHidden(true) @@ -1577,6 +1605,9 @@ struct JournalSheetDismissButton: SwiftUI.View { struct View: SwiftUI.View { let context: LUIAppleExtensionViewContext + #if os(iOS) + @Environment(\.journalStartupClock) private var startupClock + #endif @Environment(\.journalStartupContainerFrame) private var startupContainerFrame #if !os(iOS) @Environment(\.journalFilterAccessibilityFocus) private var filterAccessibilityFocus @@ -1680,6 +1711,11 @@ struct JournalSheetDismissButton: SwiftUI.View { properties.connecting != nil, properties.controls != nil { FloatingChrome(content: child(0), cluster: child(1), progress: child(2), properties: properties, leading: child(3)) + #if os(iOS) + .onAppear { + if startupClock?.phase == .pickerRequested { startupClock?.finish() } + } + #endif } case .startup: if let properties, context.childIDs.count == 1 { @@ -1695,6 +1731,13 @@ struct JournalSheetDismissButton: SwiftUI.View { $0.minY - bounds.frame(in: .global).minY } ?? 0) } + #if os(iOS) + .onChange(of: properties.canChoose == true && properties.active == true && context.isUserInteractionEnabled && startupClock?.phase == .pickerRequested, initial: true) { _, eligible in + if eligible { startupClock?.deliverManagerPicker { + JournalExtensions.emit(context: context, payload: Data("choose-graph".utf8)) + } } + } + #endif } case .header: if let properties, context.childIDs.isEmpty, let title = properties.title { diff --git a/swift/JournalList.swift b/swift/JournalList.swift index cf970acf..618e6ae6 100644 --- a/swift/JournalList.swift +++ b/swift/JournalList.swift @@ -407,7 +407,7 @@ extension EnvironmentValues { func didLayout() { presentationLayoutRevision+=1 #if os(iOS) - reportPresentationLayout() + reportPresentationLayout(deferToNextTurn: false) #endif } var active = false @@ -444,12 +444,18 @@ extension EnvironmentValues { } request.complete(y) } - func reportPresentationLayout() { + func reportPresentationLayout(deferToNextTurn: Bool = true) { // Empty timelines also have a completed native viewport layout. Requiring // positive content height would strand their initial loading cover. guard active, presentationLayout != nil, restoredOffset == nil, !reportingLayout, let scrollView, scrollView.window != nil, scrollView.bounds.height > 0, scrollView.bounds.width > 0 else { return } + if !deferToNextTurn { + reportingLayout = true + defer { reportingLayout = false } + presentationLayout?() + return + } reportingLayout = true DispatchQueue.main.async { [weak self] in guard let self else { return } @@ -605,26 +611,33 @@ extension EnvironmentValues { resolveIfNeeded() } + private func attachScrollViewIfFound() -> Bool { + guard window != nil, let owner = self.owner, owner.scrollView?.window == nil else { + return owner?.scrollView?.window != nil + } + var ancestor = self.superview + while let candidate = ancestor, candidate !== self.window { + if let scrollView = self.findScrollView(candidate) { + owner.scrollView = scrollView + owner.applyRestoredOffset() + owner.reportPresentationLayout() + return true + } + ancestor = candidate.superview + } + return false + } + func resolveIfNeeded() { owner?.applyRestoredOffset() owner?.reportPresentationLayout() guard window != nil, owner?.scrollView?.window == nil, !resolving else { return } + if attachScrollViewIfFound() { return } resolving = true DispatchQueue.main.async { [weak self] in guard let self else { return } defer { self.resolving = false } - guard self.window != nil, let owner = self.owner, - owner.scrollView?.window == nil else { return } - var ancestor = self.superview - while let candidate = ancestor, candidate !== self.window { - if let scrollView = self.findScrollView(candidate) { - owner.scrollView = scrollView - owner.applyRestoredOffset() - owner.reportPresentationLayout() - return - } - ancestor = candidate.superview - } + _ = self.attachScrollViewIfFound() } } @@ -899,20 +912,33 @@ extension EnvironmentValues { ? EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20) : nil) .listRowSeparator(separatorVisibility(row.separator)) .accessibilityIdentifier(row.test_id ?? row.key) - .contextMenu { - ForEach(row.context_menu?.actions ?? []) { action in - Button(role: action.role == "destructive" ? .destructive : nil) { - rowEvent(action: action.key, row: row.key) - } label: { - actionLabel(action) + .modifier(RowContextMenuModifier(actions: row.context_menu?.actions ?? []) { action in + Button(role: action.role == "destructive" ? .destructive : nil) { + rowEvent(action: action.key, row: row.key) + } label: { + actionLabel(action) + } + .disabled(!actionInteractive(action)) + }) + } + + private struct RowContextMenuModifier: ViewModifier { + let actions: [Action] + @ViewBuilder let item: (Action) -> Item + func body(content: Content) -> some SwiftUI.View { + if actions.isEmpty { + content + } else { + content.contextMenu { + ForEach(actions) { action in + item(action) } - .disabled(!actionInteractive(action)) } } + } } - // Opaque `some View` can't express the recursive disclosure shape. - private func rowBody(_ row: Row) -> AnyView { + @ViewBuilder private func rowBody(_ row: Row) -> some SwiftUI.View { let lease = prepared.lease(for: row.key) let content = rowActions(row) .onAppear { @@ -926,7 +952,7 @@ extension EnvironmentValues { } } if row.isDisclosure { - return AnyView(DisclosureGroup( + AnyView(DisclosureGroup( isExpanded: Binding( get: { row.expanded == true }, set: { value in @@ -939,8 +965,9 @@ extension EnvironmentValues { } label: { content }.listRowSeparator(separatorVisibility(row.separator))) + } else { + content } - return AnyView(content) } private var style: ListStyleConfiguration { diff --git a/swift/JournalNativeServices.swift b/swift/JournalNativeServices.swift index 6ef9f19b..1ae3c653 100644 --- a/swift/JournalNativeServices.swift +++ b/swift/JournalNativeServices.swift @@ -2,7 +2,7 @@ import Foundation import OSLog @MainActor enum JournalNativeServices { - static let managedSyncOrigin = "https://api.logseq.io" + nonisolated static let managedSyncOrigin = "https://api.logseq.io" static func makePlatformServices() -> JournalPlatformServices { let storage = JournalNativeAccountStorage() @@ -15,7 +15,7 @@ import OSLog managedSyncOrigin: managedSyncOrigin) } - static func startupPayload() throws -> Data { + nonisolated static func startupPayload() throws -> Data { let manager = FileManager.default let support = try manager.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) @@ -24,7 +24,7 @@ import OSLog return try startupPayload(applicationSupportPath:canonical,managedSyncOrigin:managedSyncOrigin) } - static func startupPayload(applicationSupportPath:String,managedSyncOrigin:String) throws -> Data { + nonisolated static func startupPayload(applicationSupportPath:String,managedSyncOrigin:String) throws -> Data { do { return try JournalStartupConfiguration.encode(applicationSupportPath:applicationSupportPath, managedSyncOrigin:managedSyncOrigin) diff --git a/swift/JournalRuntime.swift b/swift/JournalRuntime.swift index a30ef69d..785d5d21 100644 --- a/swift/JournalRuntime.swift +++ b/swift/JournalRuntime.swift @@ -1,6 +1,7 @@ import Foundation import LUIAppleBackend import Observation +import OSLog /// C bridge entries exported by app/journal_lui_bridge.c (see also /// platform/native/lui_ocaml_bridge.c in the lui repository). Every entry that @@ -237,12 +238,38 @@ private let platformRequest: PlatformRequestCallback = { data, length in backend.onEvent = { [weak self] event in self?.handle(event) } } + @ObservationIgnored private var startUptime: TimeInterval = 0 + @ObservationIgnored private var startupTimelinePresented = false + @ObservationIgnored private var startupContentReady = false + @ObservationIgnored private var startupContentContinuations: [CheckedContinuation] = [] + private static let startupLogger = Logger(subsystem: "com.logseq.journal", category: "startup") + + private static func platformRequestKind(_ bytes: Data) -> String { + guard let decoded = try? JournalPlatformWire.decodeRequest(bytes) else { return "unknown" } + switch decoded { + case .authenticatedUser: return "authenticatedUser" + case .signOut: return "signOut" + case .terminationReady: return "terminationReady" + case .localAccount: return "localAccount" + case .timelinePresented: return "timelinePresented" + case .onlineRequested: return "onlineRequested" + case .onlineCancelled: return "onlineCancelled" + case .idToken: return "idToken" + case .copyText: return "copyText" + } + } + /// Boots the OCaml runtime; the LDB1 startup payload rides inside /// `lui_ocaml_start` so init receives it before the worker session begins. /// The platform event stream attaches afterwards. func start() throws { if let reportedFailure { throw reportedFailure } guard !started else { return } + let t0 = ProcessInfo.processInfo.systemUptime + startUptime = t0 + startupTimelinePresented = false + startupContentReady = false + resumeStartupContentWaiters() generation = UUID() let identity = generation platformRequestIngress.begin(identity) @@ -284,6 +311,8 @@ private let platformRequest: PlatformRequestCallback = { data, length in record(.start,.missingRoot) throw reportedFailure! } + let tOcaml = ProcessInfo.processInfo.systemUptime + Self.startupLogger.info("journal-startup stage=runtime.ocaml_start.done elapsed_ms=\(Int(((tOcaml - t0) * 1000).rounded()), privacy: .public) initial_patches=\(self.appliedPatches, privacy: .public)") started = true platform.connect(to: self) let requests = platformRequestIngress.activate(identity) { [weak self] request in @@ -298,6 +327,8 @@ private let platformRequest: PlatformRequestCallback = { data, length in await self.deliverPlatformRequest(request.bytes,receipt:request) } } + let tActivate = ProcessInfo.processInfo.systemUptime + Self.startupLogger.info("journal-startup stage=runtime.platform_ingress.activated elapsed_ms=\(Int(((tActivate - tOcaml) * 1000).rounded()), privacy: .public) initial_requests=\(requests.count, privacy: .public)") } /// Waits for requests emitted during admission, after native start/connect. @@ -317,10 +348,48 @@ private let platformRequest: PlatformRequestCallback = { data, length in } } + /// Waits briefly for the initial timeline tree to land in the backend before + /// mounting `LUISwiftUIRoot` so SwiftUI does not starve `@MainActor` worker + /// pumps while laying out an intermediate loading surface. + func waitForStartupContent(timeoutMilliseconds: Int = 200) async throws { + if startupContentReady { return } + let identity = generation + let timeoutTask = Task { @MainActor [weak self] in + do { try await Task.sleep(for: .milliseconds(timeoutMilliseconds)) } + catch { return } + guard let self, self.generation == identity else { return } + self.resumeStartupContentWaiters() + } + defer { timeoutTask.cancel() } + try await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + if startupContentReady || !started || generation != identity { + continuation.resume() + } else { + startupContentContinuations.append(continuation) + } + } + try Task.checkCancellation() + guard started, generation == identity else { throw CancellationError() } + } onCancel: { + Task { @MainActor [weak self] in + guard let self, self.generation == identity else { return } + self.resumeStartupContentWaiters() + } + } + } + + private func resumeStartupContentWaiters() { + let waiters = startupContentContinuations + startupContentContinuations = [] + for waiter in waiters { waiter.resume() } + } + @discardableResult func stop() -> Bool { guard started || stopPending else { return true } platformRequestIngress.close(generation) generation = UUID() + resumeStartupContentWaiters() for task in initialPlatformTasks { task.cancel() } initialPlatformTasks = [] platform.disconnect() @@ -333,11 +402,28 @@ private let platformRequest: PlatformRequestCallback = { data, length in func apply(json: String) { let identity = generation + let t0 = ProcessInfo.processInfo.systemUptime do { try backend.apply(json: json) guard generation == identity else { return } rootID = backend.rootIDs.first appliedPatches += 1 + if !startupContentReady && appliedPatches >= 2 + && (json.contains("\"journal-list\"") + || (!json.contains("\"progress\"") + && !json.contains("startup-loading") + && !json.contains("\"loading\":true") + && !json.contains("timeline-host") + && (json.contains("graph-picker-list") || json.contains("\"text-input\"")))) { + startupContentReady = true + resumeStartupContentWaiters() + } + let t1 = ProcessInfo.processInfo.systemUptime + let elapsedMs = Int(((t1 - t0) * 1000).rounded()) + if !startupTimelinePresented && (elapsedMs >= 2 || json.utf8.count >= 4096) { + let sinceStartMs = Int(((t1 - startUptime) * 1000).rounded()) + Self.startupLogger.info("journal-startup stage=runtime.apply_patch patch=\(self.appliedPatches, privacy: .public) bytes=\(json.utf8.count, privacy: .public) elapsed_ms=\(elapsedMs, privacy: .public) since_start_ms=\(sinceStartMs, privacy: .public)") + } } catch { guard generation == identity else { return } record(.patch,Self.safeReason(error)) @@ -346,7 +432,14 @@ private let platformRequest: PlatformRequestCallback = { data, length in func pump() { guard started else { return } + let t0 = ProcessInfo.processInfo.systemUptime let identity = generation, accepted = journalOCamlPump() + let t1 = ProcessInfo.processInfo.systemUptime + let elapsedMs = Int(((t1 - t0) * 1000).rounded()) + if !startupTimelinePresented && elapsedMs >= 2 { + let sinceStartMs = Int(((t1 - startUptime) * 1000).rounded()) + Self.startupLogger.info("journal-startup stage=runtime.pump elapsed_ms=\(elapsedMs, privacy: .public) since_start_ms=\(sinceStartMs, privacy: .public)") + } if generation == identity, started, accepted != 1 { recordBridge(.pump,3) } } @@ -363,7 +456,16 @@ private let platformRequest: PlatformRequestCallback = { data, length in generation == identity && (receipt.map { platformRequestIngress.owns(identity,$0) } ?? true) } guard ownsRequest() else { return } + let kind = Self.platformRequestKind(bytes) + let reqStart = ProcessInfo.processInfo.systemUptime let response = await platform.request(bytes) + let reqEnd = ProcessInfo.processInfo.systemUptime + let elapsedMs = Int(((reqEnd - reqStart) * 1000).rounded()) + if !startupTimelinePresented || elapsedMs >= 20 { + let sinceStartMs = Int(((reqEnd - startUptime) * 1000).rounded()) + Self.startupLogger.info("journal-startup stage=runtime.platform_request kind=\(kind, privacy: .public) elapsed_ms=\(elapsedMs, privacy: .public) since_start_ms=\(sinceStartMs, privacy: .public)") + } + if kind == "timelinePresented" { startupTimelinePresented = true } guard started, ownsRequest(), !Task.isCancelled else { return } // nil belongs to retired/suppressed work. Current cancellation is an LJF1 // result and still completes the original continuation without a ledger row. diff --git a/swift/JournalRuntimeHost.swift b/swift/JournalRuntimeHost.swift index 86a0eebb..fbb67feb 100644 --- a/swift/JournalRuntimeHost.swift +++ b/swift/JournalRuntimeHost.swift @@ -14,7 +14,20 @@ struct JournalRuntimeHost: View { let platform: JournalApplicationPlatform let payload: Data let extensions: LUIAppleExtensionRegistry + let prestarted: JournalRuntime? @State private var lifetime = JournalRuntimeLifetime() + + init( + platform: JournalApplicationPlatform, + payload: Data, + extensions: LUIAppleExtensionRegistry, + prestarted: JournalRuntime? = nil + ) { + self.platform = platform + self.payload = payload + self.extensions = extensions + self.prestarted = prestarted + } private var runtime: JournalRuntime? { get { lifetime.runtime } nonmutating set { lifetime.runtime = newValue } @@ -23,12 +36,17 @@ struct JournalRuntimeHost: View { get { lifetime.startingRuntime } nonmutating set { lifetime.startingRuntime = newValue } } - @State private var fallbackClock = JournalStartupClock() @State private var graphScrollOffsets = JournalGraphScrollOffsets() - @Environment(\.journalStartupClock) private var inheritedClock @State private var failure: Error? @State private var startupRevision = 0 - private var clock: JournalStartupClock { inheritedClock ?? fallbackClock } + + private var displayRuntime: JournalRuntime? { + #if os(iOS) + runtime ?? (platform.startupClock.phase != .waitingBeforeDeadline ? startingRuntime : nil) + #else + runtime + #endif + } private var content: some SwiftUI.View { Group { @@ -39,7 +57,7 @@ struct JournalRuntimeHost: View { Text(runtime?.failureDescription ?? failure.map { JournalRuntime.safeDescription($0,operation:"runtime.start.failed") } ?? "Journal could not start (runtime.start.failed).") } - } else if let runtime, let rootID = runtime.rootID { + } else if let runtime = displayRuntime, let rootID = runtime.rootID { LUISwiftUIRoot(backend: runtime.backend, rootID: rootID) } else { JournalStartupLoadingSurface(loading: false, initial: true, active: true) @@ -62,24 +80,45 @@ struct JournalRuntimeHost: View { content #endif } - .environment(\.journalStartupClock, clock) + .environment(\.journalStartupClock, platform.startupClock) .environment(\.journalGraphScrollOffsets, graphScrollOffsets) .background(JournalEnvironmentObserver { platform.pushEnvironment($0) }) .task(id: startupRevision) { if runtime == nil && startingRuntime == nil { + let startupLogger = Logger(subsystem: "com.logseq.journal", category: "startup") + let t0 = ProcessInfo.processInfo.systemUptime do { - let next = try JournalRuntime( - platform: platform, - startupPayload: payload, - extensionRegistry: extensions) + let next: JournalRuntime + let alreadyStarted: Bool + if startupRevision == 0, let prestarted, prestarted.failure == nil { + next = prestarted + alreadyStarted = true + } else { + next = try JournalRuntime( + platform: platform, + startupPayload: payload, + extensionRegistry: extensions) + alreadyStarted = false + } + let t1 = ProcessInfo.processInfo.systemUptime + startupLogger.info("journal-startup stage=host.runtime.created elapsed_ms=\(Int(((t1 - t0) * 1000).rounded()), privacy: .public) since_start_ms=\(Int(((t1 - t0) * 1000).rounded()), privacy: .public) prestarted=\(alreadyStarted, privacy: .public)") startingRuntime = next do { - try next.start() + if !alreadyStarted { + try next.start() + } + let t2 = ProcessInfo.processInfo.systemUptime + startupLogger.info("journal-startup stage=host.runtime.started elapsed_ms=\(Int(((t2 - t1) * 1000).rounded()), privacy: .public) since_start_ms=\(Int(((t2 - t0) * 1000).rounded()), privacy: .public)") try await next.waitForInitialPlatformRequests() + let t3 = ProcessInfo.processInfo.systemUptime + startupLogger.info("journal-startup stage=host.initial_platform_requests.done elapsed_ms=\(Int(((t3 - t2) * 1000).rounded()), privacy: .public) since_start_ms=\(Int(((t3 - t0) * 1000).rounded()), privacy: .public)") + try await next.waitForStartupContent() try Task.checkCancellation() guard startingRuntime === next else { throw CancellationError() } runtime = next startingRuntime = nil + let t4 = ProcessInfo.processInfo.systemUptime + startupLogger.info("journal-startup stage=host.root.mounted elapsed_ms=\(Int(((t4 - t3) * 1000).rounded()), privacy: .public) since_start_ms=\(Int(((t4 - t0) * 1000).rounded()), privacy: .public)") } catch { if next.stop() { if startingRuntime === next { @@ -106,29 +145,7 @@ struct JournalRuntimeHost: View { } } -@Observable @MainActor final class JournalStartupClock { - private(set) var expired = false - @ObservationIgnored private var started: TimeInterval? - @ObservationIgnored private var task: Task? - @ObservationIgnored private var revision = 0 - var elapsed: Bool { - expired || started.map { ProcessInfo.processInfo.systemUptime - $0 >= 0.1 } == true - } - func begin() { - guard started == nil else { return } - started = ProcessInfo.processInfo.systemUptime - let version = revision - task = Task { [weak self] in - do { try await Task.sleep(for: .milliseconds(100)) } - catch { return } - guard let self, !Task.isCancelled, version == revision else { return } - expired = true - } - } - func restart() { - revision += 1; task?.cancel(); task = nil; started = nil; expired = false - } -} + private struct JournalStartupClockKey: EnvironmentKey { static let defaultValue: JournalStartupClock? = nil @@ -146,9 +163,15 @@ struct JournalStartupLoadingSurface: View { let active: Bool var value: Double? = nil var message = "" - var action = AnyView(EmptyView()) + var action: AnyView? = nil @Environment(\.journalStartupClock) private var clock - private var visible: Bool { active && (loading || (initial && clock?.elapsed == true)) } + private var visible: Bool { + #if os(iOS) + active && (initial && clock?.phase != .finished ? clock?.phase == .slow : loading) + #else + active && (loading || (initial && clock?.phase == .slow)) + #endif + } var body: some View { VStack(spacing: 12) { Group { @@ -162,17 +185,39 @@ struct JournalStartupLoadingSurface: View { .accessibilityHidden(!visible) .frame(maxWidth: .infinity, maxHeight: .infinity) // Recovery actions do not change the centered waiting canvas. - .overlay(alignment: .bottom) { action } + .overlay(alignment: .bottom) { + #if os(iOS) + if active && initial && clock?.phase == .pickerRequested { + if let action { action } + else { Text("Opening graph picker…") } + } else if !initial || visible { + if let action { action } + else if initial, let clock { + Button("Choose other graph") { clock.requestPicker() } + .buttonStyle(.bordered).accessibilityIdentifier("graph-picker-choose") + } + } + #else + action + #endif + } .padding(24) .background(.background) .accessibilityIdentifier("journal-startup-waiting") - .onAppear { clock?.begin() } + .onAppear { + #if os(macOS) + clock?.begin(after: .milliseconds(100)) + #else + clock?.begin() + #endif + } } } struct JournalRuntimeSetup { let payload: Data let extensions: LUIAppleExtensionRegistry + var prestartedRuntime: JournalRuntime? = nil } /// Production account entry points with injectable native capabilities for QA. @@ -184,7 +229,18 @@ struct JournalHost: View { @State private var setup: Result? @State private var signInPresented = false @State private var signInStartsImmediately = false - @State private var clock = JournalStartupClock() + + init( + platform: JournalApplicationPlatform, + prepare: @escaping @MainActor () async throws -> JournalRuntimeSetup, + authentication: any JournalAuthenticationAPI, + initialSetup: Result? = nil + ) { + self.platform = platform + self.prepare = prepare + self.authentication = authentication + _setup = State(initialValue: initialSetup) + } var body: some View { Group { @@ -205,12 +261,13 @@ struct JournalHost: View { signIn: { signInStartsImmediately = true; signInPresented = true }, retry: platform.accountIssue?.stage == .bindingRead ? nil : { platform.retryOnline() }) } - JournalRuntimeHost(platform: platform, payload: setup.payload, extensions: setup.extensions) + JournalRuntimeHost(platform: platform, payload: setup.payload, + extensions: setup.extensions, prestarted: setup.prestartedRuntime) .font(.body) } } } - .environment(\.journalStartupClock, clock) + .environment(\.journalStartupClock, platform.startupClock) .task { guard setup == nil else { return } do { setup = .success(try await prepare()) } @@ -220,14 +277,14 @@ struct JournalHost: View { if phase == .background { lifecycle(backgrounded: true) } else if phase == .active { lifecycle(backgrounded: false) } } - .onChange(of: platform.authenticationRequired) { _, required in + .onChange(of: platform.authenticationRequired, initial: true) { _, required in if required && platform.localAccountAvailable == false && !signInPresented { signInStartsImmediately = false; signInPresented = true } // The authentication owner closes its sheet after account preparation. // Closing on the intermediate native identity update can cancel that work. } - .onChange(of: platform.localAccountAvailable) { _, available in + .onChange(of: platform.localAccountAvailable, initial: true) { _, available in if available == false && platform.authenticationRequired && !signInPresented { signInStartsImmediately = false; signInPresented = true } diff --git a/test/application_view_test.ml b/test/application_view_test.ml index 5eebac19..8dbf65d1 100644 --- a/test/application_view_test.ml +++ b/test/application_view_test.ml @@ -7746,7 +7746,7 @@ let test_graph_picker_controls scenario () = | Service.Get_graph_state | Get_graph_state_at _ -> let value = Atomic.get current in Ok (Service.Graph_state { generation = value.snapshot.startup.graph_generation - ; graph_id = value.snapshot.selected_graph; phase = (if scenario=`Retry_local || scenario=`Retry_graph_phase then Graph_failed else Graph_open); error = None }) + ; graph_id = value.snapshot.selected_graph; phase = (if scenario=`Manager_startup then Graph_opening else if scenario=`Retry_local || scenario=`Retry_graph_phase then Graph_failed else Graph_open); error = None }) | Client_command command -> if scenario=`Reordered_full && command=Service.Set_foreground true && Atomic.get refresh_full then while not(Atomic.get release_refresh) do Eio.Fiber.yield () done; @@ -7943,7 +7943,21 @@ let test_graph_picker_controls scenario () = ignore (hooks.dispose ()); Option.iter Logseq_db_worker_lui.Journal_worker_runtime.stop !client) (fun () -> consume (hooks.init 2 2 config); - if scenario=`Retry_local || scenario=`Retry_graph_phase then ( + if scenario = `Manager_startup then ( + let startup () = Hashtbl.to_seq props |> Seq.find_map (fun (id, fields) -> + match List.assoc_opt "payload" fields with + | Some (`String text) -> (try + let json = Yojson.Safe.from_string text in + if Yojson.Safe.Util.member "mode" json = `String "startup" then Some id else None + with _ -> None) + | _ -> None) in + wait "manager offers graph selection before graph opens" (fun () -> + Option.is_some (startup ()) && Option.is_some (find "text" "Choose another graph")); + consume (hooks.extension_event (Option.get (startup ())) "event" + {|{"id":1,"payload":"choose-graph"}|}); + wait "single startup event mounts picker" (fun () -> + Option.is_some (find "accessibility-identifier" "graph-picker-list")) + ) else if scenario=`Retry_local || scenario=`Retry_graph_phase then ( wait "failed local resident retains graph selection" (fun()->Option.is_some(find "text" "Unable to open graph")); Alcotest.(check bool) "failed local resident has no Retry" true (Option.is_none(find "accessibility-identifier" "graph-picker-retry")); @@ -7974,12 +7988,19 @@ let test_graph_picker_controls scenario () = wait "Favorites action mounts" (fun () -> Option.is_some (find "accessibility-label" "Favorites")); press (Option.get (find "accessibility-label" "Favorites")); wait "old graph Favorite read is genuinely in flight" (fun () -> Atomic.get graph_read_started)); - press (Option.get (find "text" "Switch graph")); let page=Hashtbl.to_seq props |> Seq.find_map(fun(id,fields)-> match List.assoc_opt "payload" fields with | Some (`String payload) when String.contains payload 'g' -> (try if Yojson.Safe.Util.(Yojson.Safe.from_string payload |> member "mode" |> to_string)="graph-pages" then Some id else None with _->None) | _->None) |> Option.get in + if scenario = `Current then ( + let payload = List.assoc "payload" (Hashtbl.find props page) |> Yojson.Safe.Util.to_string |> Yojson.Safe.from_string in + let source = Yojson.Safe.Util.member "pageID" payload in + let event = Yojson.Safe.to_string (`Assoc ["action",`String "choose-graph"; "source",source]) in + let values = Lui_protocol.String_map.(empty |> add "id" (Lui_protocol.IntValue 1) + |> add "payload" (Lui_protocol.StringValue event)) in + consume (hooks.dispatch (Lui_protocol.ExtensionEvent (page,"journal-chrome","event",values)))) + else press (Option.get (find "text" "Switch graph")); Alcotest.(check int) "native page retains its materialized graph while picker covers it" 1 (Hashtbl.to_seq_values page_parents |> Seq.filter((=)page) |> Seq.length); wait "graph list mounts" (fun () -> Option.is_some (find "accessibility-identifier" "graph-picker-list")); @@ -8031,7 +8052,7 @@ let test_graph_picker_controls scenario () = for _ = 1 to 10 do range (); consume (hooks.pump ()) done; Alcotest.(check int) "same viewport reuses presence observations" 2 (Atomic.get inspections); Alcotest.(check int) "presence does not reconstruct the graph catalog" before !root_renders - | `Retry_local | `Retry_graph_phase -> () + | `Manager_startup | `Retry_local | `Retry_graph_phase -> () | `Automatic_auth | `Automatic_direct | `Automatic_stop -> let native user_id= let startup=(Atomic.get current).snapshot.startup in @@ -8686,6 +8707,7 @@ let () = ; ( "graph picker", [ Alcotest.test_case "presence updates preserve native node lifecycle" `Quick test_picker_presence_native_patch_lifecycle; Alcotest.test_case "failed resident local retry restarts open" `Quick (test_graph_picker_controls `Retry_local); + Alcotest.test_case "manager startup event opens picker before graph" `Quick (test_graph_picker_controls `Manager_startup); Alcotest.test_case "failed worker local retry restarts retained mirror" `Quick (test_graph_picker_controls `Retry_graph_phase); Alcotest.test_case "offline deletion is disabled with explanation" `Quick (test_graph_picker_controls `Offline); Alcotest.test_case "refresh failure replaces old presence failure" `Quick (test_graph_picker_controls `Refresh_after_presence_failure); diff --git a/test/journal_graph_runtime_locality_test.ml b/test/journal_graph_runtime_locality_test.ml index 97df8a38..bbcc8dd4 100644 --- a/test/journal_graph_runtime_locality_test.ml +++ b/test/journal_graph_runtime_locality_test.ml @@ -8427,16 +8427,23 @@ let test_prefix_preserves_reconciliation ~resync stage () = let held = match stage with | `Root | `Preview -> held | `Continuation -> - let rec finish_previews (output : Runtime.output) = - let request = only "one retained refresh continuation" output.requests in - match Runtime.worker_read runtime request with - | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Roots _;_};_}) -> output - | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Preview_children {parent;_};_};_}) -> - finish_previews (deliver_sample runtime (sample request - ((children_sample ~parent:(parent) ~scope_revision:("children-1") ~items:([]) ~next:(None))))) - | _ -> Alcotest.fail "unexpected reconciliation request" + let rec finish_previews (pending : Graph.Uuid.t list) = + match pending with + | [] -> Alcotest.fail "expected retained refresh continuation" + | request :: rest -> + (match Runtime.worker_read runtime request with + | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Roots _;_};_}) -> + { Runtime.requests = request :: rest; responses = [] } + | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Preview_children {parent;_};_};_}) -> + let next = deliver_sample runtime (sample request + ((children_sample ~parent:(parent) ~scope_revision:("children-1") ~items:([]) ~next:(None)))) in + finish_previews (rest @ next.requests) + | Some(Runtime.Read{query=W.Timeline_check _;_}) -> + let next = deliver_sample runtime (sample request check_sample) in + finish_previews (rest @ next.requests) + | _ -> Alcotest.fail "unexpected reconciliation request") in - finish_previews held + finish_previews held.requests in let prefix, _ = drive_roots runtime [fresh] { Runtime.requests = [dates]; responses = [] } in diff --git a/test/startup_test.ml b/test/startup_test.ml index 357d02ad..0f7b8113 100644 --- a/test/startup_test.ml +++ b/test/startup_test.ml @@ -331,6 +331,7 @@ let test_stable_startup_presentation () = require (P.loading_request inactive=None && P.step inactive (Elapsed(old,1.))==inactive) "background keeps an active loading timer"; let resumed=P.step inactive (Foreground true) in + require (P.initial_attempt resumed && not (P.initial_attempt (P.step resumed Retry))) "resume is not a business retry"; require (timer resumed<>old && not(P.loading_indicator resumed)) "resume reuses old grace"; require (P.step resumed (Elapsed(old,3600.))==resumed) "late background timer changes resume"; let key=timer resumed in