From 34a2ba5fe32596cb09752efbaeedd022a1cf18a5 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 20:13:49 +0800 Subject: [PATCH 01/14] Add graph-local named Timeline filters --- .../journal-build/scripts/journal_build.py | 3 +- app/application.ml | 357 ++++++------------ app/dune | 4 + app/impl/timeline_filter/dune | 5 + app/impl/timeline_filter/timeline_filter.ml | 173 +++++++++ app/journal_bridge.ml | 2 + app/journal_bridge.mli | 2 + app/journal_filter_date.ml | 35 ++ app/journal_lui_bridge.c | 12 + app/spec/filter/dune | 5 + app/spec/filter/timeline_filter.mli | 161 +++++++- app/timeline_filter_preferences.ml | 75 ++++ swift/JournalChrome.swift | 103 ++++- swift/JournalRuntime.swift | 18 +- swift/JournalTimelineFilterPreferences.swift | 12 +- test/dune | 10 + test/test_timeline_filter_contract.sh | 13 +- test/test_timeline_filter_preferences.sh | 9 +- test/timeline_filter_contract_test.ml | 29 +- .../timeline_filter_preferences_codec_test.ml | 49 +-- test/timeline_filter_preferences_test.swift | 21 +- 21 files changed, 740 insertions(+), 358 deletions(-) create mode 100644 app/impl/timeline_filter/dune create mode 100644 app/impl/timeline_filter/timeline_filter.ml create mode 100644 app/journal_filter_date.ml create mode 100644 app/spec/filter/dune create mode 100644 app/timeline_filter_preferences.ml diff --git a/.agents/skills/journal-build/scripts/journal_build.py b/.agents/skills/journal-build/scripts/journal_build.py index 245fd47f..7e775c9e 100644 --- a/.agents/skills/journal-build/scripts/journal_build.py +++ b/.agents/skills/journal-build/scripts/journal_build.py @@ -1261,7 +1261,8 @@ def interrupted(signum, frame): void journal_ocaml_platform_response(const char *d, int32_t l) { (void)d; (void)l; } void journal_ocaml_platform_failure(const char *d, int32_t l) { (void)d; (void)l; } void journal_ocaml_set_wakeup_callback(wakeup_cb cb) { (void)cb; } -void journal_ocaml_set_platform_request_callback(platform_request_cb cb) { (void)cb; }""" +void journal_ocaml_set_platform_request_callback(platform_request_cb cb) { (void)cb; } +void journal_ocaml_set_filter_commit_callback(int32_t (*cb)(const char *, int32_t)) { (void)cb; }""" if __name__ == "__main__": diff --git a/app/application.ml b/app/application.ml index 389f5199..27cff68a 100644 --- a/app/application.ml +++ b/app/application.ml @@ -173,151 +173,9 @@ type feed_refresh = ; graph_generation : Graph_service.graph_id option } -module Timeline_filter = struct - module Uuid = Logseq_db_types.Graph_types.Uuid - - type tag_id = Uuid.t - type status_id = Uuid.t - type unit_ = Days | Weeks - type preset = Past_14_days | Past_3_months - type relative_time = [ `Any_time | `Preset of preset | `Custom of int * unit_ ] - type time_error = Invalid_count - - let any_time = `Any_time - let preset value = `Preset value - - let custom ~count ~unit_ = - let multiplier = match unit_ with Days -> 1 | Weeks -> 7 in - if count <= 0 || count > max_int / multiplier - then Error Invalid_count - else Ok (`Custom (count, unit_)) - ;; - - let time_choice time = time - - type criteria = { tags : tag_id list; statuses : status_id list; time : relative_time } - - let criteria ~tags ~statuses ~time = - { tags = List.sort_uniq Uuid.compare tags; statuses = List.sort_uniq Uuid.compare statuses; time } - ;; - - let all = criteria ~tags:[] ~statuses:[] ~time:any_time - let tags criteria = criteria.tags - let statuses criteria = criteria.statuses - let time criteria = criteria.time - - let active_count criteria = - Bool.to_int (criteria.tags <> []) - + Bool.to_int (criteria.statuses <> []) - + Bool.to_int (criteria.time <> any_time) - ;; - - type time_control = Any_time | Preset of preset | Custom of { count_text : string; unit_ : unit_ } - type sheet = { draft_tags : tag_id list; draft_statuses : status_id list; draft_time : time_control } - type t = { applied : criteria; sheet : sheet option } - - let restore applied = { applied; sheet = None } - let initial = restore all - let applied state = state.applied - let sheet state = state.sheet - let draft_tags sheet = sheet.draft_tags - let draft_statuses sheet = sheet.draft_statuses - let draft_time sheet = sheet.draft_time - - let validate_draft_time sheet = - match sheet.draft_time with - | Any_time -> Ok any_time - | Preset value -> Ok (preset value) - | Custom { count_text; unit_ } -> - if not (String.for_all (function '0' .. '9' -> true | _ -> false) count_text) - then Error Invalid_count - else ( - match int_of_string_opt count_text with - | None -> Error Invalid_count - | Some count -> custom ~count ~unit_) - ;; - - let draft criteria = - let draft_time = - match time_choice criteria.time with - | `Any_time -> Any_time - | `Preset value -> Preset value - | `Custom (count, unit_) -> Custom { count_text = string_of_int count; unit_ } - in - { draft_tags = criteria.tags; draft_statuses = criteria.statuses; draft_time } - ;; - - let open_sheet state = - match state.sheet with Some _ -> state | None -> { state with sheet = Some (draft state.applied) } - ;; - - type edit = Toggle_tag of tag_id | Toggle_status of status_id | Set_time of time_control | Reset - - let toggle id ids = - if List.exists (Uuid.equal id) ids - then List.filter (fun candidate -> not (Uuid.equal id candidate)) ids - else id :: ids - ;; - - let resolve_days criteria ~today = - let calendar_months () = - let month_index = (today / 10000) * 12 + today / 100 mod 100 - 1 - 3 in - if month_index < 12 then invalid_arg "Filter range starts before year 1"; - let year = month_index / 12 and month = month_index mod 12 + 1 in - let last_day = match month with - | 2 -> if year mod 4 = 0 && (year mod 100 <> 0 || year mod 400 = 0) then 29 else 28 - | 4 | 6 | 9 | 11 -> 30 - | _ -> 31 in - Some (year * 10000 + month * 100 + min (today mod 100) last_day, today) - in - let days count = - let civil day = - let year = day / 10000 and month = day / 100 mod 100 in - let year = if month <= 2 then year - 1 else year in - let era = year / 400 in - let year_of_era = year mod 400 in - let month = if month <= 2 then month + 9 else month - 3 in - era * 146097 + year_of_era * 365 + year_of_era / 4 - year_of_era / 100 - + (153 * month + 2) / 5 + day mod 100 - 1 - 719468 - in - let earliest = civil today - (count - 1) in - if earliest < civil 10101 then invalid_arg "Filter range starts before year 1"; - let start = Unix.gmtime (float_of_int earliest *. 86400.) in - Some ((start.tm_year + 1900) * 10000 + (start.tm_mon + 1) * 100 + start.tm_mday, today) - in - match time_choice (time criteria) with - | `Any_time -> None - | `Preset Past_3_months -> calendar_months () - | `Preset Past_14_days -> days 14 - | `Custom (count, Days) -> days count - | `Custom (count, Weeks) -> days (7 * count) - ;; - - let edit state change = - match state.sheet with - | None -> state - | Some sheet -> - let sheet = - match change with - | Toggle_tag id -> { sheet with draft_tags = toggle id sheet.draft_tags } - | Toggle_status id -> { sheet with draft_statuses = toggle id sheet.draft_statuses } - | Set_time draft_time -> { sheet with draft_time } - | Reset -> draft all - in - { state with sheet = Some sheet } - ;; +module Timeline_filter = Journal_timeline_filter.Timeline_filter - let cancel state = { state with sheet = None } - - let apply state = - match state.sheet with - | None -> Ok state - | Some sheet -> - Result.map - (fun time -> restore (criteria ~tags:sheet.draft_tags ~statuses:sheet.draft_statuses ~time)) - (validate_draft_time sheet) - ;; -end +let initial_filters = Timeline_filter.restore Timeline_filter.empty_preferences type modal = | No_modal @@ -412,61 +270,6 @@ module Task_catalog = struct ;; end -module Timeline_filter_preferences = struct - let startup_prefix = "JTF1" - - let unwrap_startup payload = - if not (String.starts_with ~prefix:startup_prefix payload) then [], payload else - match String.index_from_opt payload (String.length startup_prefix) '\n' with - | None -> [], payload - | Some separator -> - let offset = String.length startup_prefix in - let snapshot = String.sub payload offset (separator - offset) in - let config = String.sub payload (separator + 1) (String.length payload - separator - 1) in - let entries = - try match Yojson.Safe.from_string snapshot with `Assoc entries -> entries | _ -> [] - with Yojson.Json_error _ -> [] in - entries, config - ;; - - let decode text = - let open Timeline_filter in - let open Yojson.Safe.Util in - let ids = function - | `List values -> List.map (fun value -> - match Uuid.of_string (to_string value) with - | Ok id -> id | Error _ -> raise Exit) values - | _ -> raise Exit in - try - let value = Yojson.Safe.from_string text in - if member "version" value <> `Int 1 then raise Exit; - let time = match member "time" value with - | `String "any" -> any_time - | `String "past-7-days" -> - (match custom ~count:7 ~unit_:Days with Ok time -> time | Error _ -> raise Exit) - | `String "past-2-weeks" -> preset Past_14_days - | `String "past-3-months" -> preset Past_3_months - | `List [`Int count; `String unit_] -> - let unit_ = match unit_ with "days" -> Days | "weeks" -> Weeks | _ -> raise Exit in - (match custom ~count ~unit_ with Ok time -> time | Error _ -> raise Exit) - | _ -> raise Exit in - Some (criteria ~tags:(ids (member "tags" value)) ~statuses:(ids (member "statuses" value)) ~time) - with Yojson.Json_error _ | Type_error _ | Exit -> None - ;; - - let encode value = - let open Timeline_filter in - let ids values = `List (List.map (fun id -> `String (Uuid.to_string id)) values) in - let time = match time value with - | `Any_time -> `String "any" - | `Preset Past_14_days -> `String "past-2-weeks" - | `Preset Past_3_months -> `String "past-3-months" - | `Custom (count, unit_) -> `List [`Int count; `String (match unit_ with Days -> "days" | Weeks -> "weeks")] in - Yojson.Safe.to_string (`Assoc ["version", `Int 1; "tags", ids (tags value); - "statuses", ids (statuses value); "time", time]) - ;; -end - type cleanup = Discard_staged_file of Journal_asset_import.staged type cleanup_plan = cleanup Rrbvec.t @@ -494,6 +297,7 @@ type state = ; routes : Journal_routes.t ; filter_tag_picker : filter_tag_picker ; filters : Timeline_filter.t + ; filter_error : string option ; filters_restored : bool ; timeline : Journal_timeline_state.t ; timeline_structure_revision : int @@ -651,7 +455,8 @@ let initial_state = ; favorites_requests = [] ; routes = Journal_routes.create () ; filter_tag_picker = { sheet_epoch = 0; search_epoch = 0; prefix = ""; labels = []; page = Tag_loading } - ; filters = Timeline_filter.initial + ; filters = initial_filters + ; filter_error = None ; filters_restored = false ; timeline = Journal_timeline_state.empty ~today:0 ; timeline_structure_revision = 0 @@ -876,7 +681,8 @@ let clear_graph_surface ~discard ?(discard_capture = true) state = ; favorites_requests = [] ; routes = Journal_routes.create () ; filter_tag_picker = { sheet_epoch = 0; search_epoch = 0; prefix = ""; labels = []; page = Tag_loading } - ; filters = Timeline_filter.initial + ; filters = initial_filters + ; filter_error = None ; filters_restored = false ; timeline = Journal_timeline_state.empty ~today:0 ; feed_loaded = false @@ -2075,7 +1881,8 @@ module Root_navigation = struct ; task_status_page = 0 ; reference_sources = Reference_sources.empty ; graph_state = { state.graph_state with generation } - ; filters = Timeline_filter.initial + ; filters = initial_filters + ; filter_error = None ; filters_restored = false ; graph_ready = false ; feed_loaded = false @@ -2410,7 +2217,8 @@ type command = | More_filter_tags | Retry_filter_tags | Close_filters of int - | Apply_filters of int + | Reset_filter_error of int + | Submit_filters of int * Timeline_filter.command | Open_diagnostics | Close_diagnostics | Open_error_info @@ -2836,9 +2644,10 @@ let filters_page state dispatch filter_draft = | Preset Past_14_days -> Custom { count_text = "14"; unit_ = Days } | Any_time | Preset Past_3_months -> Custom { count_text = "7"; unit_ = Days } in - let range = match apply state.filters, state.calendar with - | Ok filters, Some calendar -> - (try Some (resolve_days (applied filters) ~today:(Journal_calendar.local_day calendar)) + let range = match validate_draft_time filter_draft, state.calendar with + | Ok time, Some calendar -> + let draft = criteria ~tags:[] ~statuses:[] ~time in + (try Some (Journal_filter_date.resolve_days draft ~today:(Journal_calendar.local_day calendar)) with Invalid_argument _ -> None) | _ -> None in @@ -2891,14 +2700,18 @@ let filters_page state dispatch filter_draft = ; "sheetEpoch", `Int picker.sheet_epoch ; "choices", `Assoc [ "tags", `List selected; "statuses", `List options ; "times", `List times; "results", `List results ] + ; "filterError", Option.fold ~none:`Null ~some:(fun text -> `String text) state.filter_error ; "custom", custom; "dateRange", date_range; "text", `String picker.prefix ; "message", Option.fold ~none:`Null ~some:(fun text -> `String text) tag_message ]) in let on_event event = let raw = event.Journal_lui_native.payload in - match raw with + if event.event_id = picker.sheet_epoch then match raw with | "cancel" -> dispatch.send (Close_filters event.event_id) + | "name" -> dispatch.send (Reset_filter_error event.event_id) | "reset" -> dispatch.send (Edit_filters Reset) - | "apply" when enabled -> dispatch.send (Apply_filters event.event_id) + | "apply" when enabled -> dispatch.send (Submit_filters (event.event_id, Apply)) + | _ when enabled && String.starts_with ~prefix:"save:" raw -> + dispatch.send (Submit_filters (event.event_id, Save_as (String.sub raw 5 (String.length raw - 5)))) | _ when String.starts_with ~prefix:"search:" raw -> dispatch.send (Edit_filter_tag_text (String.sub raw 7 (String.length raw - 7))) | _ when String.starts_with ~prefix:"count:" raw -> @@ -2953,6 +2766,7 @@ let timeline_page ~on_error_info ~account_menu_available ~filter_count + ~filter_entry ~cache_reset_available ~on_account_action = @@ -3010,11 +2824,25 @@ let timeline_page in let filter_control = if favorites_selected then None else + let names, active = match filter_entry with + | Timeline_filter.Configure_directly -> [], None + | Native_menu { names; active_name } -> names, active_name in let payload = Yojson.Safe.to_string (`Assoc - [ "mode", `String "filter-trigger"; "level", `Int filter_count - ; "enabled", `Bool interaction_enabled ]) in + [ "filterNames", `List (List.map (fun name -> `String name) names) + ; "filterActiveName", Option.fold ~none:`Null ~some:(fun name -> `String name) active + ; "mode", `String "filter-trigger"; "level", `Int filter_count + ; "filterOwner", `Int graph_generation; "enabled", `Bool interaction_enabled ]) in Some (V.of_lui (Journal_lui_native.mount ~key:"journal-filters" ~payload ~children:[] - ~on_event:(fun _ -> on_account_action.send Open_filters) + ~on_event:(fun event -> + let owner = event.Journal_lui_native.event_id in + let raw = event.payload in + if owner = graph_generation then + match raw with + | "open" -> on_account_action.send Open_filters + | "clear" -> on_account_action.send (Submit_filters (owner, Clear)) + | _ when String.starts_with ~prefix:"select:" raw -> + on_account_action.send (Submit_filters (owner, Select (String.sub raw 7 (String.length raw - 7)))) + | _ -> ()) Journal_lui_native.chrome_identifier)) in let destination_action index = @@ -3649,23 +3477,33 @@ let start let filter_preferences = ref filter_preferences in let graph_filter_key id = String.lowercase_ascii (Logseq_db_types.Graph_types.Uuid.to_string id) in - let save_filters id criteria = + let save_filters id preferences = let key = graph_filter_key id in - let text = if criteria = Timeline_filter.all then "" else Timeline_filter_preferences.encode criteria in - filter_preferences := List.remove_assoc key !filter_preferences; - if text <> "" then filter_preferences := (key, `String text) :: !filter_preferences; - Journal_bridge.platform_request ("journal.timeline-filter.commit\n" ^ key ^ "\n" ^ text) in + let text = Timeline_filter_preferences.encode preferences in + if Journal_bridge.commit_timeline_filter ("journal.timeline-filter.commit\n" ^ key ^ "\n" ^ text) + then ( + filter_preferences := (key, `String text) :: List.remove_assoc key !filter_preferences; + true) + else false in let saved_filters id calendar = - let criteria = match List.assoc_opt (graph_filter_key id) !filter_preferences with - | Some (`String text) -> Timeline_filter_preferences.decode text - | _ -> None in - let criteria = Option.value criteria ~default:Timeline_filter.all in - try ignore (Timeline_filter.resolve_days criteria ~today:(Journal_calendar.local_day calendar)); criteria - with Invalid_argument _ -> Timeline_filter.all in + let open Timeline_filter in + let invalid reason = + Printf.eprintf "Invalid Timeline filter preferences for %s: %s\n%!" (graph_filter_key id) reason; + initial_filters in + match List.assoc_opt (graph_filter_key id) !filter_preferences with + | None -> initial_filters + | Some (`String text) -> + (match Timeline_filter_preferences.decode text with + | Error message -> invalid message + | Ok preferences -> + let filters = restore preferences in + (try ignore (Journal_filter_date.resolve_days (applied filters) ~today:(Journal_calendar.local_day calendar)); filters + with Invalid_argument reason -> invalid reason)) + | Some _ -> invalid "Expected a text record" in let restore_filters state = match state.filters_restored, state.graph_state.graph_id, state.calendar with | false, Some id, Some calendar -> - { state with filters_restored = true; filters = Timeline_filter.restore (saved_filters id calendar) } + { state with filters_restored = true; filters = saved_filters id calendar } | _ -> state in let pump = Journal_pump.create () in Journal_pump.set_wakeup pump Journal_bridge.wakeup; @@ -5381,8 +5219,8 @@ let start | None -> Journal_graph_runtime.{ requests = []; responses = [] } | Some calendar -> let criteria = Option.fold ~none:Timeline_filter.all - ~some:(fun id -> saved_filters id calendar) graph_state.graph_id in - let days = Timeline_filter.resolve_days criteria ~today:(Journal_calendar.local_day calendar) in + ~some:(fun id -> Timeline_filter.applied (saved_filters id calendar)) graph_state.graph_id in + let days = Journal_filter_date.resolve_days criteria ~today:(Journal_calendar.local_day calendar) in Journal_graph_runtime.set_timeline_filter (!graph_runtime_cell) ~tags:(Timeline_filter.tags criteria) ~statuses:(Timeline_filter.statuses criteria) ~days; submit @@ -6284,7 +6122,7 @@ let start | Some context -> let generation = snapshot.next_request_generation in let criteria = Timeline_filter.applied snapshot.filters in - let days = Timeline_filter.resolve_days criteria ~today:context.local_day in + let days = Journal_filter_date.resolve_days criteria ~today:context.local_day in Journal_graph_runtime.set_timeline_filter (!graph_runtime_cell) ~tags:(Timeline_filter.tags criteria) ~statuses:(Timeline_filter.statuses criteria) ~days; let output = @@ -7332,12 +7170,12 @@ let start let selected = Timeline_filter.tags (Timeline_filter.applied filters) in let labels = List.filter (fun (id, _) -> List.mem id selected) state.filter_tag_picker.labels in let picker = { sheet_epoch; search_epoch = 0; prefix = ""; labels; page = Tag_loading } in - { state with modal = Filters_sheet; filter_tag_picker = picker; filters }, + { state with modal = Filters_sheet; filter_tag_picker = picker; filters; filter_error = None }, Effect.many [ search_filter_tags ~owner picker ~after:None ~debounce:false ; resolve_filter_tag_labels ~owner ~sheet_epoch selected ]) | Edit_filters edit -> update (fun state -> - if state.modal = Filters_sheet then { state with filters = Timeline_filter.edit state.filters edit } else state) + if state.modal = Filters_sheet then { state with filters = Timeline_filter.edit state.filters edit; filter_error = None } else state) | (Edit_filter_tag_text _ | More_filter_tags | Retry_filter_tags) as action -> let owner = current_owner () in set_state_and_effect (fun state -> @@ -7367,24 +7205,48 @@ let start if state.modal = Filters_sheet && state.filter_tag_picker.sheet_epoch = sheet_epoch then { state with modal = No_modal; filters = Timeline_filter.cancel state.filters } else state) - | Apply_filters sheet_epoch -> - set_state_and_effect (fun state -> - if state.modal <> Filters_sheet || state.filter_tag_picker.sheet_epoch <> sheet_epoch - then state, Effect.ignore else - match Timeline_filter.apply state.filters, state.graph_state.graph_id with - | Ok filters, Some graph_id when state.filters_restored - && Option.exists (fun calendar -> - try ignore (Timeline_filter.resolve_days (Timeline_filter.applied filters) - ~today:(Journal_calendar.local_day calendar)); true - with Invalid_argument _ -> false) state.calendar -> - let changed = Timeline_filter.applied filters <> Timeline_filter.applied state.filters in - let next = if not changed then { state with modal = No_modal; filters } else - { state with modal = No_modal; filters; feed_loaded = false; feed_refresh = None - ; timeline = Journal_timeline_state.empty ~today:(Option.fold ~none:0 ~some:Journal_calendar.local_day state.calendar) - ; timeline_structure_revision = state.timeline_structure_revision + 1 - ; presented_feed_context = None } in - next, Effect.of_thunk (fun () -> save_filters graph_id (Timeline_filter.applied filters)) - | _ -> state, Effect.ignore) + | Reset_filter_error epoch -> + update (fun state -> + if state.modal = Filters_sheet && state.filter_tag_picker.sheet_epoch = epoch + then { state with filter_error = None } else state) + | Submit_filters (epoch, command) -> + update (fun state -> + let open Timeline_filter in + let valid_owner = match command with + | Apply | Save_as _ -> state.modal = Filters_sheet && state.filter_tag_picker.sheet_epoch = epoch + | Select _ | Clear -> state.modal = No_modal && state.graph_state.generation = epoch + && Journal_routes.destination state.routes = Journals in + if not valid_owner || not state.graph_ready || not state.filters_restored then state else + let report message = + if state.modal = Filters_sheet then + { state with filter_error = Some message } + else show_sync_error state (Non_worker_sync_failure message) in + match state.graph_state.graph_id, state.calendar, submit state.filters command with + | Some graph_id, Some calendar, Ok { next = filters; replacement } -> + let today = Journal_calendar.local_day calendar in + (match Journal_filter_date.resolve_days (applied filters) ~today with + | exception Invalid_argument reason -> report reason + | _ -> + if not (Option.fold ~none:true ~some:(save_filters graph_id) replacement) + then report "Could not save Timeline filter preferences." + else + let next = { state with modal = No_modal; filters; filter_error = None } in + if applied filters = applied state.filters then next else + { next with feed_loaded = false; feed_refresh = None + ; timeline = Journal_timeline_state.empty ~today + ; timeline_structure_revision = state.timeline_structure_revision + 1 + ; presented_feed_context = None }) + | _, _, Error error -> + report (match error with + | Invalid_time Invalid_count -> "Enter a valid positive count." + | Invalid_preferences Empty_name -> "Enter a filter name." + | Invalid_preferences Duplicate_name -> "A filter with this name already exists." + | Invalid_preferences Name_too_long -> "Use a shorter, valid filter name." + | Invalid_preferences Too_many_filters -> "You can save up to five filters per graph." + | Invalid_preferences Too_many_selections -> "Select at most 100 tags and 100 statuses." + | Invalid_preferences Unknown_selection | Unknown_name -> "This saved filter is unavailable." + | No_open_sheet -> "The filter sheet is no longer open.") + | _ -> state) | Open_diagnostics -> set_state_and_effect (fun state -> let admission_refresh, directive = @@ -8169,6 +8031,7 @@ let start && left.reference_sources == right.reference_sources && left.task_catalog.definitions == right.task_catalog.definitions && Timeline_filter.applied left.filters = Timeline_filter.applied right.filters + && Timeline_filter.entry left.filters = Timeline_filter.entry right.filters && left.feed_loaded = right.feed_loaded && left.graph_error == right.graph_error && (Option.is_none left.graph_error @@ -8476,6 +8339,7 @@ let start ~on_error_info:(bind_action dispatch Open_error_info) ~account_menu_available:true ~filter_count:(Timeline_filter.active_count (Timeline_filter.applied state.filters)) + ~filter_entry:(Timeline_filter.entry state.filters) ~on_account_action:dispatch ~cache_reset_available:(local_deletion_available state) in @@ -9414,6 +9278,7 @@ module For_testing = struct ~on_error_info:handler ~account_menu_available:true ~filter_count:0 + ~filter_entry:Timeline_filter.Configure_directly ~on_account_action:(ignore_dispatch handler) ~cache_reset_available:false |> fun page -> diff --git a/app/dune b/app/dune index 6014c064..dce8a925 100644 --- a/app/dune +++ b/app/dune @@ -5,6 +5,8 @@ journal_validation journal_calendar journal_time + journal_filter_date + timeline_filter_preferences journal_model journal_environment journal_graph_projection @@ -12,6 +14,7 @@ journal_pure_copy) (libraries logseq_db_types + journal_timeline_filter mldoc ppx_deriving_yojson.runtime threads @@ -86,6 +89,7 @@ journal_worker_coordination_impl logseq_journal.timeline_cursor journal_timeline_cursor_impl + journal_timeline_filter_impl threads unix ppx_deriving_yojson.runtime diff --git a/app/impl/timeline_filter/dune b/app/impl/timeline_filter/dune new file mode 100644 index 00000000..1453a00f --- /dev/null +++ b/app/impl/timeline_filter/dune @@ -0,0 +1,5 @@ +(library + (name journal_timeline_filter_impl) + (implements journal_timeline_filter) + (modules timeline_filter) + (libraries logseq_db_types)) diff --git a/app/impl/timeline_filter/timeline_filter.ml b/app/impl/timeline_filter/timeline_filter.ml new file mode 100644 index 00000000..6ca0b8ea --- /dev/null +++ b/app/impl/timeline_filter/timeline_filter.ml @@ -0,0 +1,173 @@ +module Uuid = Logseq_db_types.Graph_types.Uuid + +type tag_id = Uuid.t +type status_id = Uuid.t +type unit_ = Days | Weeks +type preset = Past_14_days | Past_3_months +type relative_time = [ `Any_time | `Preset of preset | `Custom of int * unit_ ] +type time_error = Invalid_count + +let any_time = `Any_time +let preset value = `Preset value + +let custom ~count ~unit_ = + let multiplier = match unit_ with Days -> 1 | Weeks -> 7 in + if count <= 0 || count > max_int / multiplier + then Error Invalid_count + else Ok (`Custom (count, unit_)) +;; + +let time_choice time = time + +type criteria = { tags : tag_id list; statuses : status_id list; time : relative_time } + +let criteria ~tags ~statuses ~time = + { tags = List.sort_uniq Uuid.compare tags; statuses = List.sort_uniq Uuid.compare statuses; time } +;; + +let all = criteria ~tags:[] ~statuses:[] ~time:any_time +let tags criteria = criteria.tags +let statuses criteria = criteria.statuses +let time criteria = criteria.time + +let active_count criteria = + Bool.to_int (criteria.tags <> []) + + Bool.to_int (criteria.statuses <> []) + + Bool.to_int (criteria.time <> any_time) +;; + +type time_control = Any_time | Preset of preset | Custom of { count_text : string; unit_ : unit_ } +type sheet = { draft_tags : tag_id list; draft_statuses : status_id list; draft_time : time_control } + +type preferences = { definitions : (string * criteria) list; selected_name : string option } +type preference_error = Empty_name | Duplicate_name | Name_too_long | Too_many_filters | Too_many_selections | Unknown_selection + +let empty_preferences = { definitions = []; selected_name = None } +let definitions preferences = preferences.definitions +let selected_name preferences = preferences.selected_name + +let preferences ~definitions ~selected_name = + let rec validate seen = function + | [] -> + let definitions = List.rev seen in + if Option.exists (fun name -> not (List.mem_assoc name definitions)) selected_name + then Error Unknown_selection + else Ok { definitions; selected_name } + | (name, criteria) :: rest -> + let name = String.trim name in + if List.length seen = 5 then Error Too_many_filters + else if name = "" then Error Empty_name + else if String.length name > 128 || not (String.is_valid_utf_8 name) then Error Name_too_long + else if List.mem_assoc name seen then Error Duplicate_name + else if List.length criteria.tags > 100 || List.length criteria.statuses > 100 + then Error Too_many_selections + else validate ((name, criteria) :: seen) rest + in + validate [] definitions +;; + +type t = { applied : criteria; sheet : sheet option; preferences : preferences } + +let restore preferences = + let applied = Option.bind preferences.selected_name (fun name -> List.assoc_opt name preferences.definitions) in + { applied = Option.value applied ~default:all; sheet = None; preferences } +;; + +type entry = Configure_directly | Native_menu of { names : string list; active_name : string option } + +let entry state = + match state.preferences.definitions with + | [] -> Configure_directly + | definitions -> Native_menu { names = List.map fst definitions; active_name = state.preferences.selected_name } +;; + +let applied state = state.applied +let sheet state = state.sheet +let draft_tags sheet = sheet.draft_tags +let draft_statuses sheet = sheet.draft_statuses +let draft_time sheet = sheet.draft_time + +let validate_draft_time sheet = + match sheet.draft_time with + | Any_time -> Ok any_time + | Preset value -> Ok (preset value) + | Custom { count_text; unit_ } -> + if not (String.for_all (function '0' .. '9' -> true | _ -> false) count_text) + then Error Invalid_count + else ( + match int_of_string_opt count_text with + | None -> Error Invalid_count + | Some count -> custom ~count ~unit_) +;; + +let draft criteria = + let draft_time = + match time_choice criteria.time with + | `Any_time -> Any_time + | `Preset value -> Preset value + | `Custom (count, unit_) -> Custom { count_text = string_of_int count; unit_ } + in + { draft_tags = criteria.tags; draft_statuses = criteria.statuses; draft_time } +;; + +let open_sheet state = + match state.sheet with Some _ -> state | None -> { state with sheet = Some (draft state.applied) } +;; + +type edit = Toggle_tag of tag_id | Toggle_status of status_id | Set_time of time_control | Reset + +let toggle id ids = + if List.exists (Uuid.equal id) ids + then List.filter (fun candidate -> not (Uuid.equal id candidate)) ids + else id :: ids +;; + +let edit state change = + match state.sheet with + | None -> state + | Some sheet -> + let sheet = + match change with + | Toggle_tag id -> { sheet with draft_tags = toggle id sheet.draft_tags } + | Toggle_status id -> { sheet with draft_statuses = toggle id sheet.draft_statuses } + | Set_time draft_time -> { sheet with draft_time } + | Reset -> draft all + in + { state with sheet = Some sheet } +;; + +let cancel state = { state with sheet = None } + +type command = Apply | Save_as of string | Select of string | Clear +type error = Invalid_time of time_error | Invalid_preferences of preference_error | No_open_sheet | Unknown_name +type transition = { next : t; replacement : preferences option } + +let submit state command = + let previous = state.preferences in + let finish applied sheet preferences = + Ok { next = { applied; sheet; preferences } + ; replacement = (if preferences = previous then None else Some preferences) } + in + match command with + | Clear -> finish all state.sheet { previous with selected_name = None } + | Select name -> + (match List.assoc_opt name previous.definitions with + | None -> Error Unknown_name + | Some applied -> finish applied state.sheet { previous with selected_name = Some name }) + | Apply | Save_as _ -> + match state.sheet with + | None -> Error No_open_sheet + | Some sheet -> + match validate_draft_time sheet with + | Error error -> Error (Invalid_time error) + | Ok time -> + let applied = criteria ~tags:sheet.draft_tags ~statuses:sheet.draft_statuses ~time in + match command with + | Apply -> finish applied None { previous with selected_name = None } + | Save_as name -> + let selected_name = Some (String.trim name) in + (match preferences ~definitions:(previous.definitions @ [name, applied]) ~selected_name with + | Ok preferences -> finish applied None preferences + | Error error -> Error (Invalid_preferences error)) + | Clear | Select _ -> assert false +;; diff --git a/app/journal_bridge.ml b/app/journal_bridge.ml index 95eba473..ed9e8307 100644 --- a/app/journal_bridge.ml +++ b/app/journal_bridge.ml @@ -11,6 +11,8 @@ type hooks = } external wakeup : unit -> unit = "journal_ml_wakeup" +external commit_timeline_filter : string -> bool = "journal_ml_commit_timeline_filter" + external platform_request : string -> unit = "journal_ml_platform_request" let current : hooks option ref = ref None diff --git a/app/journal_bridge.mli b/app/journal_bridge.mli index aec0ee3f..b0ae6a4e 100644 --- a/app/journal_bridge.mli +++ b/app/journal_bridge.mli @@ -48,6 +48,8 @@ val picked : int -> string -> string the app thread. *) external wakeup : unit -> unit = "journal_ml_wakeup" +external commit_timeline_filter : string -> bool = "journal_ml_commit_timeline_filter" + (* Forwards one LJP2 request envelope to the host platform bridge (the host answers asynchronously through [platform_response]). *) external platform_request : string -> unit = "journal_ml_platform_request" diff --git a/app/journal_filter_date.ml b/app/journal_filter_date.ml new file mode 100644 index 00000000..f01df1a9 --- /dev/null +++ b/app/journal_filter_date.ml @@ -0,0 +1,35 @@ +open Journal_timeline_filter.Timeline_filter + +let resolve_days criteria ~today = + let calendar_months () = + let month_index = (today / 10000) * 12 + today / 100 mod 100 - 1 - 3 in + if month_index < 12 then invalid_arg "Filter range starts before year 1"; + let year = month_index / 12 and month = month_index mod 12 + 1 in + let last_day = match month with + | 2 -> if year mod 4 = 0 && (year mod 100 <> 0 || year mod 400 = 0) then 29 else 28 + | 4 | 6 | 9 | 11 -> 30 + | _ -> 31 in + Some (year * 10000 + month * 100 + min (today mod 100) last_day, today) + in + let days count = + let civil day = + let year = day / 10000 and month = day / 100 mod 100 in + let year = if month <= 2 then year - 1 else year in + let era = year / 400 in + let year_of_era = year mod 400 in + let month = if month <= 2 then month + 9 else month - 3 in + era * 146097 + year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + + (153 * month + 2) / 5 + day mod 100 - 1 - 719468 + in + let earliest = civil today - (count - 1) in + if earliest < civil 10101 then invalid_arg "Filter range starts before year 1"; + let start = Unix.gmtime (float_of_int earliest *. 86400.) in + Some ((start.tm_year + 1900) * 10000 + (start.tm_mon + 1) * 100 + start.tm_mday, today) + in + match time_choice (time criteria) with + | `Any_time -> None + | `Preset Past_3_months -> calendar_months () + | `Preset Past_14_days -> days 14 + | `Custom (count, Days) -> days count + | `Custom (count, Weeks) -> days (7 * count) +;; diff --git a/app/journal_lui_bridge.c b/app/journal_lui_bridge.c index d111e881..dd311024 100644 --- a/app/journal_lui_bridge.c +++ b/app/journal_lui_bridge.c @@ -495,6 +495,18 @@ CAMLprim value journal_ml_wakeup(value unit) { return Val_unit; } +typedef int32_t (*journal_filter_commit_callback)(const char *, int32_t); +static journal_filter_commit_callback filter_commit_callback = NULL; + +LUI_EXPORT void journal_ocaml_set_filter_commit_callback(journal_filter_commit_callback callback) { + filter_commit_callback = callback; +} + +CAMLprim value journal_ml_commit_timeline_filter(value payload) { + return Val_bool(filter_commit_callback != NULL && filter_commit_callback( + (const char *)Bytes_val(payload), (int32_t)caml_string_length(payload))); +} + CAMLprim value journal_ml_platform_request(value payload) { if (platform_request_callback != NULL) { platform_request_callback( diff --git a/app/spec/filter/dune b/app/spec/filter/dune new file mode 100644 index 00000000..5c89ff8b --- /dev/null +++ b/app/spec/filter/dune @@ -0,0 +1,5 @@ +(library + (name journal_timeline_filter) + (modules timeline_filter) + (virtual_modules timeline_filter) + (libraries logseq_db_types)) diff --git a/app/spec/filter/timeline_filter.mli b/app/spec/filter/timeline_filter.mli index 0105d066..8f384739 100644 --- a/app/spec/filter/timeline_filter.mli +++ b/app/spec/filter/timeline_filter.mli @@ -1,5 +1,35 @@ -(** A1 Timeline filters: one toolbar entry and a transactional bottom sheet. - Settings only. Timeline owns query construction, matching, and paging. *) +(** Named Timeline filters and the transactional configuration sheet. + + {1 TLDR} + + The App owns one [t] per active graph. [entry] chooses direct configuration + or a native menu; [submit] applies a draft, saves and selects a name, + selects an existing name, or clears the current filter. The host owns + graph-local UserDefaults and installs the [next] state only after any + required preference replacement succeeds. [restore] takes the validated + graph preferences before the first Timeline feed request. Timeline still + owns date resolution, query construction, matching, and paging. + + {1 Minimal usage example} + + Given the active graph's validated [preferences], [publish] installs state + and updates the existing feed if effective criteria changed. The host's + [commit] replaces the graph record and returns a result; [report] surfaces + failures. Run the command in the graph owner's serialized turn. + {[ + let restored = restore preferences in + publish restored; + let draft = open_sheet restored in + match submit draft Apply with + | Error error -> report (`Filter error) + | Ok { next; replacement = None } -> publish next + | Ok { next; replacement = Some preferences } -> + (match commit preferences with + | Ok () -> publish next + | Error error -> report (`Storage error)) + ]} + + {1 Criteria and relative time} *) module Uuid = Logseq_db_types.Graph_types.Uuid @@ -47,25 +77,72 @@ val tags : criteria -> tag_id list val statuses : criteria -> status_id list val time : criteria -> relative_time -(** Count active groups (0..3), not selections. Only the Filters button is - shown on Timeline; no summary row and no Clear all row. An empty result - keeps Filters available and may offer an action to reopen the sheet. *) +(** Count active groups (0..3), not selections or named definitions. *) val active_count : criteria -> int -(** State for the active graph. The sheet draft is ephemeral. Only applied - criteria are saved by the App host in per-graph UserDefaults; this module - performs no persistence and nothing is written to the graph. Favorites and - Capture do not consume filter state. *) +(** {1 Graph preferences and restoration} *) + +type preferences + +type preference_error = + | Empty_name + | Duplicate_name + | Name_too_long + | Too_many_filters + | Too_many_selections + | Unknown_selection + +val empty_preferences : preferences + +(** Validate a decoded graph record. Proposed policy: trim surrounding + whitespace, reject empty names and exact case-sensitive duplicates after + trimming, and never overwrite a definition. Allow at most five saved + definitions per graph. Each name is at most 128 UTF-8 bytes after trimming; + each criteria group allows up to 100 unique IDs. A selected name must refer + to a definition in the same record. + Reject payloads exceeding 512 KiB before decoding; enforce collection + limits during decoding as well as on the validated record. Validate UUIDs, + UTF-8 and relative time. Retain definition order. *) +val preferences + : definitions:(string * criteria) list + -> selected_name:string option + -> (preferences, preference_error) result + +val definitions : preferences -> (string * criteria) list +val selected_name : preferences -> string option + +(** The host stores the definitions and optional selected name in one record + per graph in UserDefaults, never in graph data. No draft or anonymous + criteria are persisted. Missing or legacy anonymous records start empty; + do not migrate anonymous criteria into named definitions. Surface invalid + records and start unfiltered without rewriting them on read. *) type t -val initial : t - -(** Start with the active graph's loaded criteria and a closed sheet. Use - [initial] if that graph has no valid saved settings. *) -val restore : criteria -> t +(** Restore the selected named criteria, or [all], with a closed sheet. On + startup and graph switch, restore before the first feed request for that + graph. Resolve relative time against the current local day as before, not + the save date. Feed matching, existing OR semantics and paging are unchanged; + Favorites and Capture do not consume filter state. *) +val restore : preferences -> t val applied : t -> criteria +(** {1 Toolbar and draft} *) + +type entry = + | Configure_directly + | Native_menu of + { names : string list + ; active_name : string option + } + +(** With no saved definitions, the icon opens configuration directly. + Otherwise show all names in stored order in a native menu, mark the active + name (never mark one for an anonymous filter), then show Clear filter and + Configure filters, with Configure filters last. An empty feed still offers + access to Filters. *) +val entry : t -> entry + type sheet val sheet : t -> sheet option @@ -105,9 +182,57 @@ type edit = clears all draft groups, including time; Apply is still required. *) val edit : t -> edit -> t -(** Cancel or dismiss discards the sheet without touching applied criteria. *) +(** Cancel or dismiss the configuration sheet without touching applied + criteria or preferences. Save and Apply are text-only buttons in the same + row, with equal width and height and centered labels. Apply retains primary + styling; Save uses secondary styling. *) val cancel : t -> t -(** Validate the draft, then commit and close it atomically. When closed this - is a no-op. On error the caller retains its unchanged state and open sheet. *) -val apply : t -> (t, time_error) result +(** Save opens naming over the same draft; canceling naming returns to that + draft unchanged. The host owns the naming prompt and its input. Do not use + an existing name as an implicit overwrite. *) + +(** {1 Apply, save, select, and clear} *) + +type command = + | Apply + | Save_as of string + | Select of string + | Clear + +type error = + | Invalid_time of time_error + | Invalid_preferences of preference_error + | No_open_sheet + | Unknown_name + +type transition = private + { next : t + ; replacement : preferences option + } + +(** Apply and Save_as validate the open draft and close it on success. + Apply activates anonymous criteria in memory and clears any persisted + selected name, so reopening the graph starts at [all]. Save_as appends + a definition and selects it in the same replacement, then applies it. + At five saved definitions, Save_as rejects an additional definition with + [Invalid_preferences Too_many_filters]. Show the limit without discarding + the draft or changing the current selection. Apply remains available at + capacity; it does not add a definition. + Select activates an existing name and persists the selection. Clear + applies [all] and clears the selected name without deleting definitions. + Select and Clear do not modify a draft. Validation errors preserve the + draft, active criteria and preferences. Keep naming open with feedback + for a rejected name; surface draft errors in the sheet. + + [None] means the preferences did not change. For [Some], the App host + serializes read/modify/replace through one owner per graph, deriving each + command from the latest committed graph record, never a sheet-open + snapshot. Replace the whole record in one UserDefaults operation. Install + [next] and expose the change to the feed only after the host acknowledges + that it accepted and applied the replacement to UserDefaults. This is not + a guarantee of synchronous disk flush. On rejection retain the previous + state and surface the error. Do not publish + a completion to a different or reopened graph session. A selection-only + change with identical effective criteria need not reload the feed. *) +val submit : t -> command -> (transition, error) result diff --git a/app/timeline_filter_preferences.ml b/app/timeline_filter_preferences.ml new file mode 100644 index 00000000..87278743 --- /dev/null +++ b/app/timeline_filter_preferences.ml @@ -0,0 +1,75 @@ +open Journal_timeline_filter.Timeline_filter + +let startup_prefix = "JTF1" + +let unwrap_startup payload = + if not (String.starts_with ~prefix:startup_prefix payload) then [], payload else + match String.index_from_opt payload (String.length startup_prefix) '\n' with + | None -> [], payload + | Some separator -> + let offset = String.length startup_prefix in + let snapshot = String.sub payload offset (separator - offset) in + let config = String.sub payload (separator + 1) (String.length payload - separator - 1) in + let entries = + try match Yojson.Safe.from_string snapshot with `Assoc entries -> entries | _ -> [] + with Yojson.Json_error _ -> [] in + entries, config +;; + +exception Invalid_record of string + +let decode text = + let open Yojson.Safe.Util in + let invalid message = raise (Invalid_record message) in + let bounded limit = function + | `List values when List.length values <= limit -> values + | _ -> invalid "Invalid filter collection size" + in + let ids value = List.map (fun value -> + match Uuid.of_string (to_string value) with Ok id -> id | Error message -> invalid message) + (bounded 100 value) in + let criteria_of_json value = + let time = match member "time" value with + | `String "any" -> any_time + | `String "14-days" -> preset Past_14_days + | `String "3-months" -> preset Past_3_months + | `List [`Int count; `String unit_name] -> + let unit_ = match unit_name with "days" -> Days | "weeks" -> Weeks | _ -> invalid "Invalid time unit" in + (match custom ~count ~unit_ with Ok time -> time | Error Invalid_count -> invalid "Invalid time count") + | _ -> invalid "Invalid relative time" + in + criteria ~tags:(ids (member "tags" value)) ~statuses:(ids (member "statuses" value)) ~time + in + try + if String.length text > 512 * 1024 then invalid "Filter record exceeds 512 KiB"; + let value = Yojson.Safe.from_string text in + match member "version" value with + | `Int 1 -> Ok empty_preferences + | `Int 2 -> + let definitions = bounded 5 (member "definitions" value) |> List.map (fun item -> + to_string (member "name" item), criteria_of_json item) in + let selected_name = match member "selected" value with `Null -> None | value -> Some (to_string value) in + (match preferences ~definitions ~selected_name with + | Ok record -> Ok record + | Error error -> Error (match error with + | Empty_name -> "Empty filter name" | Duplicate_name -> "Duplicate filter name" + | Name_too_long -> "Invalid filter name length or encoding" | Too_many_filters -> "Too many saved filters" + | Too_many_selections -> "Too many filter selections" | Unknown_selection -> "Unknown selected filter")) + | _ -> Error "Unsupported filter record version" + with + | Yojson.Json_error message | Type_error (message, _) | Invalid_record message -> Error message +;; + +let encode record = + let ids values = `List (List.map (fun id -> `String (Uuid.to_string id)) values) in + let definition (name, value) = + let time = match time_choice (time value) with + | `Any_time -> `String "any" + | `Preset Past_14_days -> `String "14-days" + | `Preset Past_3_months -> `String "3-months" + | `Custom (count, unit_) -> `List [`Int count; `String (match unit_ with Days -> "days" | Weeks -> "weeks")] in + `Assoc ["name", `String name; "tags", ids (tags value); "statuses", ids (statuses value); "time", time] + in + let selected = Option.fold ~none:`Null ~some:(fun name -> `String name) (selected_name record) in + Yojson.Safe.to_string (`Assoc ["version", `Int 2; "definitions", `List (List.map definition (definitions record)); "selected", selected]) +;; diff --git a/swift/JournalChrome.swift b/swift/JournalChrome.swift index 7160cfe0..9754bbc1 100644 --- a/swift/JournalChrome.swift +++ b/swift/JournalChrome.swift @@ -296,6 +296,10 @@ struct JournalSheetDismissButton: SwiftUI.View { let ownerID: String? let visible: Bool? let sheetEpoch: Int? + let filterOwner: Int? + let filterNames: [String]? + let filterActiveName: String? + let filterError: String? let choices: FilterChoices? let custom: FilterCustom? let dateRange: [Int]? @@ -328,15 +332,16 @@ struct JournalSheetDismissButton: SwiftUI.View { private struct FilterTriggerButton: SwiftUI.View { let count: Int - let action: () -> Void + let names: [String] + let activeName: String? + let action: (String) -> Void @Environment(\.colorScheme) private var scheme @Environment(\.accessibilityReduceTransparency) private var reduceTransparency private var active: Bool { count > 0 } - var body: some SwiftUI.View { - Button(action: action) { - Image(systemName: "line.3.horizontal.decrease") + private var icon: some SwiftUI.View { + Image(systemName: "line.3.horizontal.decrease") .font(.system(size: 17, weight: .semibold)) .foregroundStyle(active ? filterBlue(scheme) : Color.primary) .frame(width: 44, height: 44) @@ -350,8 +355,30 @@ struct JournalSheetDismissButton: SwiftUI.View { } } .contentShape(Circle()) + } + + var body: some SwiftUI.View { + Group { + if names.isEmpty { + Button { action("open") } label: { icon }.buttonStyle(.plain) + } else { + Menu { + ForEach(names.indices, id: \.self) { index in + let name = names[index] + Button { action("select:" + name) } label: { + if activeName?.utf8.elementsEqual(name.utf8) == true { Label(name, systemImage: "checkmark") } + else { Text(name) } + } + } + Divider() + Button("Clear filter") { action("clear") } + Button("Configure filters") { action("open") } + } label: { icon } + .menuOrder(.fixed) + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + } } - .buttonStyle(.plain) #if os(iOS) .background { if reduceTransparency { Circle().fill(Color(uiColor: .secondarySystemBackground)) } @@ -412,6 +439,8 @@ struct JournalSheetDismissButton: SwiftUI.View { let accessibilityFocus: AccessibilityFocusState.Binding #endif @State private var showsTags = false + @State private var naming = false + @State private var filterName = "" @FocusState private var editing: Field? @Environment(\.colorScheme) private var scheme @Environment(\.dynamicTypeSize) private var typeSize @@ -567,6 +596,18 @@ struct JournalSheetDismissButton: SwiftUI.View { .frame(maxWidth: .infinity, alignment: .leading) } + private func footerButton(_ title: String, primary: Bool, action: @escaping () -> Void) -> some SwiftUI.View { + Button(action: action) { + Text(title).font(.headline) + .foregroundStyle(primary ? Color.white : filterBlue(scheme)) + .frame(maxWidth: .infinity, minHeight: 46) + .background(primary ? Color(red: 0.12, green: 0.31, blue: 0.63) : Color.primary.opacity(0.08), in: .capsule) + .contentShape(.capsule) + } + .buttonStyle(.plain) + .accessibilityIdentifier(primary ? "journal-filter-apply" : "journal-filter-save") + } + private var scrollableFields: some SwiftUI.View { ScrollViewReader { scroll in ScrollView { fields } @@ -632,19 +673,41 @@ struct JournalSheetDismissButton: SwiftUI.View { Text("Enter a positive whole number within the supported range.") .font(.footnote).foregroundStyle(.secondary) } - let apply = Button { send("apply") } label: { - Text("Apply filters").font(.headline) - .foregroundStyle(.white) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - .padding(.horizontal, 10) - .frame(maxWidth: .infinity, minHeight: 46) - .background(Color(red: 0.12, green: 0.31, blue: 0.63), in: .capsule) + if !naming, let error = properties.filterError { + Text(error).font(.footnote).foregroundStyle(.red) + } + let apply = HStack(spacing: 12) { + footerButton("Save", primary: false) { + editing = nil + filterName = "" + send("name") + naming = true + } + footerButton("Apply", primary: true) { send("apply") } } - .buttonStyle(.plain) .disabled(properties.enabled != true) .opacity(properties.enabled == true ? 1 : 0.45) - .accessibilityIdentifier("journal-filter-apply") + .sheet(isPresented: $naming) { + NavigationStack { + Form { + TextField("Name", text: $filterName) + .accessibilityIdentifier("journal-filter-name") + if let error = properties.filterError { + Text(error).foregroundStyle(.red) + } + } + .navigationTitle("Save filter") + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { naming = false; send("name") } + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { send("save:" + filterName) } + } + } + } + .presentationDetents([.medium]) + } #if os(iOS) if editing == .count { HStack(spacing: 12) { @@ -1439,7 +1502,7 @@ struct JournalSheetDismissButton: SwiftUI.View { guard isPresented, active?.epoch == epoch, cancelledEpoch != epoch, let requested, requested.epoch == epoch else { return } if action == "apply", requested.properties.enabled != true { return } - if JournalExtensions.emit(context: context, id: (action == "cancel" || action == "apply") ? epoch : 1, + if JournalExtensions.emit(context: context, id: epoch, payload: Data(action.utf8)), action == "cancel" { cancelledEpoch = epoch isPresented = false @@ -1531,7 +1594,7 @@ struct JournalSheetDismissButton: SwiftUI.View { .onTapGesture { JournalExtensions.emit(context: context, id: epoch, payload: Data("cancel".utf8)) } .accessibilityHidden(true) FilterPanel(properties: properties, choices: choices, send: { action in - JournalExtensions.emit(context: context, id: (action == "cancel" || action == "apply") ? epoch : 1, + JournalExtensions.emit(context: context, id: epoch, payload: Data(action.utf8)) }, accessibilityFocus: $filterFocus) .padding(.horizontal, 4) @@ -1551,8 +1614,10 @@ struct JournalSheetDismissButton: SwiftUI.View { case .filterTrigger: if let properties { let count = properties.level ?? 0 - let trigger = FilterTriggerButton(count: count) { - JournalExtensions.emit(context: context, payload: Data("open".utf8)) + let trigger = FilterTriggerButton(count: count, names: properties.filterNames ?? [], + activeName: properties.filterActiveName) { action in + guard let owner = properties.filterOwner else { return } + JournalExtensions.emit(context: context, id: owner, payload: Data(action.utf8)) } .disabled(properties.enabled != true) #if os(iOS) diff --git a/swift/JournalRuntime.swift b/swift/JournalRuntime.swift index 906e0b9f..a30ef69d 100644 --- a/swift/JournalRuntime.swift +++ b/swift/JournalRuntime.swift @@ -116,13 +116,24 @@ private final class JournalPlatformRequestIngress: @unchecked Sendable { owner = nil; receiver = nil; pending = []; latest = [:] } } +private typealias FilterCommitCallback = @convention(c) (UnsafePointer?, Int32) -> Int32 +@_silgen_name("journal_ocaml_set_filter_commit_callback") +private func journalOCamlSetFilterCommitCallback(_ callback: FilterCommitCallback?) + +private let filterCommit: FilterCommitCallback = { data, length in + guard Thread.isMainThread, let data, length > 0 else { return 0 } + let request = Data(bytes: data, count: Int(length)) + return MainActor.assumeIsolated { + guard activeRuntime != nil else { return 0 } + return JournalTimelineFilterPreferences(defaults: .standard).handleCommit(request) ? 1 : 0 + } +} + private let platformRequestIngress = JournalPlatformRequestIngress() private let platformRequest: PlatformRequestCallback = { data, length in guard let data, length > 0 else { return } let request = Data(bytes: data, count: Int(length)) - if !JournalTimelineFilterPreferences(defaults: .standard).handleCommit(request) { - platformRequestIngress.submit(request) - } + platformRequestIngress.submit(request) } /// Owns the lui backend, the OCaml runtime, and the platform bridge for one @@ -238,6 +249,7 @@ private let platformRequest: PlatformRequestCallback = { data, length in defer { if !started { platformRequestIngress.close(identity) } } journalOCamlSetWakeupCallback(wakeup) journalOCamlSetPlatformRequestCallback(platformRequest) + journalOCamlSetFilterCommitCallback(filterCommit) activeRuntime = self #if os(macOS) let operatingSystem: Int32 = 1 diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index b51435ef..3964a4af 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -27,13 +27,11 @@ struct JournalTimelineFilterPreferences { let body = request.dropFirst(Self.commitPrefix.count) guard let separator = body.firstIndex(of: 10), let id = UUID(uuidString: String(decoding: body.prefix(upTo: separator), as: UTF8.self)), - let criteria = String(data: body.suffix(from: separator + 1), encoding: .utf8) else { return true } + body.count - body.distance(from: body.startIndex, to: separator) - 1 <= 512 * 1024, + let record = String(data: body.suffix(from: separator + 1), encoding: .utf8), + !record.isEmpty else { return false } let key = Self.keyPrefix + id.uuidString.lowercased() - if criteria.isEmpty { - defaults.removeObject(forKey: key) - } else { - defaults.set(criteria, forKey: key) - } - return true + defaults.set(record, forKey: key) + return defaults.string(forKey: key) == record } } diff --git a/test/dune b/test/dune index fb4f9d6e..0430263f 100644 --- a/test/dune +++ b/test/dune @@ -1,3 +1,13 @@ +(test + (name timeline_filter_preferences_codec_test) + (modules timeline_filter_preferences_codec_test) + (libraries journal_app_business journal_timeline_filter_impl journal_worker_coordination_impl)) + +(test + (name timeline_filter_contract_test) + (modules timeline_filter_contract_test) + (libraries journal_timeline_filter_impl)) + (library (name coordination_test_fixture) (modules coordination_test_fixture) diff --git a/test/test_timeline_filter_contract.sh b/test/test_timeline_filter_contract.sh index b0405273..2556d3a4 100644 --- a/test/test_timeline_filter_contract.sh +++ b/test/test_timeline_filter_contract.sh @@ -1,15 +1,4 @@ #!/usr/bin/env bash set -euo pipefail cd "$(dirname "$0")/.." -dune build logseq_db_types/lib/logseq_db_types.cmxa @install -export OCAMLPATH="$PWD/_build/install/default/lib${OCAMLPATH:+:$OCAMLPATH}" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -compile=(ocamlfind ocamlopt -package logseq_db_types,unix -I "$work") -awk '/^module Timeline_filter = struct$/ { inside=1; next } inside && /^end$/ { exit } inside { print }' \ - app/application.ml > "$work/timeline_filter.ml" -"${compile[@]}" -c -o "$work/timeline_filter.cmi" app/spec/filter/timeline_filter.mli -"${compile[@]}" -c -o "$work/timeline_filter.cmx" "$work/timeline_filter.ml" -"${compile[@]}" -c -o "$work/test.cmx" test/timeline_filter_contract_test.ml -"${compile[@]}" -linkpkg -o "$work/test" "$work/timeline_filter.cmx" "$work/test.cmx" -"$work/test" +dune exec ./test/timeline_filter_contract_test.exe diff --git a/test/test_timeline_filter_preferences.sh b/test/test_timeline_filter_preferences.sh index 6a762766..34bb2edf 100644 --- a/test/test_timeline_filter_preferences.sh +++ b/test/test_timeline_filter_preferences.sh @@ -8,11 +8,4 @@ swiftc -swift-version 6 swift/JournalTimelineFilterPreferences.swift \ "$work/preferences" bash test/test_timeline_filter_contract.sh -export OCAMLPATH="$PWD/_build/install/default/lib${OCAMLPATH:+:$OCAMLPATH}" -awk '/^module Timeline_filter(_preferences)? = struct$/ { inside=1 } inside { print } /^end$/ { inside=0 }' \ - app/application.ml > "$work/filter_modules.ml" -compile=(ocamlfind ocamlopt -package logseq_db_types,yojson,unix -I "$work") -"${compile[@]}" -c -o "$work/filter_modules.cmx" "$work/filter_modules.ml" -"${compile[@]}" -c -o "$work/test.cmx" test/timeline_filter_preferences_codec_test.ml -"${compile[@]}" -linkpkg -o "$work/codec" "$work/filter_modules.cmx" "$work/test.cmx" -"$work/codec" +dune exec ./test/timeline_filter_preferences_codec_test.exe diff --git a/test/timeline_filter_contract_test.ml b/test/timeline_filter_contract_test.ml index dbdda2b5..3980e1fd 100644 --- a/test/timeline_filter_contract_test.ml +++ b/test/timeline_filter_contract_test.ml @@ -1,4 +1,4 @@ -module Filter = Timeline_filter +module Filter = Journal_timeline_filter.Timeline_filter let uuid suffix = match Filter.Uuid.of_string ("00000000-0000-4000-8000-00000000000" ^ suffix) with @@ -14,23 +14,40 @@ let () = let saved = Filter.criteria ~tags:[ tag; tag ] ~statuses:[ status ] ~time:Filter.any_time in assert (Filter.tags saved = [ tag ]); assert (Filter.active_count saved = 2); - let restored = Filter.restore saved in + let prefs = get (Filter.preferences ~definitions:["Work", saved] ~selected_name:(Some "Work")) in + let restored = Filter.restore prefs in + let submit state command = (get (Filter.submit state command)).next in assert (Filter.sheet restored = None); let reset = Filter.edit (Filter.open_sheet restored) Reset in assert (Filter.draft_tags (draft reset) = []); assert (Filter.active_count (Filter.applied reset) = 2); assert (Filter.applied (Filter.cancel reset) = saved); - assert (Filter.applied (get (Filter.apply reset)) = Filter.all); + assert (Filter.applied (submit reset Apply) = Filter.all); let draft_state = Filter.open_sheet restored in let invalid = Filter.edit draft_state (Set_time (Custom { count_text = "0"; unit_ = Weeks })) in - assert (Filter.apply invalid = Error Invalid_count); + assert (Filter.submit invalid Apply = Error (Invalid_time Invalid_count)); assert (Filter.custom ~count:max_int ~unit_:Weeks = Error Invalid_count); let custom = Filter.edit invalid (Set_time (Custom { count_text = "2"; unit_ = Weeks })) in - let applied = get (Filter.apply (Filter.open_sheet custom)) in + let applied = submit (Filter.open_sheet custom) Apply in assert (Filter.sheet applied = None); assert (Filter.active_count (Filter.applied applied) = 3); assert (Filter.time_choice (Filter.time (Filter.applied applied)) = `Custom (2, Weeks)); let toggled = Filter.edit (Filter.open_sheet applied) (Toggle_status status) in assert (Filter.draft_statuses (draft toggled) = []); - assert (Filter.applied (Filter.cancel toggled) = Filter.applied applied) + assert (Filter.applied (Filter.cancel toggled) = Filter.applied applied); + assert (Filter.entry (Filter.restore Filter.empty_preferences) = Configure_directly); + assert (Filter.entry restored = Native_menu { names = ["Work"]; active_name = Some "Work" }); + assert (Filter.submit draft_state (Save_as " ") = Error (Invalid_preferences Empty_name)); + assert (Filter.submit draft_state (Save_as " Work ") = Error (Invalid_preferences Duplicate_name)); + let saved = get (Filter.submit custom (Save_as " Custom ")) in + let prefs = Option.get saved.replacement in + assert (Filter.selected_name prefs = Some "Custom"); + assert (Filter.applied (Filter.restore prefs) = Filter.applied saved.next); + let applied = get (Filter.submit (Filter.open_sheet saved.next) Apply) in + assert (Filter.selected_name (Option.get applied.replacement) = None); + assert (Filter.definitions (Option.get applied.replacement) = Filter.definitions prefs); + let full = get (Filter.preferences ~definitions:(List.init 5 (fun index -> string_of_int index, Filter.all)) ~selected_name:None) in + let draft = Filter.open_sheet (Filter.restore full) in + assert (Filter.submit draft (Save_as "sixth") = Error (Invalid_preferences Too_many_filters)); + assert ((get (Filter.submit draft Apply)).replacement = None) ;; diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index cf9202af..2c80b891 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -1,37 +1,28 @@ -open Filter_modules -module Filter = Timeline_filter +module Filter = Journal_timeline_filter.Timeline_filter module Preferences = Timeline_filter_preferences let () = let tag = Result.get_ok (Filter.Uuid.of_string "00000000-0000-4000-8000-000000000001") in let status = Result.get_ok (Filter.Uuid.of_string "00000000-0000-4000-8000-000000000002") in - let decode_time time = - Preferences.decode (Printf.sprintf {|{"version":1,"tags":[],"statuses":[],"time":"%s"}|} time) - |> Option.get - in - let months = decode_time "past-3-months" in - List.iter (fun (today, first) -> - assert (Filter.resolve_days months ~today = Some (first, today))) - [ 20240531, 20240229; 20230531, 20230228; 20250115, 20241015; 20241231, 20240930 ]; - List.iter (fun (key, first) -> - let today = 20250107 in - assert (Filter.resolve_days (decode_time key) ~today = Some (first, today))) - [ "past-7-days", 20250101; "past-2-weeks", 20241225 ]; + let criteria time = Filter.criteria ~tags:[tag] ~statuses:[status] ~time in let custom = Result.get_ok (Filter.custom ~count:14 ~unit_:Days) in let preset = Filter.preset Filter.Past_14_days in - let criteria time = Filter.criteria ~tags:[tag] ~statuses:[status] ~time in - List.iter (fun time -> - let value = criteria time in - let restored = Preferences.decode (Preferences.encode value) |> Option.get |> Filter.restore in - assert (Filter.applied restored = value); - assert (Filter.sheet restored = None)) [custom; preset; Filter.time months; Filter.any_time]; - assert (Preferences.encode (criteria custom) <> Preferences.encode (criteria preset)); - List.iter (fun value -> assert (Preferences.decode value = None)) - [ "broken"; {|{"version":2,"tags":[],"statuses":[],"time":"any"}|} - ; {|{"version":1,"tags":["bad"],"statuses":[],"time":"any"}|} - ; {|{"version":1,"tags":[],"statuses":[],"time":[0,"weeks"]}|} ]; - assert (Preferences.unwrap_startup "LDB1\000\255" = ([], "LDB1\000\255")); - assert (Preferences.unwrap_startup "JTF1{\"graph\":\"criteria\"}\nLDB1\000\255" - = (["graph", `String "criteria"], "LDB1\000\255")); - assert (Preferences.unwrap_startup "JTF1invalid-json\nLDB1" = ([], "LDB1")) + let months = Filter.preset Filter.Past_3_months in + let definitions = List.map (fun (name, time) -> name, criteria time) + ["Custom", custom; "Fortnight", preset; "Quarter", months; "All time", Filter.any_time] in + let record = Result.get_ok (Filter.preferences ~definitions ~selected_name:(Some "Quarter")) in + let restored = Result.get_ok (Preferences.decode (Preferences.encode record)) in + assert (Filter.definitions restored = definitions); + assert (Filter.selected_name restored = Some "Quarter"); + assert (Filter.applied (Filter.restore restored) = criteria months); + List.iter (fun (today, first) -> + assert (Journal_filter_date.resolve_days (criteria months) ~today = Some (first, today))) + [20240531, 20240229; 20230531, 20230228; 20250115, 20241015; 20241231, 20240930]; + assert (Preferences.decode {|{"version":1,"tags":[],"statuses":[],"time":"past-7-days"}|} + = Ok Filter.empty_preferences); + List.iter (fun value -> assert (Result.is_error (Preferences.decode value))) + [ "broken"; String.make (512 * 1024 + 1) ' ' + ; {|{"version":2,"definitions":[],"selected":"unknown"}|} + ; {|{"version":2,"definitions":[{"name":"X","tags":["not-a-uuid"],"statuses":[],"time":"any"}],"selected":null}|} + ; {|{"version":2,"definitions":[{"name":"X","tags":[],"statuses":[],"time":[0,"weeks"]}],"selected":null}|} ] ;; diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index 79578cb2..165b23ff 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -7,23 +7,26 @@ import Foundation defer { defaults.removePersistentDomain(forName: suite) } let graphA = "10000000-0000-4000-8000-000000000001" let graphB = "10000000-0000-4000-8000-000000000002" - let preset = #"{"version":1,"tags":[],"statuses":[],"time":"past-7-days"}"# - let custom = #"{"version":1,"tags":[],"statuses":[],"time":[7,"days"]}"# + let preset = #"{"version":2,"definitions":[{"name":"Work","tags":[],"statuses":[],"time":"14-days"}],"selected":"Work"}"# + let custom = #"{"version":2,"definitions":[{"name":"Other","tags":[],"statuses":[],"time":[7,"days"]}],"selected":"Other"}"# let preferences = JournalTimelineFilterPreferences(defaults: defaults) - func commit(_ graph: String, _ criteria: String) { + func commit(_ graph: String, _ criteria: String) -> Bool { preferences.handleCommit(Data("journal.timeline-filter.commit\n\(graph)\n\(criteria)".utf8)) } precondition(preferences.snapshot.isEmpty) - commit(graphA, preset) - commit(graphB, custom) + precondition(commit(graphA, preset)) + precondition(commit(graphB, custom)) let reopened = JournalTimelineFilterPreferences(defaults: UserDefaults(suiteName: suite)!) precondition(reopened.snapshot == [graphA: preset, graphB: custom]) preferences.handleCommit(Data("journal.timeline-filter.draft\n\(graphA)\n".utf8)) - commit("not-a-uuid", custom) + precondition(!commit("not-a-uuid", custom)) precondition(reopened.snapshot == [graphA: preset, graphB: custom]) - commit(graphA, "") - precondition(reopened.snapshot == [graphB: custom]) - precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == [graphB: custom]) + let noSelection = #"{"version":2,"definitions":[{"name":"Work","tags":[],"statuses":[],"time":"14-days"}],"selected":null}"# + precondition(!commit(graphA, "")) + precondition(!commit(graphA, String(repeating: "a", count: 512 * 1024 + 1))) + precondition(reopened.snapshot == [graphA: preset, graphB: custom]) + precondition(commit(graphA, noSelection)) + precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == [graphA: noSelection, graphB: custom]) } static func trySnapshot(_ data: Data) -> [String: String] { From 3accf7f40f1b9eb8be5d3825e0bbaff7e05fc199 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 20:35:51 +0800 Subject: [PATCH 02/14] Restore resident Timeline filter selections and bound startup preferences --- app/application.ml | 29 +++++++++++++++---- app/impl/timeline_filter/timeline_filter.ml | 4 ++- app/timeline_filter_preferences.ml | 16 +++++++--- .../JournalRuntimeStartupBridge.c | 1 + swift/JournalTimelineFilterPreferences.swift | 24 +++++++++++---- test/timeline_filter_contract_test.ml | 11 ++++++- .../timeline_filter_preferences_codec_test.ml | 12 +++++++- test/timeline_filter_preferences_test.swift | 15 ++++++++++ tool/test_journal_runtime_failure.py | 1 + 9 files changed, 96 insertions(+), 17 deletions(-) diff --git a/app/application.ml b/app/application.ml index 27cff68a..ba7206b3 100644 --- a/app/application.ml +++ b/app/application.ml @@ -3500,10 +3500,26 @@ let start (try ignore (Journal_filter_date.resolve_days (applied filters) ~today:(Journal_calendar.local_day calendar)); filters with Invalid_argument reason -> invalid reason)) | Some _ -> invalid "Expected a text record" in - let restore_filters state = - match state.filters_restored, state.graph_state.graph_id, state.calendar with - | false, Some id, Some calendar -> - { state with filters_restored = true; filters = saved_filters id calendar } + let restore_filters ~switched state = + match state.graph_state.graph_id, state.calendar with + | Some id, Some calendar when switched || not state.filters_restored -> + let filters = saved_filters id calendar in + let restored = { state with filters_restored = true; filters } in + let restored = + if not state.filters_restored || Timeline_filter.applied filters = Timeline_filter.applied state.filters + then restored + else + { restored with feed_loaded = false; feed_refresh = None + ; timeline = Journal_timeline_state.empty ~today:(Journal_calendar.local_day calendar) + ; timeline_structure_revision = state.timeline_structure_revision + 1 + ; presented_feed_context = None } in + let warning = match List.assoc_opt (graph_filter_key id) !filter_preferences with + | Some (`String "") -> Some "The saved Timeline filters for this graph exceed the storage limit or are invalid." + | None when List.mem_assoc "overflow" !filter_preferences -> + Some "Some saved Timeline filters could not be loaded (64-graph storage limit or invalid startup data)." + | _ -> None in + Option.fold ~none:restored ~some:(fun message -> + show_sync_error restored (Non_worker_sync_failure message)) warning | _ -> state in let pump = Journal_pump.create () in Journal_pump.set_wakeup pump Journal_bridge.wakeup; @@ -7750,7 +7766,10 @@ let start Option.iter activate_runtime (timeline_scope model); let before = model in let model,eff=transition model in - let model = restore_filters model in + let switched = visible && + (before.graph_state.graph_id <> model.graph_state.graph_id + || before.graph_state.generation <> model.graph_state.generation) in + let model = restore_filters ~switched model in match !before_transition_effect before model with | Error cause -> let message = "Nothing was submitted. " ^ cause in diff --git a/app/impl/timeline_filter/timeline_filter.ml b/app/impl/timeline_filter/timeline_filter.ml index 6ca0b8ea..6e357e95 100644 --- a/app/impl/timeline_filter/timeline_filter.ml +++ b/app/impl/timeline_filter/timeline_filter.ml @@ -162,7 +162,9 @@ let submit state command = | Error error -> Error (Invalid_time error) | Ok time -> let applied = criteria ~tags:sheet.draft_tags ~statuses:sheet.draft_statuses ~time in - match command with + if List.length applied.tags > 100 || List.length applied.statuses > 100 + then Error (Invalid_preferences Too_many_selections) + else match command with | Apply -> finish applied None { previous with selected_name = None } | Save_as name -> let selected_name = Some (String.trim name) in diff --git a/app/timeline_filter_preferences.ml b/app/timeline_filter_preferences.ml index 87278743..7d555e4b 100644 --- a/app/timeline_filter_preferences.ml +++ b/app/timeline_filter_preferences.ml @@ -1,6 +1,10 @@ open Journal_timeline_filter.Timeline_filter let startup_prefix = "JTF1" +let record_limit = 64 * 1024 +let graph_limit = 64 +let envelope_limit = graph_limit * ((6 * record_limit) + 64) + 64 +let unavailable = ["overflow", `String ""] let unwrap_startup payload = if not (String.starts_with ~prefix:startup_prefix payload) then [], payload else @@ -8,11 +12,15 @@ let unwrap_startup payload = | None -> [], payload | Some separator -> let offset = String.length startup_prefix in - let snapshot = String.sub payload offset (separator - offset) in + let length = separator - offset in let config = String.sub payload (separator + 1) (String.length payload - separator - 1) in let entries = - try match Yojson.Safe.from_string snapshot with `Assoc entries -> entries | _ -> [] - with Yojson.Json_error _ -> [] in + if length > envelope_limit then unavailable else + let snapshot = String.sub payload offset length in + try match Yojson.Safe.from_string snapshot with + | `Assoc entries when List.length entries <= graph_limit + 1 -> entries + | _ -> unavailable + with Yojson.Json_error _ | Stack_overflow -> unavailable in entries, config ;; @@ -41,7 +49,7 @@ let decode text = criteria ~tags:(ids (member "tags" value)) ~statuses:(ids (member "statuses" value)) ~time in try - if String.length text > 512 * 1024 then invalid "Filter record exceeds 512 KiB"; + if String.length text > record_limit then invalid "Filter record exceeds 64 KiB"; let value = Yojson.Safe.from_string text in match member "version" value with | `Int 1 -> Ok empty_preferences diff --git a/apple-tests/platform-services/JournalRuntimeStartupBridge.c b/apple-tests/platform-services/JournalRuntimeStartupBridge.c index 995155a5..462939b5 100644 --- a/apple-tests/platform-services/JournalRuntimeStartupBridge.c +++ b/apple-tests/platform-services/JournalRuntimeStartupBridge.c @@ -17,6 +17,7 @@ int32_t lui_ocaml_start(void (*patch)(const char*),int32_t p,int32_t h,const cha int32_t lui_ocaml_stop(void){return 1;} void journal_ocaml_set_wakeup_callback(void(*f)(void)){} void journal_ocaml_set_platform_request_callback(void(*f)(const char*,int32_t)){request=f;} +void journal_ocaml_set_filter_commit_callback(int32_t(*f)(const char*,int32_t)){} int32_t journal_ocaml_pump(void){return 1;} int32_t journal_ocaml_platform_event(const char*d,int32_t n){if(inside)reentrant++;return 1;} int32_t journal_ocaml_platform_response(const char*d,int32_t n){calls++;if(inside)reentrant++;return 1;} diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index 3964a4af..cbb8f691 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -4,13 +4,27 @@ struct JournalTimelineFilterPreferences { let defaults: UserDefaults private static let keyPrefix = "journal.timeline-filter.graph." private static let commitPrefix = Data("journal.timeline-filter.commit\n".utf8) + private static let recordLimit = 64 * 1024 + private static let graphLimit = 64 var snapshot: [String: String] { var values: [String: String] = [:] - for (key, value) in defaults.dictionaryRepresentation() where key.hasPrefix(Self.keyPrefix) { - let graph = String(key.dropFirst(Self.keyPrefix.count)) - if let value = value as? String, UUID(uuidString: graph) != nil { - values[graph] = value + let stored = defaults.dictionaryRepresentation() + for key in stored.keys.sorted() where key.hasPrefix(Self.keyPrefix) { + let graph = key.dropFirst(Self.keyPrefix.count) + guard graph.utf8.prefix(37).count == 36, + let id = UUID(uuidString: String(graph)) else { continue } + let canonical = id.uuidString.lowercased() + guard values[canonical] == nil else { continue } + guard values.count < Self.graphLimit else { + values["overflow"] = "" + break + } + if let value = (stored[Self.keyPrefix + canonical] ?? stored[key]) as? String, + value.utf8.prefix(Self.recordLimit + 1).count <= Self.recordLimit { + values[canonical] = value + } else { + values[canonical] = "" } } return values @@ -27,7 +41,7 @@ struct JournalTimelineFilterPreferences { let body = request.dropFirst(Self.commitPrefix.count) guard let separator = body.firstIndex(of: 10), let id = UUID(uuidString: String(decoding: body.prefix(upTo: separator), as: UTF8.self)), - body.count - body.distance(from: body.startIndex, to: separator) - 1 <= 512 * 1024, + body.count - body.distance(from: body.startIndex, to: separator) - 1 <= Self.recordLimit, let record = String(data: body.suffix(from: separator + 1), encoding: .utf8), !record.isEmpty else { return false } let key = Self.keyPrefix + id.uuidString.lowercased() diff --git a/test/timeline_filter_contract_test.ml b/test/timeline_filter_contract_test.ml index 3980e1fd..b2cac80f 100644 --- a/test/timeline_filter_contract_test.ml +++ b/test/timeline_filter_contract_test.ml @@ -49,5 +49,14 @@ let () = let full = get (Filter.preferences ~definitions:(List.init 5 (fun index -> string_of_int index, Filter.all)) ~selected_name:None) in let draft = Filter.open_sheet (Filter.restore full) in assert (Filter.submit draft (Save_as "sixth") = Error (Invalid_preferences Too_many_filters)); - assert ((get (Filter.submit draft Apply)).replacement = None) + assert ((get (Filter.submit draft Apply)).replacement = None); + List.iter (fun (toggle, selected) -> + let ids = List.init 101 (fun index -> + get (Filter.Uuid.of_string (Printf.sprintf "00000000-0000-4000-8000-%012d" index))) in + let over = List.fold_left (fun state id -> Filter.edit state (toggle id)) draft ids in + assert (Filter.submit over Apply = Error (Invalid_preferences Too_many_selections)); + assert (Filter.submit over (Save_as "Another") = Error (Invalid_preferences Too_many_selections)); + let reduced = Filter.edit over (toggle (List.hd ids)) in + assert (List.length (selected (Filter.applied (submit reduced Apply))) = 100)) + [(fun id -> Filter.Toggle_tag id), Filter.tags; (fun id -> Filter.Toggle_status id), Filter.statuses] ;; diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index 2c80b891..bf4d2c83 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -14,6 +14,16 @@ let () = let restored = Result.get_ok (Preferences.decode (Preferences.encode record)) in assert (Filter.definitions restored = definitions); assert (Filter.selected_name restored = Some "Quarter"); + let config = "\000\255" in + let frame snapshot = "JTF1" ^ snapshot ^ "\n" ^ config in + let graph = "10000000-0000-4000-8000-000000000001" in + let snapshot = Printf.sprintf {|{"%s":"{\"version\":1}"}|} graph in + let entries, decoded_config = Preferences.unwrap_startup (frame snapshot) in + assert (decoded_config = config); + assert (List.assoc_opt graph entries = Some (`String {|{"version":1}|})); + let entries, decoded_config = Preferences.unwrap_startup + (frame (String.make (25 * 1024 * 1024) ' ')) in + assert (decoded_config = config && List.mem_assoc "overflow" entries); assert (Filter.applied (Filter.restore restored) = criteria months); List.iter (fun (today, first) -> assert (Journal_filter_date.resolve_days (criteria months) ~today = Some (first, today))) @@ -21,7 +31,7 @@ let () = assert (Preferences.decode {|{"version":1,"tags":[],"statuses":[],"time":"past-7-days"}|} = Ok Filter.empty_preferences); List.iter (fun value -> assert (Result.is_error (Preferences.decode value))) - [ "broken"; String.make (512 * 1024 + 1) ' ' + [ "broken"; String.make (64 * 1024 + 1) ' ' ; {|{"version":2,"definitions":[],"selected":"unknown"}|} ; {|{"version":2,"definitions":[{"name":"X","tags":["not-a-uuid"],"statuses":[],"time":"any"}],"selected":null}|} ; {|{"version":2,"definitions":[{"name":"X","tags":[],"statuses":[],"time":[0,"weeks"]}],"selected":null}|} ] diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index 165b23ff..c0c66c65 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -27,6 +27,21 @@ import Foundation precondition(reopened.snapshot == [graphA: preset, graphB: custom]) precondition(commit(graphA, noSelection)) precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == [graphA: noSelection, graphB: custom]) + defaults.set(String(repeating: "\\", count: 512 * 1024 + 1), + forKey: "journal.timeline-filter.graph.\(graphA)") + let bounded = reopened.wrapStartup(Data([0, 255])) + precondition(bounded.count < 1024) + precondition(trySnapshot(bounded)[graphB] == custom) + precondition(trySnapshot(bounded)[graphA] == "") + for index in 3...65 { + let graph = String(format: "10000000-0000-4000-8000-%012d", index) + precondition(commit(graph, preset)) + } + let capped = trySnapshot(reopened.wrapStartup(Data([0, 255]))) + precondition(capped.count == 65 && capped["overflow"] == "") + precondition(capped[graphB] == custom) + precondition(capped["10000000-0000-4000-8000-000000000064"] == preset) + precondition(capped["10000000-0000-4000-8000-000000000065"] == nil) } static func trySnapshot(_ data: Data) -> [String: String] { diff --git a/tool/test_journal_runtime_failure.py b/tool/test_journal_runtime_failure.py index d4dab454..62944b40 100644 --- a/tool/test_journal_runtime_failure.py +++ b/tool/test_journal_runtime_failure.py @@ -44,6 +44,7 @@ int32_t journal_ocaml_pump(void) { return mode == 3 ? 0 : 1; } void journal_ocaml_set_wakeup_callback(void (*f)(void)) {} void journal_ocaml_set_platform_request_callback(void (*f)(const char *,int32_t)) {} +void journal_ocaml_set_filter_commit_callback(int32_t (*f)(const char *,int32_t)) {} int32_t journal_ocaml_platform_event(const char *d,int32_t n) { platform_calls++; return mode == 4 ? 0 : 1; } int32_t journal_ocaml_platform_response(const char *d,int32_t n) { platform_calls++; return mode == 5 ? 0 : 1; } int32_t journal_ocaml_platform_failure(const char *d,int32_t n) { platform_calls++; return mode == 6 ? 0 : 1; } From 50d95f86d842f3e008eb3243e5210429ead53a02 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 20:43:16 +0800 Subject: [PATCH 03/14] Reject Timeline filter writes beyond startup capacity --- app/application.ml | 2 +- swift/JournalTimelineFilterPreferences.swift | 115 +++++++++++++++---- test/timeline_filter_preferences_test.swift | 39 +++++-- 3 files changed, 123 insertions(+), 33 deletions(-) diff --git a/app/application.ml b/app/application.ml index ba7206b3..d11778f2 100644 --- a/app/application.ml +++ b/app/application.ml @@ -7244,7 +7244,7 @@ let start | exception Invalid_argument reason -> report reason | _ -> if not (Option.fold ~none:true ~some:(save_filters graph_id) replacement) - then report "Could not save Timeline filter preferences." + then report "Could not save Timeline filter preferences. Saved filters are limited to 64 graphs." else let next = { state with modal = No_modal; filters; filter_error = None } in if applied filters = applied state.filters then next else diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index cbb8f691..accce021 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -7,27 +7,86 @@ struct JournalTimelineFilterPreferences { private static let recordLimit = 64 * 1024 private static let graphLimit = 64 - var snapshot: [String: String] { - var values: [String: String] = [:] - let stored = defaults.dictionaryRepresentation() - for key in stored.keys.sorted() where key.hasPrefix(Self.keyPrefix) { - let graph = key.dropFirst(Self.keyPrefix.count) - guard graph.utf8.prefix(37).count == 36, - let id = UUID(uuidString: String(graph)) else { continue } - let canonical = id.uuidString.lowercased() - guard values[canonical] == nil else { continue } - guard values.count < Self.graphLimit else { - values["overflow"] = "" - break + private struct Record: Decodable { + struct Definition: Decodable { + let name: String + let tags: [UUID] + let statuses: [UUID] + + private enum CodingKeys: String, CodingKey { case name, tags, statuses, time } + + init(from decoder: Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + name = try fields.decode(String.self, forKey: .name) + tags = try fields.decode([UUID].self, forKey: .tags) + statuses = try fields.decode([UUID].self, forKey: .statuses) + if let preset = try? fields.decode(String.self, forKey: .time), + ["any", "14-days", "3-months"].contains(preset) { return } + var time = try fields.nestedUnkeyedContainer(forKey: .time) + let count = try time.decode(Int.self) + let unit = try time.decode(String.self) + let ocamlMaxInt = Int.max / 2 + guard time.isAtEnd, count > 0, + (unit == "days" && count <= ocamlMaxInt || unit == "weeks" && count <= ocamlMaxInt / 7) else { + throw DecodingError.dataCorruptedError(forKey: .time, in: fields, debugDescription: "Invalid relative time") + } + } + + var trimmedName: Data { + Data(name.trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n\u{000C}")).utf8) } - if let value = (stored[Self.keyPrefix + canonical] ?? stored[key]) as? String, - value.utf8.prefix(Self.recordLimit + 1).count <= Self.recordLimit { - values[canonical] = value - } else { - values[canonical] = "" + } + + let version: Int + let definitions: [Definition] + let selected: String? + + static func decode(_ text: String) -> Self? { + guard text.utf8.prefix(JournalTimelineFilterPreferences.recordLimit + 1).count + <= JournalTimelineFilterPreferences.recordLimit, + let record = try? JSONDecoder().decode(Self.self, from: Data(text.utf8)), + record.version == 2, record.definitions.count <= 5 else { return nil } + var names: Set = [] + for definition in record.definitions { + let name = definition.trimmedName + guard (1...128).contains(name.count), names.insert(name).inserted, + definition.tags.count <= 100, definition.statuses.count <= 100 else { return nil } } + if let selected = record.selected, !names.contains(Data(selected.utf8)) { return nil } + return record } - return values + } + + private static func graphID(forKey key: String) -> String? { + guard key.hasPrefix(keyPrefix) else { return nil } + let graph = key.dropFirst(keyPrefix.count) + guard graph.utf8.prefix(37).count == 36 else { return nil } + return UUID(uuidString: String(graph))?.uuidString.lowercased() + } + + private static func admittedRecords(in stored: [String: Any]) -> (records: [String: String], overflow: Bool) { + let keysByGraph = Dictionary(grouping: stored.keys.compactMap { key in + graphID(forKey: key).map { (graph: $0, key: key) } + }, by: \.graph) + var records: [String: String] = [:] + for graph in keysByGraph.keys.sorted() { + let canonicalKey = keyPrefix + graph + let keys = [canonicalKey] + keysByGraph[graph, default: []].map(\.key).filter { $0 != canonicalKey }.sorted() + for key in keys { + guard let value = stored[key] as? String, + let record = Record.decode(value), !record.definitions.isEmpty else { continue } + guard records.count < graphLimit else { return (records, true) } + records[graph] = value + break + } + } + return (records, false) + } + + var snapshot: [String: String] { + var (records, overflow) = Self.admittedRecords(in: defaults.dictionaryRepresentation()) + if overflow { records["overflow"] = "" } + return records } func wrapStartup(_ payload: Data) -> Data { @@ -42,10 +101,20 @@ struct JournalTimelineFilterPreferences { guard let separator = body.firstIndex(of: 10), let id = UUID(uuidString: String(decoding: body.prefix(upTo: separator), as: UTF8.self)), body.count - body.distance(from: body.startIndex, to: separator) - 1 <= Self.recordLimit, - let record = String(data: body.suffix(from: separator + 1), encoding: .utf8), - !record.isEmpty else { return false } - let key = Self.keyPrefix + id.uuidString.lowercased() - defaults.set(record, forKey: key) - return defaults.string(forKey: key) == record + let text = String(data: body.suffix(from: separator + 1), encoding: .utf8), + let record = Record.decode(text) else { return false } + let graph = id.uuidString.lowercased() + let key = Self.keyPrefix + graph + let stored = defaults.dictionaryRepresentation() + if record.definitions.isEmpty { + for key in stored.keys where Self.graphID(forKey: key) == graph { + defaults.removeObject(forKey: key) + } + return true + } + let (admitted, _) = Self.admittedRecords(in: stored) + guard admitted[graph] != nil || admitted.count < Self.graphLimit else { return false } + defaults.set(text, forKey: key) + return defaults.string(forKey: key) == text } } diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index c0c66c65..c9b40c04 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -32,16 +32,37 @@ import Foundation let bounded = reopened.wrapStartup(Data([0, 255])) precondition(bounded.count < 1024) precondition(trySnapshot(bounded)[graphB] == custom) - precondition(trySnapshot(bounded)[graphA] == "") - for index in 3...65 { - let graph = String(format: "10000000-0000-4000-8000-%012d", index) - precondition(commit(graph, preset)) + func graph(_ index: Int) -> String { + String(format: "10000000-0000-4000-8000-%012d", index) } - let capped = trySnapshot(reopened.wrapStartup(Data([0, 255]))) - precondition(capped.count == 65 && capped["overflow"] == "") - precondition(capped[graphB] == custom) - precondition(capped["10000000-0000-4000-8000-000000000064"] == preset) - precondition(capped["10000000-0000-4000-8000-000000000065"] == nil) + for (index, legacy) in [#"{"version":1}"#, #"{"version":3,"definitions":[]}"#, + #"{"version":2,"definitions":[],"selected":null}"#, + #"{"version":2,"definitions":[{"name":"Broken"}],"selected":null}"#, + preset.replacingOccurrences(of: "\"selected\":\"Work\"", with: "\"selected\":\"Missing\""), + "not json"].enumerated() { + defaults.set(legacy, forKey: "journal.timeline-filter.graph.\(graph(index + 3))") + } + var expected = [graphB: custom] + for index in 10...72 { + precondition(commit(graph(index), preset)) + expected[graph(index)] = preset + } + precondition(!commit(graph(0), preset), "A write must not displace an existing graph") + precondition(!commit(graph(73), preset), "A write must not succeed and disappear on restart") + precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) + precondition(commit(graph(72), noSelection)) + expected[graph(72)] = noSelection + precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) + let empty = #"{"version":2,"definitions":[],"selected":null}"# + precondition(commit(graphB, empty)) + expected.removeValue(forKey: graphB) + precondition(commit(graph(73), preset)) + expected[graph(73)] = preset + precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) + defaults.set(preset, forKey: "journal.timeline-filter.graph.\(graph(74))") + expected["overflow"] = "" + precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) + precondition(defaults.string(forKey: "journal.timeline-filter.graph.\(graph(74))") == preset) } static func trySnapshot(_ data: Data) -> [String: String] { From 3daab2efc86952ba5c011a257abaad5902eb6db2 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 20:45:19 +0800 Subject: [PATCH 04/14] Delete saved Timeline filters from Configure --- app/application.ml | 10 ++++-- app/impl/timeline_filter/timeline_filter.ml | 17 +++++++-- app/spec/filter/timeline_filter.mli | 11 ++++-- swift/JournalChrome.swift | 38 +++++++++++++++++++++ test/timeline_filter_contract_test.ml | 27 +++++++++++++++ 5 files changed, 97 insertions(+), 6 deletions(-) diff --git a/app/application.ml b/app/application.ml index d11778f2..ae0e514d 100644 --- a/app/application.ml +++ b/app/application.ml @@ -2698,6 +2698,9 @@ let filters_page state dispatch filter_draft = let payload = Yojson.Safe.to_string (`Assoc [ "mode", `String "filter-overlay"; "enabled", `Bool enabled ; "sheetEpoch", `Int picker.sheet_epoch + ; "filterNames", `List (match Timeline_filter.entry state.filters with + | Configure_directly -> [] + | Native_menu { names; _ } -> List.map (fun name -> `String name) names) ; "choices", `Assoc [ "tags", `List selected; "statuses", `List options ; "times", `List times; "results", `List results ] ; "filterError", Option.fold ~none:`Null ~some:(fun text -> `String text) state.filter_error @@ -2712,6 +2715,8 @@ let filters_page state dispatch filter_draft = | "apply" when enabled -> dispatch.send (Submit_filters (event.event_id, Apply)) | _ when enabled && String.starts_with ~prefix:"save:" raw -> dispatch.send (Submit_filters (event.event_id, Save_as (String.sub raw 5 (String.length raw - 5)))) + | _ when String.starts_with ~prefix:"delete:" raw -> + dispatch.send (Submit_filters (event.event_id, Delete (String.sub raw 7 (String.length raw - 7)))) | _ when String.starts_with ~prefix:"search:" raw -> dispatch.send (Edit_filter_tag_text (String.sub raw 7 (String.length raw - 7))) | _ when String.starts_with ~prefix:"count:" raw -> @@ -7229,7 +7234,7 @@ let start update (fun state -> let open Timeline_filter in let valid_owner = match command with - | Apply | Save_as _ -> state.modal = Filters_sheet && state.filter_tag_picker.sheet_epoch = epoch + | Apply | Save_as _ | Delete _ -> state.modal = Filters_sheet && state.filter_tag_picker.sheet_epoch = epoch | Select _ | Clear -> state.modal = No_modal && state.graph_state.generation = epoch && Journal_routes.destination state.routes = Journals in if not valid_owner || not state.graph_ready || not state.filters_restored then state else @@ -7246,7 +7251,8 @@ let start if not (Option.fold ~none:true ~some:(save_filters graph_id) replacement) then report "Could not save Timeline filter preferences. Saved filters are limited to 64 graphs." else - let next = { state with modal = No_modal; filters; filter_error = None } in + let modal = match command with Delete _ -> Filters_sheet | _ -> No_modal in + let next = { state with modal; filters; filter_error = None } in if applied filters = applied state.filters then next else { next with feed_loaded = false; feed_refresh = None ; timeline = Journal_timeline_state.empty ~today diff --git a/app/impl/timeline_filter/timeline_filter.ml b/app/impl/timeline_filter/timeline_filter.ml index 6e357e95..d60e6074 100644 --- a/app/impl/timeline_filter/timeline_filter.ml +++ b/app/impl/timeline_filter/timeline_filter.ml @@ -138,7 +138,7 @@ let edit state change = let cancel state = { state with sheet = None } -type command = Apply | Save_as of string | Select of string | Clear +type command = Apply | Save_as of string | Select of string | Clear | Delete of string type error = Invalid_time of time_error | Invalid_preferences of preference_error | No_open_sheet | Unknown_name type transition = { next : t; replacement : preferences option } @@ -154,6 +154,19 @@ let submit state command = (match List.assoc_opt name previous.definitions with | None -> Error Unknown_name | Some applied -> finish applied state.sheet { previous with selected_name = Some name }) + | Delete name -> + (match state.sheet with + | None -> Error No_open_sheet + | Some sheet -> + if not (List.mem_assoc name previous.definitions) then Error Unknown_name else + let definitions = List.remove_assoc name previous.definitions in + if previous.selected_name = Some name then + let unchanged = + List.sort Uuid.compare sheet.draft_tags = state.applied.tags + && List.sort Uuid.compare sheet.draft_statuses = state.applied.statuses + && sheet.draft_time = (draft state.applied).draft_time in + finish all (Some (if unchanged then draft all else sheet)) { definitions; selected_name = None } + else finish state.applied state.sheet { previous with definitions }) | Apply | Save_as _ -> match state.sheet with | None -> Error No_open_sheet @@ -171,5 +184,5 @@ let submit state command = (match preferences ~definitions:(previous.definitions @ [name, applied]) ~selected_name with | Ok preferences -> finish applied None preferences | Error error -> Error (Invalid_preferences error)) - | Clear | Select _ -> assert false + | Clear | Select _ | Delete _ -> assert false ;; diff --git a/app/spec/filter/timeline_filter.mli b/app/spec/filter/timeline_filter.mli index 8f384739..0f8c1169 100644 --- a/app/spec/filter/timeline_filter.mli +++ b/app/spec/filter/timeline_filter.mli @@ -192,13 +192,14 @@ val cancel : t -> t draft unchanged. The host owns the naming prompt and its input. Do not use an existing name as an implicit overwrite. *) -(** {1 Apply, save, select, and clear} *) +(** {1 Apply, save, select, clear, and delete} *) type command = | Apply | Save_as of string | Select of string | Clear + | Delete of string type error = | Invalid_time of time_error @@ -221,7 +222,13 @@ type transition = private capacity; it does not add a definition. Select activates an existing name and persists the selection. Clear applies [all] and clears the selected name without deleting definitions. - Select and Clear do not modify a draft. Validation errors preserve the + Select and Clear do not modify a draft. Delete requires an open sheet and + an exact existing name. Offer it only in the configuration sheet, with + confirmation naming the definition. Canceling confirmation has no effect. + Delete removes only that definition and keeps the sheet open. Deleting the + selected definition clears the selection and applies [all]; rebase an + unchanged draft to [all] but keep edits. Other deletions leave applied + criteria, selection and draft unchanged. Validation errors preserve the draft, active criteria and preferences. Keep naming open with feedback for a rejected name; surface draft errors in the sheet. diff --git a/swift/JournalChrome.swift b/swift/JournalChrome.swift index 9754bbc1..1db72ef3 100644 --- a/swift/JournalChrome.swift +++ b/swift/JournalChrome.swift @@ -439,6 +439,9 @@ struct JournalSheetDismissButton: SwiftUI.View { let accessibilityFocus: AccessibilityFocusState.Binding #endif @State private var showsTags = false + @State private var managesSavedFilters = false + @State private var confirmingDeletion = false + @State private var deletionName: String? @State private var naming = false @State private var filterName = "" @FocusState private var editing: Field? @@ -566,8 +569,43 @@ struct JournalSheetDismissButton: SwiftUI.View { return formatter.string(from: dates[0], to: dates[1]) + " · Includes today" } + private func savedFilterManagement(_ names: [String]) -> some SwiftUI.View { + DisclosureGroup("Manage saved filters", isExpanded: $managesSavedFilters) { + ForEach(names, id: \.self) { name in + HStack { + Text(verbatim: name) + Spacer() + Button(role: .destructive) { + editing = nil + deletionName = name + confirmingDeletion = true + } label: { + Image(systemName: "trash") + .frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .foregroundStyle(.red) + .accessibilityLabel("Delete \(name)") + } + } + } + .font(.subheadline) + .tint(filterBlue(scheme)) + .alert("Delete saved filter?", isPresented: $confirmingDeletion, presenting: deletionName) { name in + Button("Cancel", role: .cancel) {} + Button("Delete", role: .destructive) { send("delete:" + name) } + } message: { name in + Text("Delete ‘\(name)’ from saved filters?") + } + } + private var fields: some SwiftUI.View { VStack(alignment: .leading, spacing: 6) { + if let names = properties.filterNames, !names.isEmpty { + savedFilterManagement(names) + Divider().padding(.vertical, 4) + } heading("TAG · MATCH ANY") FilterChipRows { ForEach(choices.tags) { chip($0) } diff --git a/test/timeline_filter_contract_test.ml b/test/timeline_filter_contract_test.ml index b2cac80f..84158b18 100644 --- a/test/timeline_filter_contract_test.ml +++ b/test/timeline_filter_contract_test.ml @@ -50,6 +50,33 @@ let () = let draft = Filter.open_sheet (Filter.restore full) in assert (Filter.submit draft (Save_as "sixth") = Error (Invalid_preferences Too_many_filters)); assert ((get (Filter.submit draft Apply)).replacement = None); + let delete state name = get (Filter.submit state (Delete name)) in + let active = Filter.open_sheet saved.next in + assert (Filter.submit saved.next (Delete "Custom") = Error No_open_sheet); + assert (Filter.submit active (Delete " Custom ") = Error Unknown_name); + let deleted = delete active "Custom" in + let persisted = Option.get deleted.replacement in + assert (List.map fst (Filter.definitions persisted) = ["Work"]); + assert (Filter.selected_name persisted = None); + assert (Filter.applied (Filter.restore persisted) = Filter.all); + assert (Filter.applied deleted.next = Filter.all); + assert (Filter.applied (submit deleted.next Apply) = Filter.all); + let edited = Filter.edit active (Set_time (Custom { count_text = "0"; unit_ = Weeks })) in + assert (Filter.sheet (delete edited "Custom").next = Filter.sheet edited); + let inactive = delete active "Work" in + assert (Filter.sheet inactive.next = Filter.sheet active); + assert (Filter.applied inactive.next = Filter.applied active); + let persisted = Option.get inactive.replacement in + assert (Filter.selected_name persisted = Some "Custom"); + assert (Filter.applied (Filter.restore persisted) = Filter.applied active); + let anonymous = Filter.open_sheet (submit active Apply) in + let deleted = delete anonymous "Work" in + assert (Filter.applied deleted.next = Filter.applied anonymous); + assert (Filter.sheet deleted.next = Filter.sheet anonymous); + assert (Filter.selected_name (Option.get deleted.replacement) = None); + let freed = delete draft "2" in + let refilled = get (Filter.submit freed.next (Save_as "sixth")) in + assert (List.map fst (Filter.definitions (Option.get refilled.replacement)) = ["0"; "1"; "3"; "4"; "sixth"]); List.iter (fun (toggle, selected) -> let ids = List.init 101 (fun index -> get (Filter.Uuid.of_string (Printf.sprintf "00000000-0000-4000-8000-%012d" index))) in From 745629c3ed7622c8462e05bffa55dbc50f6b5f9d Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 20:55:37 +0800 Subject: [PATCH 05/14] Guard Timeline filter commits against unseen records --- app/application.ml | 12 +++--- app/timeline_filter_preferences.ml | 11 +++++ swift/JournalTimelineFilterPreferences.swift | 43 +++++++++++++------ .../timeline_filter_preferences_codec_test.ml | 6 +++ test/timeline_filter_preferences_test.swift | 26 +++++++---- 5 files changed, 70 insertions(+), 28 deletions(-) diff --git a/app/application.ml b/app/application.ml index ae0e514d..51461a67 100644 --- a/app/application.ml +++ b/app/application.ml @@ -3484,12 +3484,10 @@ let start String.lowercase_ascii (Logseq_db_types.Graph_types.Uuid.to_string id) in let save_filters id preferences = let key = graph_filter_key id in - let text = Timeline_filter_preferences.encode preferences in - if Journal_bridge.commit_timeline_filter ("journal.timeline-filter.commit\n" ^ key ^ "\n" ^ text) - then ( - filter_preferences := (key, `String text) :: List.remove_assoc key !filter_preferences; - true) - else false in + match Timeline_filter_preferences.commit ~persist:Journal_bridge.commit_timeline_filter + !filter_preferences ~key preferences with + | Some retained -> filter_preferences := retained; true + | None -> false in let saved_filters id calendar = let open Timeline_filter in let invalid reason = @@ -7249,7 +7247,7 @@ let start | exception Invalid_argument reason -> report reason | _ -> if not (Option.fold ~none:true ~some:(save_filters graph_id) replacement) - then report "Could not save Timeline filter preferences. Saved filters are limited to 64 graphs." + then report "Could not update saved Timeline filters. Restart the app to reload saved filters. If you have filters saved for 64 graphs, remove filters from another graph before adding more." else let modal = match command with Delete _ -> Filters_sheet | _ -> No_modal in let next = { state with modal; filters; filter_error = None } in diff --git a/app/timeline_filter_preferences.ml b/app/timeline_filter_preferences.ml index 7d555e4b..3861448f 100644 --- a/app/timeline_filter_preferences.ml +++ b/app/timeline_filter_preferences.ml @@ -81,3 +81,14 @@ let encode record = let selected = Option.fold ~none:`Null ~some:(fun name -> `String name) (selected_name record) in Yojson.Safe.to_string (`Assoc ["version", `Int 2; "definitions", `List (List.map definition (definitions record)); "selected", selected]) ;; + +let commit ~persist entries ~key record = + let text = encode record in + let expected = match List.assoc_opt key entries with Some (`String _ as value) -> value | _ -> `Null in + let request = "journal.timeline-filter.commit\n" ^ key ^ "\n" + ^ Yojson.Safe.to_string expected ^ "\n" ^ text in + if persist request then ( + let rest = List.remove_assoc key entries in + Some (if definitions record = [] then rest else (key, `String text) :: rest)) + else None +;; diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index accce021..003352aa 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -64,21 +64,25 @@ struct JournalTimelineFilterPreferences { return UUID(uuidString: String(graph))?.uuidString.lowercased() } + private static func storedRecord(for graph: String, keys: [String], in stored: [String: Any]) -> String? { + let canonicalKey = keyPrefix + graph + for key in [canonicalKey] + keys.filter({ $0 != canonicalKey }).sorted() { + if let value = stored[key] as? String, + let record = Record.decode(value), !record.definitions.isEmpty { return value } + } + return nil + } + private static func admittedRecords(in stored: [String: Any]) -> (records: [String: String], overflow: Bool) { let keysByGraph = Dictionary(grouping: stored.keys.compactMap { key in graphID(forKey: key).map { (graph: $0, key: key) } }, by: \.graph) var records: [String: String] = [:] for graph in keysByGraph.keys.sorted() { - let canonicalKey = keyPrefix + graph - let keys = [canonicalKey] + keysByGraph[graph, default: []].map(\.key).filter { $0 != canonicalKey }.sorted() - for key in keys { - guard let value = stored[key] as? String, - let record = Record.decode(value), !record.definitions.isEmpty else { continue } - guard records.count < graphLimit else { return (records, true) } - records[graph] = value - break - } + guard let value = storedRecord(for: graph, keys: keysByGraph[graph, default: []].map(\.key), in: stored) + else { continue } + guard records.count < graphLimit else { return (records, true) } + records[graph] = value } return (records, false) } @@ -99,15 +103,28 @@ struct JournalTimelineFilterPreferences { guard request.starts(with: Self.commitPrefix) else { return false } let body = request.dropFirst(Self.commitPrefix.count) guard let separator = body.firstIndex(of: 10), - let id = UUID(uuidString: String(decoding: body.prefix(upTo: separator), as: UTF8.self)), - body.count - body.distance(from: body.startIndex, to: separator) - 1 <= Self.recordLimit, - let text = String(data: body.suffix(from: separator + 1), encoding: .utf8), + let id = UUID(uuidString: String(decoding: body.prefix(upTo: separator), as: UTF8.self)) else { return false } + let mutation = body.suffix(from: separator + 1) + guard let expectedEnd = mutation.firstIndex(of: 10), + mutation.distance(from: mutation.startIndex, to: expectedEnd) <= 6 * Self.recordLimit + 2 else { return false } + let expected: String? + do { + expected = try JSONDecoder().decode(String?.self, from: mutation.prefix(upTo: expectedEnd)) + } catch { + return false + } + let replacement = mutation.suffix(from: expectedEnd + 1) + guard replacement.count <= Self.recordLimit, + let text = String(data: replacement, encoding: .utf8), let record = Record.decode(text) else { return false } let graph = id.uuidString.lowercased() let key = Self.keyPrefix + graph let stored = defaults.dictionaryRepresentation() + let keys = stored.keys.filter { Self.graphID(forKey: $0) == graph } + let current = Self.storedRecord(for: graph, keys: keys, in: stored) + guard current.map({ Data($0.utf8) }) == expected.map({ Data($0.utf8) }) else { return false } if record.definitions.isEmpty { - for key in stored.keys where Self.graphID(forKey: key) == graph { + for key in keys { defaults.removeObject(forKey: key) } return true diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index bf4d2c83..dd0505a6 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -14,6 +14,12 @@ let () = let restored = Result.get_ok (Preferences.decode (Preferences.encode record)) in assert (Filter.definitions restored = definitions); assert (Filter.selected_name restored = Some "Quarter"); + let key = "10000000-0000-4000-8000-000000000002" in + let other_entries = ["another graph", `String (Preferences.encode record)] in + let entries = (key, `String (Preferences.encode record)) :: other_entries in + let commit ~accepted = Preferences.commit ~persist:(fun _ -> accepted) entries ~key Filter.empty_preferences in + assert (commit ~accepted:false = None); + assert (commit ~accepted:true = Some other_entries); let config = "\000\255" in let frame snapshot = "JTF1" ^ snapshot ^ "\n" ^ config in let graph = "10000000-0000-4000-8000-000000000001" in diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index c9b40c04..85ba12d9 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -10,8 +10,9 @@ import Foundation let preset = #"{"version":2,"definitions":[{"name":"Work","tags":[],"statuses":[],"time":"14-days"}],"selected":"Work"}"# let custom = #"{"version":2,"definitions":[{"name":"Other","tags":[],"statuses":[],"time":[7,"days"]}],"selected":"Other"}"# let preferences = JournalTimelineFilterPreferences(defaults: defaults) - func commit(_ graph: String, _ criteria: String) -> Bool { - preferences.handleCommit(Data("journal.timeline-filter.commit\n\(graph)\n\(criteria)".utf8)) + func commit(_ graph: String, _ criteria: String, expecting: String? = nil) -> Bool { + let expected = String(decoding: try! JSONEncoder().encode(expecting), as: UTF8.self) + return preferences.handleCommit(Data("journal.timeline-filter.commit\n\(graph)\n\(expected)\n\(criteria)".utf8)) } precondition(preferences.snapshot.isEmpty) precondition(commit(graphA, preset)) @@ -22,10 +23,10 @@ import Foundation precondition(!commit("not-a-uuid", custom)) precondition(reopened.snapshot == [graphA: preset, graphB: custom]) let noSelection = #"{"version":2,"definitions":[{"name":"Work","tags":[],"statuses":[],"time":"14-days"}],"selected":null}"# - precondition(!commit(graphA, "")) - precondition(!commit(graphA, String(repeating: "a", count: 512 * 1024 + 1))) + precondition(!commit(graphA, "", expecting: preset)) + precondition(!commit(graphA, String(repeating: "a", count: 512 * 1024 + 1), expecting: preset)) precondition(reopened.snapshot == [graphA: preset, graphB: custom]) - precondition(commit(graphA, noSelection)) + precondition(commit(graphA, noSelection, expecting: preset)) precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == [graphA: noSelection, graphB: custom]) defaults.set(String(repeating: "\\", count: 512 * 1024 + 1), forKey: "journal.timeline-filter.graph.\(graphA)") @@ -50,11 +51,11 @@ import Foundation precondition(!commit(graph(0), preset), "A write must not displace an existing graph") precondition(!commit(graph(73), preset), "A write must not succeed and disappear on restart") precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) - precondition(commit(graph(72), noSelection)) + precondition(commit(graph(72), noSelection, expecting: preset)) expected[graph(72)] = noSelection precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) let empty = #"{"version":2,"definitions":[],"selected":null}"# - precondition(commit(graphB, empty)) + precondition(commit(graphB, empty, expecting: custom)) expected.removeValue(forKey: graphB) precondition(commit(graph(73), preset)) expected[graph(73)] = preset @@ -62,7 +63,16 @@ import Foundation defaults.set(preset, forKey: "journal.timeline-filter.graph.\(graph(74))") expected["overflow"] = "" precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == expected) - precondition(defaults.string(forKey: "journal.timeline-filter.graph.\(graph(74))") == preset) + let overflowKey = "journal.timeline-filter.graph.\(graph(74))" + let startup = reopened.snapshot + precondition(startup[graph(74)] == nil) + precondition(commit(graph(10), empty, expecting: startup[graph(10)])) + precondition(reopened.snapshot[graph(74)] == preset) + precondition(!commit(graph(74), custom), "An unseen record must not be overwritten after admission") + precondition(!commit(graph(74), empty), "An unseen record must not be deleted after admission") + precondition(defaults.string(forKey: overflowKey) == preset) + precondition(commit(graph(74), custom, expecting: reopened.snapshot[graph(74)])) + precondition(defaults.string(forKey: overflowKey) == custom) } static func trySnapshot(_ data: Data) -> [String: String] { From 714ffa6072e3c534a554056f2c6e8d83e462052f Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 21:30:37 +0800 Subject: [PATCH 06/14] Default Timeline to the past three months --- app/application.ml | 9 ++++----- app/impl/timeline_filter/timeline_filter.ml | 12 +++++------- app/journal_filter_date.ml | 1 - app/spec/filter/timeline_filter.mli | 10 ++++------ app/timeline_filter_preferences.ml | 3 +-- test/timeline_filter_contract_test.ml | 11 ++++++++++- test/timeline_filter_preferences_codec_test.ml | 18 +++++++++++++++++- 7 files changed, 41 insertions(+), 23 deletions(-) diff --git a/app/application.ml b/app/application.ml index 51461a67..058b29b4 100644 --- a/app/application.ml +++ b/app/application.ml @@ -2642,7 +2642,7 @@ let filters_page state dispatch filter_draft = let custom_time = match time with | Custom _ -> time | Preset Past_14_days -> Custom { count_text = "14"; unit_ = Days } - | Any_time | Preset Past_3_months -> Custom { count_text = "7"; unit_ = Days } + | Preset Past_3_months -> Custom { count_text = "7"; unit_ = Days } in let range = match validate_draft_time filter_draft, state.calendar with | Ok time, Some calendar -> @@ -2662,8 +2662,7 @@ let filters_page state dispatch filter_draft = let options = List.map (fun (id, title) -> choice ("status-" ^ Uuid.to_string id) title (List.mem id selected_statuses) (Toggle_status id)) statuses in let times = List.map (fun (id, label, control, selected) -> choice id label selected (Set_time control)) - [ "any", "Any time", Any_time, time = Any_time - ; "fortnight", "14 days", Preset Past_14_days, time = Preset Past_14_days + [ "fortnight", "14 days", Preset Past_14_days, time = Preset Past_14_days ; "quarter", "3 months", Preset Past_3_months, time = Preset Past_3_months ; "custom", "Custom", custom_time, (match time with Custom _ -> true | _ -> false) ] in let custom = match time with @@ -2672,7 +2671,7 @@ let filters_page state dispatch filter_draft = choice id label (unit_choice = unit_) (Set_time (Custom { count_text; unit_ = unit_choice }))) [ "days", "days", Days; "weeks", "weeks", Weeks ] in `Assoc [ "count", `String count_text; "units", `List units ] - | Any_time | Preset _ -> `Null + | Preset _ -> `Null in let selected_tags = draft_tags filter_draft in let picker = state.filter_tag_picker in @@ -2724,7 +2723,7 @@ let filters_page state dispatch filter_draft = | Custom { unit_; _ } -> let count_text = String.sub raw 6 (String.length raw - 6) in dispatch.send (Edit_filters (Set_time (Custom { count_text; unit_ }))) - | Any_time | Preset _ -> ()) + | Preset _ -> ()) | _ -> Option.iter dispatch.send (List.assoc_opt raw !actions) in payload, on_event diff --git a/app/impl/timeline_filter/timeline_filter.ml b/app/impl/timeline_filter/timeline_filter.ml index d60e6074..efe59c59 100644 --- a/app/impl/timeline_filter/timeline_filter.ml +++ b/app/impl/timeline_filter/timeline_filter.ml @@ -4,11 +4,11 @@ type tag_id = Uuid.t type status_id = Uuid.t type unit_ = Days | Weeks type preset = Past_14_days | Past_3_months -type relative_time = [ `Any_time | `Preset of preset | `Custom of int * unit_ ] +type relative_time = [ `Preset of preset | `Custom of int * unit_ ] type time_error = Invalid_count -let any_time = `Any_time let preset value = `Preset value +let default_time = preset Past_3_months let custom ~count ~unit_ = let multiplier = match unit_ with Days -> 1 | Weeks -> 7 in @@ -25,7 +25,7 @@ let criteria ~tags ~statuses ~time = { tags = List.sort_uniq Uuid.compare tags; statuses = List.sort_uniq Uuid.compare statuses; time } ;; -let all = criteria ~tags:[] ~statuses:[] ~time:any_time +let all = criteria ~tags:[] ~statuses:[] ~time:default_time let tags criteria = criteria.tags let statuses criteria = criteria.statuses let time criteria = criteria.time @@ -33,10 +33,10 @@ let time criteria = criteria.time let active_count criteria = Bool.to_int (criteria.tags <> []) + Bool.to_int (criteria.statuses <> []) - + Bool.to_int (criteria.time <> any_time) + + Bool.to_int (criteria.time <> default_time) ;; -type time_control = Any_time | Preset of preset | Custom of { count_text : string; unit_ : unit_ } +type time_control = Preset of preset | Custom of { count_text : string; unit_ : unit_ } type sheet = { draft_tags : tag_id list; draft_statuses : status_id list; draft_time : time_control } type preferences = { definitions : (string * criteria) list; selected_name : string option } @@ -89,7 +89,6 @@ let draft_time sheet = sheet.draft_time let validate_draft_time sheet = match sheet.draft_time with - | Any_time -> Ok any_time | Preset value -> Ok (preset value) | Custom { count_text; unit_ } -> if not (String.for_all (function '0' .. '9' -> true | _ -> false) count_text) @@ -103,7 +102,6 @@ let validate_draft_time sheet = let draft criteria = let draft_time = match time_choice criteria.time with - | `Any_time -> Any_time | `Preset value -> Preset value | `Custom (count, unit_) -> Custom { count_text = string_of_int count; unit_ } in diff --git a/app/journal_filter_date.ml b/app/journal_filter_date.ml index f01df1a9..f31189a2 100644 --- a/app/journal_filter_date.ml +++ b/app/journal_filter_date.ml @@ -27,7 +27,6 @@ let resolve_days criteria ~today = Some ((start.tm_year + 1900) * 10000 + (start.tm_mon + 1) * 100 + start.tm_mday, today) in match time_choice (time criteria) with - | `Any_time -> None | `Preset Past_3_months -> calendar_months () | `Preset Past_14_days -> days 14 | `Custom (count, Days) -> days count diff --git a/app/spec/filter/timeline_filter.mli b/app/spec/filter/timeline_filter.mli index 0f8c1169..b424db06 100644 --- a/app/spec/filter/timeline_filter.mli +++ b/app/spec/filter/timeline_filter.mli @@ -47,7 +47,6 @@ type preset = type relative_time type time_error = Invalid_count -val any_time : relative_time val preset : preset -> relative_time (** The custom count is a positive integer. Reject arithmetic overflow rather @@ -58,11 +57,11 @@ val custom : count:int -> unit_:unit_ -> (relative_time, time_error) result same date range but reopen in different controls. *) val time_choice : relative_time - -> [ `Any_time | `Preset of preset | `Custom of int * unit_ ] + -> [ `Preset of preset | `Custom of int * unit_ ] type criteria -(** No tag or status selected, with [any_time]. The default Timeline settings. *) +(** The default Timeline criteria: no tags or statuses, and [Past_3_months]. *) val all : criteria (** Construct settings from validated values, e.g. after decoding local @@ -77,7 +76,7 @@ val tags : criteria -> tag_id list val statuses : criteria -> status_id list val time : criteria -> relative_time -(** Count active groups (0..3), not selections or named definitions. *) +(** Count groups that differ from the default (0..3), not selections or named definitions. *) val active_count : criteria -> int (** {1 Graph preferences and restoration} *) @@ -150,7 +149,6 @@ val draft_tags : sheet -> tag_id list val draft_statuses : sheet -> status_id list type time_control = - | Any_time | Preset of preset | Custom of { count_text : string @@ -159,7 +157,7 @@ type time_control = val draft_time : sheet -> time_control -(** Show Any time, 14 days, 3 months, and Custom. The 3-month preset starts on +(** Show 14 days, 3 months, and Custom. The 3-month preset starts on the same day of the month three Gregorian calendar months before today, clamped to that month's last day if necessary. Both endpoints are inclusive. Only Custom exposes the numeric input and Days/Weeks selector. Raw text can be partial or invalid; show the diff --git a/app/timeline_filter_preferences.ml b/app/timeline_filter_preferences.ml index 3861448f..6825389e 100644 --- a/app/timeline_filter_preferences.ml +++ b/app/timeline_filter_preferences.ml @@ -38,7 +38,7 @@ let decode text = (bounded 100 value) in let criteria_of_json value = let time = match member "time" value with - | `String "any" -> any_time + | `String "any" -> time all | `String "14-days" -> preset Past_14_days | `String "3-months" -> preset Past_3_months | `List [`Int count; `String unit_name] -> @@ -72,7 +72,6 @@ let encode record = let ids values = `List (List.map (fun id -> `String (Uuid.to_string id)) values) in let definition (name, value) = let time = match time_choice (time value) with - | `Any_time -> `String "any" | `Preset Past_14_days -> `String "14-days" | `Preset Past_3_months -> `String "3-months" | `Custom (count, unit_) -> `List [`Int count; `String (match unit_ with Days -> "days" | Weeks -> "weeks")] in diff --git a/test/timeline_filter_contract_test.ml b/test/timeline_filter_contract_test.ml index 84158b18..3e476e51 100644 --- a/test/timeline_filter_contract_test.ml +++ b/test/timeline_filter_contract_test.ml @@ -11,15 +11,24 @@ let draft state = Option.get (Filter.sheet state) let () = let tag = uuid "1" and status = uuid "2" in - let saved = Filter.criteria ~tags:[ tag; tag ] ~statuses:[ status ] ~time:Filter.any_time in + let saved = Filter.criteria ~tags:[ tag; tag ] ~statuses:[ status ] ~time:(Filter.preset Past_3_months) in assert (Filter.tags saved = [ tag ]); assert (Filter.active_count saved = 2); let prefs = get (Filter.preferences ~definitions:["Work", saved] ~selected_name:(Some "Work")) in let restored = Filter.restore prefs in let submit state command = (get (Filter.submit state command)).next in + let assert_default state = + let criteria = Filter.applied state in + assert (Filter.time_choice (Filter.time criteria) = `Preset Past_3_months); + assert (Filter.active_count criteria = 0) + in + assert_default (Filter.restore Filter.empty_preferences); + assert_default (submit restored Clear); assert (Filter.sheet restored = None); let reset = Filter.edit (Filter.open_sheet restored) Reset in assert (Filter.draft_tags (draft reset) = []); + assert (Filter.draft_time (draft reset) = Preset Past_3_months); + assert_default (submit reset Apply); assert (Filter.active_count (Filter.applied reset) = 2); assert (Filter.applied (Filter.cancel reset) = saved); assert (Filter.applied (submit reset Apply) = Filter.all); diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index dd0505a6..a05e47b8 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -9,7 +9,23 @@ let () = let preset = Filter.preset Filter.Past_14_days in let months = Filter.preset Filter.Past_3_months in let definitions = List.map (fun (name, time) -> name, criteria time) - ["Custom", custom; "Fortnight", preset; "Quarter", months; "All time", Filter.any_time] in + ["Custom", custom; "Fortnight", preset; "Quarter", months] in + let legacy = {|{ "version":2,"definitions":[{"name":"Old","tags":["00000000-0000-4000-8000-000000000001"],"statuses":["00000000-0000-4000-8000-000000000002"],"time":"any"}],"selected":"Old" }|} in + let migrated = Result.get_ok (Preferences.decode legacy) in + assert (Filter.selected_name migrated = Some "Old"); + assert (Filter.definitions migrated = ["Old", criteria months]); + let legacy_key = "legacy-graph" in + let persist request = + match String.split_on_char '\n' request with + | [_; key; expected; replacement] -> + assert (key = legacy_key); + let escaped = String.concat "\\\"" (String.split_on_char '"' legacy) in + assert (expected = "\"" ^ escaped ^ "\""); + assert (Result.get_ok (Preferences.decode replacement) = migrated); + true + | _ -> assert false + in + assert (Option.is_some (Preferences.commit ~persist [legacy_key, `String legacy] ~key:legacy_key migrated)); let record = Result.get_ok (Filter.preferences ~definitions ~selected_name:(Some "Quarter")) in let restored = Result.get_ok (Preferences.decode (Preferences.encode record)) in assert (Filter.definitions restored = definitions); From fb0d4e9ec360fb4b4672519ae11dfd233e880fc5 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 21:40:05 +0800 Subject: [PATCH 07/14] Supply coverage in bounded Timeline view fixtures --- test/application_view_test.ml | 1 + 1 file changed, 1 insertion(+) diff --git a/test/application_view_test.ml b/test/application_view_test.ml index 2faee02c..c5b0c204 100644 --- a/test/application_view_test.ml +++ b/test/application_view_test.ml @@ -7,6 +7,7 @@ let fixture_timeline_packet budget query ~items ~next = let module F = Read.For_worker in let receipt = F.timeline_receipt ~owner:(F.read_budget_owner budget) ~query ~version:"fixture" in + let receipt = F.with_timeline_coverage receipt "fixture" in F.timeline_packet ~receipt ~items:(Rrbvec.of_list items) ~next ;; From de2cfe60936a9748c4bff1eb562210717d982465 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 23:14:58 +0800 Subject: [PATCH 08/14] Clean invalid Timeline filter preferences and key rows by UTF-8 --- app/timeline_filter_preferences.ml | 5 +- swift/JournalChrome.swift | 7 +- swift/JournalTimelineFilterPreferences.swift | 107 ++++++++++++------ .../timeline_filter_preferences_codec_test.ml | 5 + test/timeline_filter_preferences_test.swift | 58 +++++++++- tool/test_swiftui_warm_start.py | 2 +- 6 files changed, 145 insertions(+), 39 deletions(-) diff --git a/app/timeline_filter_preferences.ml b/app/timeline_filter_preferences.ml index 6825389e..612354c5 100644 --- a/app/timeline_filter_preferences.ml +++ b/app/timeline_filter_preferences.ml @@ -4,12 +4,12 @@ let startup_prefix = "JTF1" let record_limit = 64 * 1024 let graph_limit = 64 let envelope_limit = graph_limit * ((6 * record_limit) + 64) + 64 -let unavailable = ["overflow", `String ""] +let unavailable = ["overflow", `Bool true] let unwrap_startup payload = if not (String.starts_with ~prefix:startup_prefix payload) then [], payload else match String.index_from_opt payload (String.length startup_prefix) '\n' with - | None -> [], payload + | None -> unavailable, payload | Some separator -> let offset = String.length startup_prefix in let length = separator - offset in @@ -82,6 +82,7 @@ let encode record = ;; let commit ~persist entries ~key record = + if entries = unavailable then None else let text = encode record in let expected = match List.assoc_opt key entries with Some (`String _ as value) -> value | _ -> `Null in let request = "journal.timeline-filter.commit\n" ^ key ^ "\n" diff --git a/swift/JournalChrome.swift b/swift/JournalChrome.swift index 1db72ef3..4c18cedb 100644 --- a/swift/JournalChrome.swift +++ b/swift/JournalChrome.swift @@ -363,8 +363,8 @@ struct JournalSheetDismissButton: SwiftUI.View { Button { action("open") } label: { icon }.buttonStyle(.plain) } else { Menu { - ForEach(names.indices, id: \.self) { index in - let name = names[index] + ForEach(names.map(JournalSavedFilterName.init)) { saved in + let name = saved.name Button { action("select:" + name) } label: { if activeName?.utf8.elementsEqual(name.utf8) == true { Label(name, systemImage: "checkmark") } else { Text(name) } @@ -571,7 +571,8 @@ struct JournalSheetDismissButton: SwiftUI.View { private func savedFilterManagement(_ names: [String]) -> some SwiftUI.View { DisclosureGroup("Manage saved filters", isExpanded: $managesSavedFilters) { - ForEach(names, id: \.self) { name in + ForEach(names.map(JournalSavedFilterName.init)) { saved in + let name = saved.name HStack { Text(verbatim: name) Spacer() diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index 003352aa..63341ae0 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -1,10 +1,15 @@ import Foundation -struct JournalTimelineFilterPreferences { +struct JournalSavedFilterName: Identifiable { + let name: String + var id: Data { Data(name.utf8) } +} + +@MainActor struct JournalTimelineFilterPreferences { let defaults: UserDefaults private static let keyPrefix = "journal.timeline-filter.graph." private static let commitPrefix = Data("journal.timeline-filter.commit\n".utf8) - private static let recordLimit = 64 * 1024 + private nonisolated static let recordLimit = 64 * 1024 private static let graphLimit = 64 private struct Record: Decodable { @@ -64,33 +69,58 @@ struct JournalTimelineFilterPreferences { return UUID(uuidString: String(graph))?.uuidString.lowercased() } - private static func storedRecord(for graph: String, keys: [String], in stored: [String: Any]) -> String? { - let canonicalKey = keyPrefix + graph - for key in [canonicalKey] + keys.filter({ $0 != canonicalKey }).sorted() { - if let value = stored[key] as? String, - let record = Record.decode(value), !record.definitions.isEmpty { return value } + private struct StoredRecord { + private struct Version: Decodable { let version: Int } + + let text: String + let hasDefinitions: Bool + + init?(_ value: Any) { + guard let text = value as? String, text.utf8.prefix(recordLimit + 1).count <= recordLimit else { return nil } + if let record = Record.decode(text) { + hasDefinitions = !record.definitions.isEmpty + } else if (try? JSONDecoder().decode(Version.self, from: Data(text.utf8)))?.version == 1 { + hasDefinitions = false + } else { + return nil + } + self.text = text } - return nil } - private static func admittedRecords(in stored: [String: Any]) -> (records: [String: String], overflow: Bool) { - let keysByGraph = Dictionary(grouping: stored.keys.compactMap { key in - graphID(forKey: key).map { (graph: $0, key: key) } - }, by: \.graph) - var records: [String: String] = [:] - for graph in keysByGraph.keys.sorted() { - guard let value = storedRecord(for: graph, keys: keysByGraph[graph, default: []].map(\.key), in: stored) - else { continue } - guard records.count < graphLimit else { return (records, true) } - records[graph] = value - } - return (records, false) + private struct Entry { + let key: String + let record: StoredRecord } var snapshot: [String: String] { - var (records, overflow) = Self.admittedRecords(in: defaults.dictionaryRepresentation()) - if overflow { records["overflow"] = "" } - return records + var records: [String: Entry] = [:] + for key in defaults.dictionaryRepresentation().keys { + guard let graph = Self.graphID(forKey: key), let value = defaults.object(forKey: key) else { continue } + guard let record = StoredRecord(value) else { + defaults.removeObject(forKey: key) + continue + } + if let existing = records[graph] { + if existing.record.hasDefinitions != record.hasDefinitions { + guard record.hasDefinitions else { continue } + } else { + guard key == Self.keyPrefix + graph || + (existing.key != Self.keyPrefix + graph && key < existing.key) else { continue } + } + } + records[graph] = Entry(key: key, record: record) + } + let graphs = records.keys.sorted { + let left = records[$0]!.record.hasDefinitions + let right = records[$1]!.record.hasDefinitions + return left == right ? $0 < $1 : left + } + var snapshot = Dictionary(uniqueKeysWithValues: graphs.prefix(Self.graphLimit).map { + ($0, records[$0]!.record.text) + }) + if graphs.count > Self.graphLimit { snapshot["overflow"] = "" } + return snapshot } func wrapStartup(_ payload: Data) -> Data { @@ -118,20 +148,33 @@ struct JournalTimelineFilterPreferences { let text = String(data: replacement, encoding: .utf8), let record = Record.decode(text) else { return false } let graph = id.uuidString.lowercased() - let key = Self.keyPrefix + graph let stored = defaults.dictionaryRepresentation() let keys = stored.keys.filter { Self.graphID(forKey: $0) == graph } - let current = Self.storedRecord(for: graph, keys: keys, in: stored) - guard current.map({ Data($0.utf8) }) == expected.map({ Data($0.utf8) }) else { return false } + guard keys.count <= 1 else { return false } + let key = keys.first ?? Self.keyPrefix + graph + let hasDefinitions: Bool + if let value = stored[key] { + guard let expected, let current = StoredRecord(value), current.text.utf8.elementsEqual(expected.utf8) + else { return false } + hasDefinitions = current.hasDefinitions + } else { + guard expected == nil else { return false } + hasDefinitions = false + } if record.definitions.isEmpty { - for key in keys { - defaults.removeObject(forKey: key) - } + if !keys.isEmpty { defaults.removeObject(forKey: key) } return true } - let (admitted, _) = Self.admittedRecords(in: stored) - guard admitted[graph] != nil || admitted.count < Self.graphLimit else { return false } + if !hasDefinitions { + var occupied: Set = [] + for (storedKey, value) in stored { + guard let storedGraph = Self.graphID(forKey: storedKey), !occupied.contains(storedGraph), + StoredRecord(value)?.hasDefinitions == true else { continue } + occupied.insert(storedGraph) + if occupied.count == Self.graphLimit { return false } + } + } defaults.set(text, forKey: key) - return defaults.string(forKey: key) == text + return true } } diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index a05e47b8..dcc76134 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -46,6 +46,11 @@ let () = let entries, decoded_config = Preferences.unwrap_startup (frame (String.make (25 * 1024 * 1024) ' ')) in assert (decoded_config = config && List.mem_assoc "overflow" entries); + let never_persist _ = failwith "An unreadable startup store must not authorize writes" in + assert (Preferences.commit ~persist:never_persist entries ~key record = None); + let entries, decoded_config = Preferences.unwrap_startup (frame "[]") in + assert (decoded_config = config && List.mem_assoc "overflow" entries); + assert (Preferences.commit ~persist:never_persist entries ~key record = None); assert (Filter.applied (Filter.restore restored) = criteria months); List.iter (fun (today, first) -> assert (Journal_filter_date.resolve_days (criteria months) ~today = Some (first, today))) diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index 85ba12d9..f2544c9c 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -30,9 +30,31 @@ import Foundation precondition(trySnapshot(reopened.wrapStartup(Data([0, 255]))) == [graphA: noSelection, graphB: custom]) defaults.set(String(repeating: "\\", count: 512 * 1024 + 1), forKey: "journal.timeline-filter.graph.\(graphA)") + let keyPrefix = "journal.timeline-filter.graph." + let keyA = keyPrefix + graphA + defaults.set("unrelated", forKey: "journal.other-preference") + precondition(!commit(graphA, preset), "An invalid record inserted after startup is not absence") + precondition(!commit(graphA, #"{"version":2,"definitions":[]}"#)) let bounded = reopened.wrapStartup(Data([0, 255])) precondition(bounded.count < 1024) - precondition(trySnapshot(bounded)[graphB] == custom) + precondition(trySnapshot(bounded) == [graphB: custom]) + precondition(defaults.object(forKey: keyA) == nil, "Startup must delete the oversized record") + precondition(defaults.string(forKey: "journal.other-preference") == "unrelated") + precondition(!commit(graphA, custom, expecting: noSelection), "Old snapshot must not resurrect a deleted record") + precondition(reopened.snapshot == [graphB: custom]) + let equivalentNames = #"{"version":2,"definitions":[{"name":"\u00e9","tags":[],"statuses":[],"time":"any"},{"name":"e\u0301","tags":[],"statuses":[],"time":"14-days"}],"selected":"e\u0301"}"# + let composed = JournalSavedFilterName(name: "\u{00e9}") + let decomposed = JournalSavedFilterName(name: "e\u{0301}") + precondition(composed.name == decomposed.name) + precondition(composed.id == Data([0xc3, 0xa9])) + precondition(decomposed.id == Data([0x65, 0xcc, 0x81])) + precondition(Set([composed.id, decomposed.id]).count == 2) + let remainingName = #"{"version":2,"definitions":[{"name":"e\u0301","tags":[],"statuses":[],"time":"14-days"}],"selected":"e\u0301"}"# + precondition(commit(graphA, equivalentNames)) + precondition(reopened.snapshot[graphA] == equivalentNames) + precondition(commit(graphA, remainingName, expecting: equivalentNames)) + precondition(reopened.snapshot[graphA] == remainingName) + precondition(commit(graphA, #"{"version":2,"definitions":[]}"#, expecting: remainingName)) func graph(_ index: Int) -> String { String(format: "10000000-0000-4000-8000-%012d", index) } @@ -43,6 +65,40 @@ import Foundation "not json"].enumerated() { defaults.set(legacy, forKey: "journal.timeline-filter.graph.\(graph(index + 3))") } + let nonStringKey = keyPrefix + graph(9) + defaults.set(["version": 2], forKey: nonStringKey) + let legacyKey = keyPrefix + graph(3) + let emptyKey = keyPrefix + graph(5) + let startupAfterCleanup = reopened.snapshot + precondition(defaults.string(forKey: legacyKey) == #"{"version":1}"#) + precondition(defaults.string(forKey: emptyKey) == #"{"version":2,"definitions":[],"selected":null}"#) + for index in [4, 6, 7, 8, 9] { + precondition(defaults.object(forKey: keyPrefix + graph(index)) == nil, "Invalid record \(index) survived startup") + } + precondition(!commit(graph(4), custom, expecting: #"{"version":3,"definitions":[]}"#)) + precondition(commit(graph(4), custom, expecting: startupAfterCleanup[graph(4)])) + precondition(commit(graph(4), #"{"version":2,"definitions":[]}"#, expecting: custom)) + defaults.set(custom, forKey: keyA) + precondition(!commit(graphA, preset, expecting: startupAfterCleanup[graphA])) + precondition(defaults.string(forKey: keyA) == custom) + precondition(commit(graphA, #"{"version":2,"definitions":[]}"#, expecting: custom)) + let aliasGraph = "a0000000-0000-4000-8000-000000000000" + let aliasKey = keyPrefix + aliasGraph.uppercased() + defaults.set(custom, forKey: aliasKey) + defaults.set("broken", forKey: keyPrefix + aliasGraph) + precondition(reopened.snapshot[aliasGraph] == custom) + precondition(defaults.object(forKey: keyPrefix + aliasGraph) == nil) + defaults.set(preset, forKey: keyPrefix + aliasGraph) + precondition(!commit(aliasGraph, #"{"version":2,"definitions":[]}"#, expecting: custom)) + precondition(defaults.string(forKey: aliasKey) == custom) + precondition(defaults.string(forKey: keyPrefix + aliasGraph) == preset) + defaults.removeObject(forKey: keyPrefix + aliasGraph) + precondition(commit(aliasGraph, #"{"version":2,"definitions":[]}"#, expecting: custom)) + precondition(reopened.snapshot[aliasGraph] == nil, "An alias must not reappear after deletion") + precondition(!commit(graph(3), preset), "An unobserved legacy value is not absence") + precondition(commit(graph(3), preset, expecting: startupAfterCleanup[graph(3)])) + precondition(commit(graph(3), #"{"version":2,"definitions":[]}"#, expecting: preset)) + precondition(commit(graph(5), #"{"version":2,"definitions":[]}"#, expecting: startupAfterCleanup[graph(5)])) var expected = [graphB: custom] for index in 10...72 { precondition(commit(graph(index), preset)) diff --git a/tool/test_swiftui_warm_start.py b/tool/test_swiftui_warm_start.py index c2dc623d..e777d735 100644 --- a/tool/test_swiftui_warm_start.py +++ b/tool/test_swiftui_warm_start.py @@ -99,7 +99,7 @@ def run(command, cwd=host): sources = [root/'swift'/name for name in ['JournalE2EECrypto.swift', 'JournalPlatformWire.swift', 'JournalPlatformServices.swift', - 'JournalStartupConfiguration.swift', 'JournalChrome.swift']] + 'JournalStartupConfiguration.swift', 'JournalTimelineFilterPreferences.swift', 'JournalChrome.swift']] source = root/'apple-tests/warm-start/JournalWarmStartAcceptance.swift' for tracked in sources + [source]: record['inputs'][str(tracked.relative_to(root))] = hashlib.sha256(tracked.read_bytes()).hexdigest() From decad6c9f4fc3d1424a050e3c4814ccb4b998a7c Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 23:29:21 +0800 Subject: [PATCH 09/14] Reject invalid persisted Timeline filter numbers and dates --- swift/JournalTimelineFilterPreferences.swift | 118 ++++++++++++++---- .../timeline_filter_preferences_codec_test.ml | 10 ++ test/timeline_filter_preferences_test.swift | 27 ++++ 3 files changed, 132 insertions(+), 23 deletions(-) diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index 63341ae0..dcecbca1 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -12,11 +12,61 @@ struct JournalSavedFilterName: Identifiable { private nonisolated static let recordLimit = 64 * 1024 private static let graphLimit = 64 + private struct LocalDay { + let year: Int + let month: Int + let dayOfYear: Int + + static func sample() -> Self? { + var now = time(nil) + var local = tm() + guard localtime_r(&now, &local) != nil else { return nil } + let year = Int(local.tm_year) + 1900 + guard year >= 1 else { return nil } + return Self(year: year, month: Int(local.tm_mon) + 1, dayOfYear: Int(local.tm_yday) + 1) + } + + var daysSinceYearOne: Int { + let precedingYears = year - 1 + return 365 * precedingYears + precedingYears / 4 - precedingYears / 100 + + precedingYears / 400 + dayOfYear - 1 + } + } + + private enum Lookback { + case days(Int), threeMonths + + func fits(_ today: LocalDay) -> Bool { + switch self { + case .days(let count): return count - 1 <= today.daysSinceYearOne + case .threeMonths: return today.year > 1 || today.month >= 4 + } + } + } + private struct Record: Decodable { + private static let stringOrFloat = try! NSRegularExpression( + pattern: #""(?:[^"\\]++|\\.)*+"|(?<=[\[,: \t\r\n])-?(?:0|[1-9][0-9]*)(?:\.[0-9]+(?:[eE][+-]?[0-9]+)?|[eE][+-]?[0-9]+)(?=[\],} \t\r\n])"#) + + private static func decodingData(_ text: String) -> Data { + let source = text as NSString + let range = NSRange(location: 0, length: source.length) + var start = 0 + var result = "" + for match in stringOrFloat.matches(in: text, range: range) { + guard source.character(at: match.range.location) != 34 else { continue } + result += source.substring(with: NSRange(location: start, length: match.range.location - start)) + result += "false" + start = NSMaxRange(match.range) + } + result += source.substring(from: start) + return Data(result.utf8) + } struct Definition: Decodable { let name: String let tags: [UUID] let statuses: [UUID] + let lookback: Lookback private enum CodingKeys: String, CodingKey { case name, tags, statuses, time } @@ -25,8 +75,13 @@ struct JournalSavedFilterName: Identifiable { name = try fields.decode(String.self, forKey: .name) tags = try fields.decode([UUID].self, forKey: .tags) statuses = try fields.decode([UUID].self, forKey: .statuses) - if let preset = try? fields.decode(String.self, forKey: .time), - ["any", "14-days", "3-months"].contains(preset) { return } + if let preset = try? fields.decode(String.self, forKey: .time) { + switch preset { + case "14-days": lookback = .days(14); return + case "any", "3-months": lookback = .threeMonths; return + default: break + } + } var time = try fields.nestedUnkeyedContainer(forKey: .time) let count = try time.decode(Int.self) let unit = try time.decode(String.self) @@ -35,6 +90,7 @@ struct JournalSavedFilterName: Identifiable { (unit == "days" && count <= ocamlMaxInt || unit == "weeks" && count <= ocamlMaxInt / 7) else { throw DecodingError.dataCorruptedError(forKey: .time, in: fields, debugDescription: "Invalid relative time") } + lookback = .days(unit == "weeks" ? 7 * count : count) } var trimmedName: Data { @@ -46,18 +102,40 @@ struct JournalSavedFilterName: Identifiable { let definitions: [Definition] let selected: String? - static func decode(_ text: String) -> Self? { + private enum CodingKeys: String, CodingKey { case version, definitions, selected } + + init(from decoder: Decoder) throws { + let fields = try decoder.container(keyedBy: CodingKeys.self) + version = try fields.decode(Int.self, forKey: .version) + if version == 1 { + definitions = [] + selected = nil + } else { + definitions = try fields.decode([Definition].self, forKey: .definitions) + selected = try fields.decodeIfPresent(String.self, forKey: .selected) + } + } + + static func decode(_ text: String, today: LocalDay?) -> Self? { guard text.utf8.prefix(JournalTimelineFilterPreferences.recordLimit + 1).count <= JournalTimelineFilterPreferences.recordLimit, - let record = try? JSONDecoder().decode(Self.self, from: Data(text.utf8)), - record.version == 2, record.definitions.count <= 5 else { return nil } - var names: Set = [] + let record = try? JSONDecoder().decode(Self.self, from: decodingData(text)), + record.version == 1 || record.version == 2, record.definitions.count <= 5 else { return nil } + var lookbacks: [Data: Lookback] = [:] for definition in record.definitions { let name = definition.trimmedName - guard (1...128).contains(name.count), names.insert(name).inserted, + guard (1...128).contains(name.count), lookbacks[name] == nil, definition.tags.count <= 100, definition.statuses.count <= 100 else { return nil } + lookbacks[name] = definition.lookback } - if let selected = record.selected, !names.contains(Data(selected.utf8)) { return nil } + let applied: Lookback + if let selected = record.selected { + guard let lookback = lookbacks[Data(selected.utf8)] else { return nil } + applied = lookback + } else { + applied = .threeMonths + } + guard today.map(applied.fits) ?? true else { return nil } return record } } @@ -70,20 +148,12 @@ struct JournalSavedFilterName: Identifiable { } private struct StoredRecord { - private struct Version: Decodable { let version: Int } - let text: String let hasDefinitions: Bool - init?(_ value: Any) { - guard let text = value as? String, text.utf8.prefix(recordLimit + 1).count <= recordLimit else { return nil } - if let record = Record.decode(text) { - hasDefinitions = !record.definitions.isEmpty - } else if (try? JSONDecoder().decode(Version.self, from: Data(text.utf8)))?.version == 1 { - hasDefinitions = false - } else { - return nil - } + init?(_ value: Any, today: LocalDay?) { + guard let text = value as? String, let record = Record.decode(text, today: today) else { return nil } + hasDefinitions = !record.definitions.isEmpty self.text = text } } @@ -94,10 +164,11 @@ struct JournalSavedFilterName: Identifiable { } var snapshot: [String: String] { + let today = LocalDay.sample() var records: [String: Entry] = [:] for key in defaults.dictionaryRepresentation().keys { guard let graph = Self.graphID(forKey: key), let value = defaults.object(forKey: key) else { continue } - guard let record = StoredRecord(value) else { + guard let record = StoredRecord(value, today: today) else { defaults.removeObject(forKey: key) continue } @@ -144,9 +215,10 @@ struct JournalSavedFilterName: Identifiable { return false } let replacement = mutation.suffix(from: expectedEnd + 1) + let today = LocalDay.sample() guard replacement.count <= Self.recordLimit, let text = String(data: replacement, encoding: .utf8), - let record = Record.decode(text) else { return false } + let record = Record.decode(text, today: today), record.version == 2 else { return false } let graph = id.uuidString.lowercased() let stored = defaults.dictionaryRepresentation() let keys = stored.keys.filter { Self.graphID(forKey: $0) == graph } @@ -154,7 +226,7 @@ struct JournalSavedFilterName: Identifiable { let key = keys.first ?? Self.keyPrefix + graph let hasDefinitions: Bool if let value = stored[key] { - guard let expected, let current = StoredRecord(value), current.text.utf8.elementsEqual(expected.utf8) + guard let expected, let current = StoredRecord(value, today: today), current.text.utf8.elementsEqual(expected.utf8) else { return false } hasDefinitions = current.hasDefinitions } else { @@ -169,7 +241,7 @@ struct JournalSavedFilterName: Identifiable { var occupied: Set = [] for (storedKey, value) in stored { guard let storedGraph = Self.graphID(forKey: storedKey), !occupied.contains(storedGraph), - StoredRecord(value)?.hasDefinitions == true else { continue } + StoredRecord(value, today: today)?.hasDefinitions == true else { continue } occupied.insert(storedGraph) if occupied.count == Self.graphLimit { return false } } diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index dcc76134..0ffc2512 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -57,8 +57,18 @@ let () = [20240531, 20240229; 20230531, 20230228; 20250115, 20241015; 20241231, 20240930]; assert (Preferences.decode {|{"version":1,"tags":[],"statuses":[],"time":"past-7-days"}|} = Ok Filter.empty_preferences); + let persisted = {|{"version":2,"definitions":[{"name":"First week","tags":[],"statuses":[],"time":[1,"weeks"]}],"selected":"First week"}|} in + let applied = Filter.applied (Filter.restore (Result.get_ok (Preferences.decode persisted))) in + assert (Journal_filter_date.resolve_days applied ~today:10107 = Some (10101, 10107)); + (match Journal_filter_date.resolve_days applied ~today:10106 with + | exception Invalid_argument _ -> () + | _ -> assert false); List.iter (fun value -> assert (Result.is_error (Preferences.decode value))) [ "broken"; String.make (64 * 1024 + 1) ' ' + ; {|{"version":2.0,"definitions":[],"selected":null}|} + ; {|{"version":1e0}|} + ; {|{"version":2,"definitions":[{"name":"Float","tags":[],"statuses":[],"time":[7.0,"days"]}],"selected":null}|} + ; {|{"version":2,"definitions":[{"name":"Float","tags":[],"statuses":[],"time":[7e0,"weeks"]}],"selected":"Float"}|} ; {|{"version":2,"definitions":[],"selected":"unknown"}|} ; {|{"version":2,"definitions":[{"name":"X","tags":["not-a-uuid"],"statuses":[],"time":"any"}],"selected":null}|} ; {|{"version":2,"definitions":[{"name":"X","tags":[],"statuses":[],"time":[0,"weeks"]}],"selected":null}|} ] diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index f2544c9c..b541077e 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -99,6 +99,33 @@ import Foundation precondition(commit(graph(3), preset, expecting: startupAfterCleanup[graph(3)])) precondition(commit(graph(3), #"{"version":2,"definitions":[]}"#, expecting: preset)) precondition(commit(graph(5), #"{"version":2,"definitions":[]}"#, expecting: startupAfterCleanup[graph(5)])) + let invalidRecords = [ + #"{"version":2.0,"definitions":[],"selected":null}"#, + #"{"version":1e0}"#, + #"{"version":2,"definitions":[{"name":"Float","tags":[],"statuses":[],"time":[7.0,"days"]}],"selected":null}"#, + #"{"version":2,"definitions":[{"name":"Float","tags":[],"statuses":[],"time":[7e0,"weeks"]}],"selected":"Float"}"#, + #"{"version":2,"definitions":[{"name":"Too far","tags":[],"statuses":[],"time":[1000000,"weeks"]}],"selected":"Too far"}"#, + ] + let validRecords = [ + #"{"version":1,"ignored":2.0}"#, + #"{"version":2,"definitions":[{"name":"7.0 days","tags":[],"statuses":[],"time":[7,"days"],"ignored":2.0}],"selected":"7.0 days"}"#, + #"{"version":2,"definitions":[{"name":"Too far","tags":[],"statuses":[],"time":[1000000,"weeks"]}],"selected":null}"#, + ] + for (index, text) in (invalidRecords + validRecords).enumerated() { + defaults.set(text, forKey: keyPrefix + graph(index + 100)) + } + let cleaned = trySnapshot(reopened.wrapStartup(Data([0, 255]))) + for (index, text) in invalidRecords.enumerated() { + let id = graph(index + 100) + precondition(cleaned[id] == nil && defaults.object(forKey: keyPrefix + id) == nil, + "Invalid persisted record survived startup: \(text)") + precondition(!commit(id, text), "Commit accepted an invalid replacement: \(text)") + } + for (index, text) in validRecords.enumerated() { + let id = graph(index + 100 + invalidRecords.count) + precondition(cleaned[id] == text && defaults.string(forKey: keyPrefix + id) == text) + defaults.removeObject(forKey: keyPrefix + id) + } var expected = [graphB: custom] for index in 10...72 { precondition(commit(graph(index), preset)) From 0514693123fb422dfebe88e574b7230e0782aa9e Mon Sep 17 00:00:00 2001 From: rcmerci Date: Wed, 25 Nov 2026 23:38:31 +0800 Subject: [PATCH 10/14] Reject malformed Timeline filter JSON and guard date underflow --- app/journal_filter_date.ml | 6 +- swift/JournalTimelineFilterPreferences.swift | 122 +++++++++++++++--- test/timeline_filter_json_cases.tsv | 17 +++ .../timeline_filter_preferences_codec_test.ml | 13 ++ test/timeline_filter_preferences_test.swift | 10 +- 5 files changed, 147 insertions(+), 21 deletions(-) create mode 100644 test/timeline_filter_json_cases.tsv diff --git a/app/journal_filter_date.ml b/app/journal_filter_date.ml index f31189a2..869e9901 100644 --- a/app/journal_filter_date.ml +++ b/app/journal_filter_date.ml @@ -21,8 +21,10 @@ let resolve_days criteria ~today = era * 146097 + year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + (153 * month + 2) / 5 + day mod 100 - 1 - 719468 in - let earliest = civil today - (count - 1) in - if earliest < civil 10101 then invalid_arg "Filter range starts before year 1"; + let last = civil today in + let offset = count - 1 in + if offset > last - civil 10101 then invalid_arg "Filter range starts before year 1"; + let earliest = last - offset in let start = Unix.gmtime (float_of_int earliest *. 86400.) in Some ((start.tm_year + 1900) * 10000 + (start.tm_mon + 1) * 100 + start.tm_mday, today) in diff --git a/swift/JournalTimelineFilterPreferences.swift b/swift/JournalTimelineFilterPreferences.swift index dcecbca1..21cdc24b 100644 --- a/swift/JournalTimelineFilterPreferences.swift +++ b/swift/JournalTimelineFilterPreferences.swift @@ -45,22 +45,108 @@ struct JournalSavedFilterName: Identifiable { } private struct Record: Decodable { - private static let stringOrFloat = try! NSRegularExpression( - pattern: #""(?:[^"\\]++|\\.)*+"|(?<=[\[,: \t\r\n])-?(?:0|[1-9][0-9]*)(?:\.[0-9]+(?:[eE][+-]?[0-9]+)?|[eE][+-]?[0-9]+)(?=[\],} \t\r\n])"#) - - private static func decodingData(_ text: String) -> Data { - let source = text as NSString - let range = NSRange(location: 0, length: source.length) - var start = 0 - var result = "" - for match in stringOrFloat.matches(in: text, range: range) { - guard source.character(at: match.range.location) != 34 else { continue } - result += source.substring(with: NSRange(location: start, length: match.range.location - start)) - result += "false" - start = NSMaxRange(match.range) - } - result += source.substring(from: start) - return Data(result.utf8) + private static func decodingData(_ text: String) -> Data? { + let bytes = Array(text.utf8) + var index = 0 + var copied = 0 + var result = Data() + + func peek() -> UInt8? { index < bytes.count ? bytes[index] : nil } + func take(_ byte: UInt8) -> Bool { + guard peek() == byte else { return false } + index += 1 + return true + } + func whitespace() { + while let byte = peek(), byte == 32 || byte == 9 || byte == 10 || byte == 13 { index += 1 } + } + func string() -> Bool { + guard take(34) else { return false } + while let byte = peek(), byte >= 32 { + index += 1 + if byte == 34 { return true } + if byte == 92 { + guard let escape = peek() else { return false } + index += 1 + switch escape { + case 34, 47, 92, 98, 102, 110, 114, 116: break + case 117: + for _ in 0..<4 { + guard let hex = peek(), (48...57).contains(hex) || (65...70).contains(hex) + || (97...102).contains(hex) else { return false } + index += 1 + } + default: return false + } + } + } + return false + } + func digits() -> Bool { + let start = index + while let byte = peek(), (48...57).contains(byte) { index += 1 } + return index > start + } + func number() -> Bool { + let start = index + _ = take(45) + guard take(48) || digits() else { return false } + var isFloat = false + if take(46) { + guard digits() else { return false } + isFloat = true + } + if take(101) || take(69) { + _ = take(43) || take(45) + guard digits() else { return false } + isFloat = true + } + if isFloat { + result.append(contentsOf: bytes[copied.. Bool { + for byte in token.utf8 where !take(byte) { return false } + return true + } + func value(depth: Int) -> Bool { + whitespace() + switch peek() { + case 123, 91: + guard depth < 512 else { return false } + let object = take(123) + if !object { index += 1 } + let end: UInt8 = object ? 125 : 93 + whitespace() + if take(end) { return true } + repeat { + whitespace() + if object { + guard string() else { return false } + whitespace() + guard take(58) else { return false } + } + guard value(depth: depth + 1) else { return false } + whitespace() + } while take(44) + return take(end) + case 34: return string() + case 116: return literal("true") + case 102: return literal("false") + case 110: return literal("null") + default: return number() + } + } + + whitespace() + guard peek() == 123, value(depth: 0) else { return nil } + whitespace() + guard index == bytes.count else { return nil } + result.append(contentsOf: bytes[copied...]) + return result } struct Definition: Decodable { let name: String @@ -119,7 +205,8 @@ struct JournalSavedFilterName: Identifiable { static func decode(_ text: String, today: LocalDay?) -> Self? { guard text.utf8.prefix(JournalTimelineFilterPreferences.recordLimit + 1).count <= JournalTimelineFilterPreferences.recordLimit, - let record = try? JSONDecoder().decode(Self.self, from: decodingData(text)), + let data = decodingData(text), + let record = try? JSONDecoder().decode(Self.self, from: data), record.version == 1 || record.version == 2, record.definitions.count <= 5 else { return nil } var lookbacks: [Data: Lookback] = [:] for definition in record.definitions { @@ -217,6 +304,7 @@ struct JournalSavedFilterName: Identifiable { let replacement = mutation.suffix(from: expectedEnd + 1) let today = LocalDay.sample() guard replacement.count <= Self.recordLimit, + !replacement.starts(with: [0xEF, 0xBB, 0xBF]), let text = String(data: replacement, encoding: .utf8), let record = Record.decode(text, today: today), record.version == 2 else { return false } let graph = id.uuidString.lowercased() diff --git a/test/timeline_filter_json_cases.tsv b/test/timeline_filter_json_cases.tsv new file mode 100644 index 00000000..07104d15 --- /dev/null +++ b/test/timeline_filter_json_cases.tsv @@ -0,0 +1,17 @@ +ok {"version":1,"ignored":{"array":[true,false,null,-0,2.5E+10,"escaped \" quote",{}]}} +ok {"version":2,"definitions":[{"name":"Float 7.0, \\ and \u0041","tags":[],"statuses":[],"time":[7,"days"]}],"selected":null} +bad {"version":2,"definitions":[],"selected":null} +bad {"version":2,"definitions":[],"selected":null,} +bad {"version":2,"definitions":[{"name":"X","tags":[],"statuses":[],"time":[7,"days",]}],"selected":null} +bad {"version":2,"definitions":[],"ignored":{"nested":1,}} +bad {"version":2,"definitions":[],"ignored":[true,]} +bad {"version":2,"definitions":[],"ignored":[1 2]} +bad {"version":2,"definitions":[],"ignored":01} +bad {"version":2,"definitions":[],"ignored":1.} +bad {"version":2,"definitions":[],"ignored":1e+} +bad {"version":2,"definitions":[],"ignored":"\q"} +bad {"version":2,"definitions":[],"ignored":"\u12 +bad {"version":2,"definitions":[],"ignored":"unterminated\ +bad {"version":2,"definitions":[],"ignored":[true +bad {"version":2,"definitions":[],"ignored":fal +bad {"version":2,"definitions":[] } {} diff --git a/test/timeline_filter_preferences_codec_test.ml b/test/timeline_filter_preferences_codec_test.ml index 0ffc2512..e2760748 100644 --- a/test/timeline_filter_preferences_codec_test.ml +++ b/test/timeline_filter_preferences_codec_test.ml @@ -57,6 +57,19 @@ let () = [20240531, 20240229; 20230531, 20230228; 20250115, 20241015; 20241231, 20240930]; assert (Preferences.decode {|{"version":1,"tags":[],"statuses":[],"time":"past-7-days"}|} = Ok Filter.empty_preferences); + let root = Option.value (Sys.getenv_opt "DUNE_SOURCEROOT") ~default:"." in + let corpus = Filename.concat root "test/timeline_filter_json_cases.tsv" in + In_channel.with_open_bin corpus (fun channel -> + In_channel.fold_lines (fun () line -> + match String.split_on_char '\t' line with + | [expected; text] when expected = "ok" || expected = "bad" -> + if Result.is_ok (Preferences.decode text) <> (expected = "ok") then + failwith ("Unexpected OCaml codec verdict: " ^ text) + | _ -> failwith ("Malformed test fixture: " ^ line)) () channel); + let max_days = Result.get_ok (Filter.custom ~count:max_int ~unit_:Days) in + (match Journal_filter_date.resolve_days (criteria max_days) ~today:10101 with + | exception Invalid_argument message -> assert (message = "Filter range starts before year 1") + | _ -> assert false); let persisted = {|{"version":2,"definitions":[{"name":"First week","tags":[],"statuses":[],"time":[1,"weeks"]}],"selected":"First week"}|} in let applied = Filter.applied (Filter.restore (Result.get_ok (Preferences.decode persisted))) in assert (Journal_filter_date.resolve_days applied ~today:10107 = Some (10101, 10107)); diff --git a/test/timeline_filter_preferences_test.swift b/test/timeline_filter_preferences_test.swift index b541077e..76f6726d 100644 --- a/test/timeline_filter_preferences_test.swift +++ b/test/timeline_filter_preferences_test.swift @@ -99,14 +99,20 @@ import Foundation precondition(commit(graph(3), preset, expecting: startupAfterCleanup[graph(3)])) precondition(commit(graph(3), #"{"version":2,"definitions":[]}"#, expecting: preset)) precondition(commit(graph(5), #"{"version":2,"definitions":[]}"#, expecting: startupAfterCleanup[graph(5)])) - let invalidRecords = [ + let corpus = try String(contentsOfFile: "test/timeline_filter_json_cases.tsv", encoding: .utf8) + let cases = corpus.split(separator: "\n").map { line in + let fields = line.split(separator: "\t", maxSplits: 1) + precondition(fields.count == 2 && (fields[0] == "ok" || fields[0] == "bad")) + return (accepted: fields[0] == "ok", text: String(fields[1])) + } + let invalidRecords = cases.filter { !$0.accepted }.map(\.text) + [ #"{"version":2.0,"definitions":[],"selected":null}"#, #"{"version":1e0}"#, #"{"version":2,"definitions":[{"name":"Float","tags":[],"statuses":[],"time":[7.0,"days"]}],"selected":null}"#, #"{"version":2,"definitions":[{"name":"Float","tags":[],"statuses":[],"time":[7e0,"weeks"]}],"selected":"Float"}"#, #"{"version":2,"definitions":[{"name":"Too far","tags":[],"statuses":[],"time":[1000000,"weeks"]}],"selected":"Too far"}"#, ] - let validRecords = [ + let validRecords = cases.filter(\.accepted).map(\.text) + [ #"{"version":1,"ignored":2.0}"#, #"{"version":2,"definitions":[{"name":"7.0 days","tags":[],"statuses":[],"time":[7,"days"],"ignored":2.0}],"selected":"7.0 days"}"#, #"{"version":2,"definitions":[{"name":"Too far","tags":[],"statuses":[],"time":[1000000,"weeks"]}],"selected":null}"#, From 7b203d51e113fb6ab78441f582ae9cc36b3ad95f Mon Sep 17 00:00:00 2001 From: rcmerci Date: Thu, 26 Nov 2026 19:03:40 +0800 Subject: [PATCH 11/14] Preserve journal feed depth and bound per-parent reads --- .../worker_pure_coordinator.ml | 1 + app/journal_graph_feed_plan.ml | 85 +++--- app/journal_graph_runtime.ml | 2 + .../lib/effect_runner/effect_runner.ml | 78 ++++-- logseq_db_worker/test/test_effect_runner.ml | 81 +++++- .../typed_read/worker_pure_read.ml | 42 ++- .../typed_read/worker_pure_read.mli | 20 +- logseq_overlay_db/lib/database.ml | 247 ++++++++++++++---- logseq_overlay_db/spec/database.mli | 25 +- logseq_overlay_db/test/test_overlay_reads.ml | 133 +++++++++- logseq_overlay_db/test/test_overlay_sync.ml | 39 ++- test/application_view_test.ml | 2 +- test/journal_graph_runtime_locality_test.ml | 52 ++-- ..._db_worker_application_integration_test.ml | 2 +- 14 files changed, 678 insertions(+), 131 deletions(-) diff --git a/app/impl/worker_coordination/worker_pure_coordinator.ml b/app/impl/worker_coordination/worker_pure_coordinator.ml index 8cb32a8f..812b8b90 100644 --- a/app/impl/worker_coordination/worker_pure_coordinator.ml +++ b/app/impl/worker_coordination/worker_pure_coordinator.ml @@ -55,6 +55,7 @@ type _ kind = let kind : type a. a Worker.query -> a kind = function | Timeline_read{query=Worker.Timeline.Dates _;_}->Timeline_dates | Timeline_read{query=Worker.Timeline.Roots _;_}->Timeline_roots + | Timeline_read{query=Worker.Timeline.Roots_through_grandchildren _;_}->Timeline_roots | Timeline_read{query=Worker.Timeline.Preview_children _;_}->Timeline_preview | Timeline_check _->Timeline_check | Graph_info -> Info diff --git a/app/journal_graph_feed_plan.ml b/app/journal_graph_feed_plan.ml index 85c0e471..58506d2d 100644 --- a/app/journal_graph_feed_plan.ml +++ b/app/journal_graph_feed_plan.ml @@ -262,14 +262,15 @@ let make_root_batch t ~ports owner ~page_uuid (page : Projection.page) cursor li } ;; -let plan_root_batch ~ports batch = +let plan_root_batch t ~ports batch = let limit = batch.root_limit in let request = ports.plan_read (Root_tree batch) ~maximum_items:limit (Worker.Timeline_read - { query = Paging.roots ~page:(batch.root_page_uuid) + { query = (if t.tags = [] && t.statuses = [] then Paging.roots ~page:batch.root_page_uuid + else Paging.roots_through_grandchildren ~page:batch.root_page_uuid ~tags:t.tags ~statuses:t.statuses) ; after = batch.root_cursor }) in (match batch.root_owner with @@ -292,7 +293,7 @@ let plan_root_batch ~ports batch = let read_root_batch t ~ports owner (page:Projection.page) cursor limit = match Graph.Uuid.of_string page.id with | Error message -> Error message - | Ok page_uuid -> Ok (make_root_batch t ~ports owner ~page_uuid page cursor limit |> plan_root_batch ~ports) + | Ok page_uuid -> Ok (make_root_batch t ~ports owner ~page_uuid page cursor limit |> plan_root_batch t ~ports) ;; let continue_root_batch t ~ports owner page cursor limit = @@ -398,7 +399,12 @@ let read_changed_roots t ~ports page limit = (min limit target) ;; -let read_root_dates ~ports scan = +let dates_coverage_scope t = + if t.tags = [] && t.statuses = [] then Paging.Root_membership + else Paging.Root_and_descendant_membership +;; + +let read_root_dates t ~ports scan = match Worker.journal_day scan.root_from_day, Worker.journal_day (min 99991231 scan.root_journal_through) with | Error error, _ | _, Error error -> scan_failure scan (Paging.error_message (Paging.Read_failed error)) @@ -409,7 +415,7 @@ let read_root_dates ~ports scan = (Root_dates (scan, params)) ~maximum_items:params.limit (Worker.Timeline_read - { query = Paging.dates ~from_day:params.from_day ~through_day:params.through_day + { query = Paging.dates ~coverage_scope:(dates_coverage_scope t) ~from_day:params.from_day ~through_day:params.through_day ; after = params.after }) in ports.report @@ -435,7 +441,7 @@ let root_date_continuation scan = ;; (* The first metadata packet usually covers Today. Probe its exact range only when every discovered date is future and the catalog has more packets. *) -let read_priority_today ~ports scan = +let read_priority_today t ~ports scan = match scan.root_skipped_day with | None -> scan_failure scan "The priority date is unavailable." | Some today -> match Worker.journal_day today with @@ -447,7 +453,7 @@ let read_priority_today ~ports scan = (Root_today (scan, params)) ~maximum_items:params.limit (Worker.Timeline_read - { query = Paging.dates ~from_day:params.from_day ~through_day:params.through_day + { query = Paging.dates ~coverage_scope:(dates_coverage_scope t) ~from_day:params.from_day ~through_day:params.through_day ; after = params.after }) in ports.report @@ -545,7 +551,7 @@ let rec next_feed_batch ?(verified=false) t ~ports scan = | None when scan.root_journal_through < scan.root_from_day -> scan.root_journals_done <- true; if not (has_retained t) then responses [root_feed_response ~ports scan true] else check t ~ports (Publish_feed scan) - | None -> read_root_dates ~ports scan) + | None -> read_root_dates t ~ports scan) ;; let complete_verified_batch t ~ports batch = @@ -711,13 +717,16 @@ let complete_verified_batch t ~ports batch = else next))) ;; -let read_root_preview ~ports preview = +let read_root_preview t ~ports preview = + let parent = preview.preview_root.block.uuid in + let query = if t.tags = [] && t.statuses = [] then Paging.preview_children ~parent + else Paging.filtered_preview_children ~parent in let request = ports.plan_read (Root_preview preview) ~maximum_items:preview.preview_limit (Worker.Timeline_read - { query = Paging.preview_children ~parent:preview.preview_root.block.uuid + { query ; after = preview.preview_cursor }) in (match preview.preview_batch.root_owner with @@ -751,7 +760,7 @@ let next_root_preview t ~ports batch = ; preview_limit = 3 } in - requests [ read_root_preview ~ports preview ]) + requests [ read_root_preview t ~ports preview ]) ;; let start_feed_scan t ~ports ~cursor ~root_limit ~day_limit ~request_generation ?(reuse=false) ?after () = @@ -784,8 +793,12 @@ let start_feed_scan t ~ports ~cursor ~root_limit ~day_limit ~request_generation t.window_epoch <- Int64.succ t.window_epoch; (* A replacement catalog traversal owns its own date scopes. Root and preview receipts still belong to every retained page. *) + let appended_coverage = + if Option.is_some cursor || Option.exists (fun (_, cursor) -> Option.is_some cursor) after + then Hashtbl.find_opt t.retained Coverage_scope else None in Hashtbl.filter_map_inplace (fun scope proof -> match scope with - | Dates_scope _ | Coverage_scope -> None | _ -> Some proof) t.retained; + | Coverage_scope -> appended_coverage + | Dates_scope _ -> None | _ -> Some proof) t.retained; if cursor = None && after = None then t.initial_feed_spec <- Some (root_limit, day_limit); let scan = @@ -878,14 +891,8 @@ let receive_root_tree t ~ports batch (packet : Worker_pure_data.tree_member Pagi then root_failure batch "The root cursor did not advance." else ( Hashtbl.replace batch.root_proofs (Roots_scope batch.root_page.id) (Paging.Receipt packet.receipt); - let matches (m : Worker_pure_data.tree_member) = - (t.tags = [] && t.statuses = []) - || List.exists (fun tag -> List.exists (Graph.Uuid.equal tag) t.tags) m.value.block.tags - || Option.exists (fun status -> List.exists (Graph.Uuid.equal status) t.statuses) m.value.task_status - in - let members = Rrbvec.filter_map (fun (m : Worker_pure_data.tree_member) -> - if matches m then Some Projection.{block=m.value.block;revision=m.revision;depth=0} - else None) items in + let members = Rrbvec.map (fun (m : Worker_pure_data.tree_member) -> + Projection.{block=m.value.block;revision=m.revision;depth=0}) items in match (ports.context ()).time_context with | Error message -> root_failure batch message | Ok time_context -> @@ -977,7 +984,7 @@ let receive_root_preview t ~ports preview (packet : Worker_pure_data.child_membe then root_failure batch "The child cursor did not advance." else requests - [ read_root_preview ~ports + [ read_root_preview t ~ports { preview with preview_members = selected ; preview_cursor = next_cursor @@ -1042,7 +1049,7 @@ let restart_dates t ~ports scan = scan.root_journal_boundary <- None; Hashtbl.clear scan.root_journal_boundary_pages; scan.root_journals_done <- false; - read_root_dates ~ports scan) + read_root_dates t ~ports scan) ;; let with_coverage t ~ports scan receipt accept = @@ -1050,10 +1057,19 @@ let with_coverage t ~ports scan receipt accept = match Paging.coverage receipt with | None -> scan_failure scan "Filtered Timeline read returned no coverage witness." | Some proof -> - match Hashtbl.find_opt scan.root_proofs Coverage_scope with - | None -> Hashtbl.replace scan.root_proofs Coverage_scope proof; accept () - | Some old -> - if Paging.equal_coverage proof old then accept () else restart_dates t ~ports scan + let previous = match Hashtbl.find_opt scan.root_proofs Coverage_scope with + | Some _ as previous -> previous + | None -> Hashtbl.find_opt t.retained Coverage_scope in + match previous with + | Some old when not (Paging.equal_coverage proof old) -> + if scan.root_continued then stale_continuation scan + else if Option.is_some scan.root_source_cursor then + let output = start_feed_scan t ~ports ~cursor:None + ~root_limit:scan.root_requested_root_limit ~day_limit:scan.root_requested_day_limit + ~request_generation:scan.root_generation () in + {output with publications=Rrbvec.push_front output.publications (Refresh_started scan.root_generation)} + else restart_dates t ~ports scan + | _ -> Hashtbl.replace scan.root_proofs Coverage_scope proof; accept () ;; let operation_failure operation message = match operation with @@ -1199,7 +1215,7 @@ let receive : type a. ?session:Worker.session -> t -> ports:ports let handles = match operation, query with | Check _, Worker.Timeline_check _ -> true | (Root_dates _ | Root_today _), Worker.Timeline_read {query=Paging.Dates _;_} -> true - | Root_tree _, Worker.Timeline_read {query=Paging.Roots _;_} -> true + | Root_tree _, Worker.Timeline_read {query=(Paging.Roots _ | Paging.Roots_through_grandchildren _);_} -> true | Root_preview _, Worker.Timeline_read {query=Paging.Preview_children _;_} -> true | _ -> false in if not handles then None else if not (is_current t operation) then Some empty else @@ -1282,7 +1298,7 @@ let receive : type a. ?session:Worker.session -> t -> ports:ports ~none:false ~some:(fun day -> p.day > day) scan.root_skipped_day) - pages -> read_priority_today ~ports scan + pages -> read_priority_today t ~ports scan | None -> next_feed_batch t ~ports scan) else next_feed_batch t ~ports scan)) | Root_today (scan, params), Worker.Timeline_read {query=Paging.Dates _;_}, Ok packet -> @@ -1306,6 +1322,13 @@ let receive : type a. ?session:Worker.session -> t -> ports:ports (match batch.root_owner with | Feed_roots scan -> with_coverage t ~ports scan packet.receipt accept | Changed_roots _ -> accept ()) + | Root_tree batch, Worker.Timeline_read {query=Paging.Roots_through_grandchildren _;_}, Ok packet -> + let accept () = + ports.observe_packet (Roots (Rrbvec.to_seq packet.items)); + receive_root_tree t ~ports batch packet in + (match batch.root_owner with + | Feed_roots scan -> with_coverage t ~ports scan packet.receipt accept + | Changed_roots _ -> accept ()) | Root_preview preview, Worker.Timeline_read {query=Paging.Preview_children _;_}, Ok packet -> ports.observe_packet (Preview (Rrbvec.to_seq packet.items)); receive_root_preview t ~ports preview packet @@ -1327,20 +1350,20 @@ let failed t ~ports operation ~code = scan.root_date_retries <- scan.root_date_retries + 1; Option.iter (fun day -> scan.root_journal_through <- day) scan.root_journal_boundary; scan.root_journal_cursor <- None; - read_root_dates ~ports scan) + read_root_dates t ~ports scan) | Root_dates (scan, _), Logseq_db_worker.Error.Response_too_large when scan.root_list_size>1 -> scan.root_list_size <- max 1 (scan.root_list_size/2); (* Resize from the inclusive catalog boundary and deduplicate only identities already observed at that boundary. *) Option.iter (fun day -> scan.root_journal_through <- day) scan.root_journal_boundary; scan.root_journal_cursor <- None; - read_root_dates ~ports scan + 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 | _->()); 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 ~ports {preview with preview_limit=max 1 (preview.preview_limit/2); + requests [read_root_preview t ~ports {preview with preview_limit=max 1 (preview.preview_limit/2); preview_members=Rrbvec.empty;preview_cursor=None}] | _ -> empty) ;; diff --git a/app/journal_graph_runtime.ml b/app/journal_graph_runtime.ml index 3d7bd343..de0ddd4a 100644 --- a/app/journal_graph_runtime.ml +++ b/app/journal_graph_runtime.ml @@ -2727,6 +2727,8 @@ let receive_delivery_body t ~origin ~request_id result = Rrbvec.singleton (Reference.Missing_page uuid) | Query_result (Worker.Timeline_read {query=Worker.Timeline.Roots _;_}, Ok packet) -> Rrbvec.map (fun (item:Worker_pure_data.tree_member) -> block item.value) packet.items + | Query_result (Worker.Timeline_read {query=Worker.Timeline.Roots_through_grandchildren _;_}, Ok packet) -> + Rrbvec.map (fun (item:Worker_pure_data.tree_member) -> block item.value) packet.items | Query_result (Worker.Timeline_read {query=Worker.Timeline.Preview_children _;_}, Ok packet) -> Rrbvec.map (fun (item:Worker_pure_data.child_member) -> block item.value) packet.items | Query_result (Worker.Child_members _, { items; _ }) -> diff --git a/logseq_db_worker/lib/effect_runner/effect_runner.ml b/logseq_db_worker/lib/effect_runner/effect_runner.ml index ea1d2026..6251750b 100644 --- a/logseq_db_worker/lib/effect_runner/effect_runner.ml +++ b/logseq_db_worker/lib/effect_runner/effect_runner.ml @@ -1511,12 +1511,27 @@ let read_typed let block_lookup record = function |Overlay.Present_block{value;revision}->Worker_pure_data.V2_present_block{value=record value;revision=Overlay.Block_state_revision.to_string revision} |Missing_block{uuid;revision}->V2_missing_block{uuid;revision=Overlay.Block_state_revision.to_string revision} in + let timeline_coverage_scope query = + Option.map (function + | Read.Timeline.Root_membership -> Database.Journal_root_membership + | Root_and_descendant_membership -> Database.Journal_root_and_descendant_membership) + (Read.Timeline.coverage_scope query) in + let timeline_version : type item. _ -> item Read.Timeline.query -> _ = fun snapshot query -> + let scope = match query with + | Read.Timeline.Dates _ -> Database.Journal_index + | Roots page -> Page_roots page + | Roots_through_grandchildren {page;_} -> Page_roots page + | Preview_children {parent;_} -> Parent_children parent in + Result.bind (Database.timeline_scope_version snapshot scope) (fun version -> + let version = Database.timeline_scope_version_to_string version in + match query with + | Preview_children {overflow_fallback=true;_} -> + Database.timeline_scope_version snapshot Journal_root_and_descendant_membership + |> Result.map (fun depth -> version ^ "/" ^ Database.timeline_scope_version_to_string depth) + | _ -> Ok version) in match query with |Read.Timeline_read {query=timeline_query;after}->with_snapshot(fun snapshot record _ -> let module Timeline=Read.Timeline in - let scope : type item. item Timeline.query -> Database.timeline_scope = function - | Dates _->Journal_index | Roots page->Page_roots page - | Preview_children parent->Parent_children parent in let source_error error = match error with |Overlay.Read_limit_exceeded->Timeline.Limit_exceeded "Timeline source exceeded its structural bound" |_->Timeline.Read_failed(typed_read_error error) in @@ -1529,17 +1544,16 @@ let read_typed Error(Timeline.Invalidated Owner_changed) |_->Ok() in let value=Result.bind checked(fun()-> - Database.timeline_scope_version snapshot (scope timeline_query) + timeline_version snapshot timeline_query |>Result.map_error source_error |>fun version->Result.bind version(fun version-> - let version=Database.timeline_scope_version_to_string version in if Option.exists(fun cursor->F.timeline_receipt_version(F.timeline_cursor_receipt cursor)<>version)after then Error(Timeline.Invalidated Scope_changed) else let position=Option.map F.timeline_cursor_position after in let decode_position decode=match position with None->Ok None|Some value->Result.map Option.some(decode value) in let read : type item. item Timeline.query -> int -> (item Rrbvec.t * string option,Timeline.error)result = fun query limit->match query with - |Dates {from_day;through_day}-> + |Dates {from_day;through_day;_}-> Result.bind(decode_position Database.journal_position_of_string)(fun after-> Database.get_timeline_journals snapshot ~from_day:(F.journal_day_value from_day) ~through_day:(F.journal_day_value through_day) ~limit ~after) @@ -1555,18 +1569,29 @@ let read_typed |>Result.map(fun(items,next)->Rrbvec.of_list(List.map(fun(item:Overlay.tree_member)-> Worker_pure_data.{value=record item.block;revision=Overlay.Block_state_revision.to_string item.revision; depth=item.depth;parent=item.parent})items),Option.map Database.member_position_to_string next) - |Preview_children parent-> + |Roots_through_grandchildren {page;tags;statuses}-> Result.bind(decode_position Database.member_position_of_string)(fun after-> - Database.get_timeline_children snapshot ~parent ~limit ~after) - |>Result.map_error source_error + Database.get_timeline_roots_through_grandchildren snapshot ~page ~tags ~statuses ~limit ~after) + |>Result.map_error (function Overlay.Stale_read_cursor -> Timeline.Invalidated Scope_changed | error -> source_error error) + |>Result.map(fun(items,next)->Rrbvec.of_list(List.map(fun(item:Overlay.tree_member)-> + Worker_pure_data.{value=record item.block;revision=Overlay.Block_state_revision.to_string item.revision; + depth=item.depth;parent=item.parent})items),Option.map Database.member_position_to_string next) + |Preview_children {parent;overflow_fallback}-> + let read = if overflow_fallback then Database.get_timeline_filtered_preview_children + else Database.get_timeline_children in + Result.bind(decode_position Database.member_position_of_string)(fun after-> + read snapshot ~parent ~limit ~after) + |>Result.map_error (function + | Overlay.Stale_read_cursor when overflow_fallback -> Timeline.Invalidated Scope_changed + | error -> source_error error) |>Result.map(fun(items,next)->Rrbvec.of_list(List.map(fun(item:Overlay.child_member)-> Worker_pure_data.{value=record item.block;revision=Overlay.Block_state_revision.to_string item.revision})items), Option.map Database.member_position_to_string next) in let receipt=F.timeline_receipt ~owner ~query:timeline_query ~version in - let receipt = match timeline_query with - | Preview_children _ -> Ok receipt - | Dates _ | Roots _ -> - Database.timeline_scope_version snapshot Journal_root_membership + let receipt = match timeline_coverage_scope timeline_query with + | None -> Ok receipt + | Some scope -> + Database.timeline_scope_version snapshot scope |> Result.map_error source_error |> Result.map (fun coverage -> F.with_timeline_coverage receipt (Database.timeline_scope_version_to_string coverage)) in @@ -1582,16 +1607,27 @@ let read_typed Ok value) |Read.Timeline_check receipts->with_snapshot(fun snapshot _ _ -> let module Timeline=Read.Timeline in - let check (Timeline.Receipt receipt) = + let rec check (Timeline.Receipt receipt) = if not(Read.equal_session owner(F.timeline_receipt_owner receipt)) then Error(Timeline.Invalidated Owner_changed) else - let scope=if F.timeline_receipt_is_coverage receipt then Database.Journal_root_membership - else match F.timeline_receipt_query receipt with - |Timeline.Dates _->Database.Journal_index - |Roots page->Page_roots page|Preview_children parent->Parent_children parent in - match Database.timeline_scope_version snapshot scope with - |Error error->Error(Timeline.Read_failed(typed_read_error error)) - |Ok version when Database.timeline_scope_version_to_string version=F.timeline_receipt_version receipt->Ok() + let query = F.timeline_receipt_query receipt in + let read_version result = Result.map_error (fun error -> Timeline.Read_failed(typed_read_error error)) result in + let version = + if F.timeline_receipt_is_coverage receipt then + match timeline_coverage_scope query with + | None -> Error (Timeline.Invalidated Scope_changed) + | Some scope -> Database.timeline_scope_version snapshot scope + |> Result.map Database.timeline_scope_version_to_string |> read_version + else timeline_version snapshot query |> read_version in + match version with + |Error error->Error error + |Ok version when version=F.timeline_receipt_version receipt-> + (match F.timeline_receipt_query receipt with + | Roots_through_grandchildren _ when not (F.timeline_receipt_is_coverage receipt) -> + (match Timeline.coverage receipt with + | Some coverage -> check coverage + | None -> Error (Timeline.Invalidated Scope_changed)) + | _ -> Ok ()) |Ok _->Error(Timeline.Invalidated Scope_changed) in Ok(F.timeline_check(Rrbvec.map check receipts))) |Read.Changes{generation;after}->fit (fun limit->changes ~generation ~after ~limit) diff --git a/logseq_db_worker/test/test_effect_runner.ml b/logseq_db_worker/test/test_effect_runner.ml index b5e4ca1c..b8d14f4d 100644 --- a/logseq_db_worker/test/test_effect_runner.ml +++ b/logseq_db_worker/test/test_effect_runner.ml @@ -1189,7 +1189,7 @@ let test_observation_release_waits_for_initial_snapshot () = "empty Timeline scopes retain an exhaustion receipt"; let day=Read.journal_day 20260902 |> Result.get_ok in let dates=run (Read.Timeline_read { - query=Timeline.dates ~from_day:day ~through_day:day; after=None }) |> Result.get_ok in + query=Timeline.dates ~coverage_scope:Root_membership ~from_day:day ~through_day:day; after=None }) |> Result.get_ok in let receipts=Rrbvec.of_list [Timeline.Receipt packet.receipt; Timeline.Receipt empty.receipt; Timeline.Receipt dates.receipt] in let checked=(run(Read.Timeline_check receipts)).Timeline.results in @@ -1210,6 +1210,85 @@ let test_observation_release_waits_for_initial_snapshot () = require (match Db.read_for_scope db ~scope (F.pack_query tiny (Read.Timeline_read{query=roots;after=None})) with | Read.Query_answer(_,Read.Timeline_read _,Ok(Error(Timeline.Limit_exceeded _)))->true | _->false) "Timeline singleton reports its final receipt and DTO byte bound"; + let module Mutation = Logseq_db_worker_contract.Worker_pure_mutation in + let origin = scope.account.managed_sync_origin and user = scope.account.user_id in + let graph = scope.graph_id in + let commit intent = match Db.durable_mutation_for_scope db ~scope ~intent ~current:(fun () -> true) with + | Mutation.Committed _ -> () + | _ -> Alcotest.fail "Timeline receipt fixture mutation did not commit" in + let journal = Fixture.mutation_uuid 29010 and child = Fixture.mutation_uuid 29012 in + let grandchild = Fixture.mutation_uuid 29015 in + let day = Read.journal_day 20261107 |> Result.get_ok in + let root : Worker_pure_data.append_node = { + block_id=Fixture.mutation_uuid 29011;title="Root";task_status=None; + children=Rrbvec.of_list Worker_pure_data.[ + {block_id=child;title="Child";task_status=None; + children=Rrbvec.singleton {block_id=grandchild;title="Grandchild";task_status=None;children=Rrbvec.empty}}; + {block_id=Fixture.mutation_uuid 29016;title="Sibling";task_status=None;children=Rrbvec.empty}] } in + commit (Mutation.Append_intent (Mutation.create_append ~origin ~user ~graph + ~mutation_id:(Fixture.mutation_uuid 29013) ~page:journal ~day ~root |> Result.get_ok)); + let status = Fixture.builtin_todo_uuid in + let read_roots query = run (Read.Timeline_read {query;after=None}) |> Result.get_ok in + let filtered = Timeline.roots_through_grandchildren ~page:journal ~tags:[] ~statuses:[status] in + let ordinary = read_roots (Timeline.roots ~page:journal) in + let day_query = Timeline.dates ~coverage_scope:Root_membership ~from_day:day ~through_day:day in + let day_packet = read_roots day_query in + let depth_query = Timeline.dates ~coverage_scope:Root_and_descendant_membership ~from_day:day ~through_day:day in + let depth_packet = read_roots depth_query in + let absent_day = Read.journal_day 20261108 |> Result.get_ok in + let empty_dates scope = read_roots (Timeline.dates ~coverage_scope:scope + ~from_day:absent_day ~through_day:absent_day) in + let empty_day = empty_dates Root_membership + and empty_depth = empty_dates Root_and_descendant_membership in + let coverage packet = Option.get (Timeline.coverage packet.Timeline.receipt) in + require (Rrbvec.is_empty empty_day.items && empty_day.next = Timeline.End && + Rrbvec.is_empty empty_depth.items && empty_depth.next = Timeline.End) + "both Dates modes can exhaust an empty range"; + require (not (Timeline.equal_coverage (coverage day_packet) (coverage depth_packet))) + "root and descendant coverage compare unequal"; + let preview_query = Timeline.preview_children ~parent:root.block_id in + let preview = read_roots preview_query in + let exhausted = read_roots filtered in + require (Rrbvec.is_empty exhausted.items && exhausted.next = Timeline.End) "filtered scope starts exhausted"; + let before = Timeline.Receipt exhausted.receipt in + let check receipts = (run (Read.Timeline_check (Rrbvec.of_list receipts))).Timeline.results |> Rrbvec.to_list in + require (check [before] = [Ok ()]) "filtered receipt validates before descendant change"; + let fallback_query = Timeline.filtered_preview_children ~parent:root.block_id in + let fallback = read_roots fallback_query in + let fallback_receipt = Timeline.Receipt fallback.receipt in + let cursor = match fallback.next with + | Timeline.More cursor -> cursor + | Timeline.End -> Alcotest.fail "fallback preview did not paginate" in + let resume () = run (Read.Timeline_read {query=fallback_query;after=Some cursor}) in + require (check [fallback_receipt] = [Ok ()]) "fallback receipt validates before descendant change"; + let second = resume () |> Result.get_ok in + require (second.next = Timeline.End && Rrbvec.length second.items = 1) + "fallback resumes on the unchanged snapshot"; + let revision = match run (Read.Outline_block {uuid=grandchild;revision=None}) with + | Worker_pure_data.V2_present_block {revision;_} -> revision + | _ -> Alcotest.fail "Timeline receipt fixture grandchild missing" in + let preconditions = Worker_pure_data.{blocks=[grandchild, revision];pages=[];scopes=[]} in + commit (Mutation.Mutation_intent (Mutation.create_mutation ~origin ~user ~graph + ~mutation_id:(Fixture.mutation_uuid 29014) + (Set_task_status {block=grandchild;status;preconditions}) |> Result.get_ok)); + require (Rrbvec.length (read_roots filtered).items = 1) "descendant status makes the root match"; + require (check [fallback_receipt] = [Error (Timeline.Invalidated Scope_changed)]) + "fallback packet receipt rejects a changed depth witness"; + require (resume () = Error (Timeline.Invalidated Scope_changed)) + "fallback continuation rejects a changed depth witness"; + require (check [Timeline.Receipt ordinary.receipt; before; Option.get (Timeline.coverage exhausted.receipt)] = + [Ok (); Error (Timeline.Invalidated Scope_changed); Error (Timeline.Invalidated Scope_changed)]) + "empty End receipt independently rejects changed membership while the ordinary root stays valid"; + require (check [coverage depth_packet; coverage empty_depth; coverage empty_day] = + [Error (Timeline.Invalidated Scope_changed); Error (Timeline.Invalidated Scope_changed); Ok ()]) + "grandchild-only change invalidates depth-selected Dates coverage"; + require (check [coverage day_packet; coverage ordinary; Timeline.Receipt preview.receipt] = + [Ok (); Ok (); Ok ()]) "grandchild-only change leaves day and regular root coverage and direct preview valid"; + require (Timeline.equal_coverage (coverage day_packet) (coverage (read_roots day_query))) + "day coverage remains equal after a grandchild-only change"; + require (Option.is_none (Timeline.coverage preview.receipt) && + Rrbvec.to_list preview.items = Rrbvec.to_list (read_roots preview_query).items) + "direct preview still has the same items and no coverage receipt"; (* Slot reconstruction is performed by the physical snapshot reader, not Core.step, so exercise it through the existing public Db fixture. *) let missing=Fixture.mutation_uuid 29001 in diff --git a/logseq_db_worker/typed_read/worker_pure_read.ml b/logseq_db_worker/typed_read/worker_pure_read.ml index 9560e896..02b03335 100644 --- a/logseq_db_worker/typed_read/worker_pure_read.ml +++ b/logseq_db_worker/typed_read/worker_pure_read.ml @@ -147,10 +147,13 @@ type (_, _) equality = Refl : ('a, 'a) equality module Timeline = struct module Day = Logseq_db_worker_contract.Worker_pure_day type worker_error = error + type coverage_scope = Root_membership | Root_and_descendant_membership type _ query = - | Dates : { from_day : Day.t; through_day : Day.t } -> Data.journal_item query + | Dates : { from_day : Day.t; through_day : Day.t; coverage_scope : coverage_scope } -> Data.journal_item query | Roots : Graph.page_uuid -> Data.tree_member query - | Preview_children : Graph.block_uuid -> Data.child_member query + | Roots_through_grandchildren : { page : Graph.page_uuid; tags : Uuid.t list; statuses : Uuid.t list } + -> Data.tree_member query + | Preview_children : { parent : Graph.block_uuid; overflow_fallback : bool } -> Data.child_member query type invalidation = Owner_changed | Scope_changed type error = | Invalid_request of string @@ -166,13 +169,20 @@ module Timeline = struct type check = { results : (unit, error) result Rrbvec.t } let coverage (receipt : 'a receipt) = Option.map (fun version -> Receipt {receipt with version;coverage=None;coverage_only=true}) receipt.coverage + let coverage_scope : type item. item query -> coverage_scope option = function + | Dates {coverage_scope;_} -> Some coverage_scope + | Roots _ -> Some Root_membership + | Roots_through_grandchildren _ -> Some Root_and_descendant_membership + | Preview_children _ -> None let equal_coverage (Receipt left) (Receipt right) = left.coverage_only && right.coverage_only && left.version = right.version - && left.owner = right.owner + && left.owner = right.owner && coverage_scope left.query = coverage_scope right.query let maximum_receipts = 4096 - let dates ~from_day ~through_day = Dates { from_day; through_day } + let dates ~coverage_scope ~from_day ~through_day = Dates { from_day; through_day; coverage_scope } let roots ~page = Roots page - let preview_children ~parent = Preview_children parent + let roots_through_grandchildren ~page ~tags ~statuses = Roots_through_grandchildren {page;tags;statuses} + let preview_children ~parent = Preview_children {parent; overflow_fallback=false} + let filtered_preview_children ~parent = Preview_children {parent; overflow_fallback=true} let worker_error_message = function |Revoked_session->"Worker session was revoked" |Invalid_input message|Stale_read message|Resync_required message|Protocol_mismatch message @@ -207,19 +217,32 @@ module Timeline = struct let equal_query : type a. a query -> a query -> bool = fun left right -> match left,right with | Dates left,Dates right -> Day.value left.from_day=Day.value right.from_day - && Day.value left.through_day=Day.value right.through_day + && Day.value left.through_day=Day.value right.through_day && left.coverage_scope=right.coverage_scope | Roots left,Roots right -> Uuid.equal left right - | Preview_children left,Preview_children right -> Uuid.equal left right + | Roots_through_grandchildren left,Roots_through_grandchildren right -> + Uuid.equal left.page right.page && left.tags = right.tags && left.statuses = right.statuses + | Preview_children left,Preview_children right -> + Uuid.equal left.parent right.parent && left.overflow_fallback = right.overflow_fallback + | Roots _,Roots_through_grandchildren _ | Roots_through_grandchildren _,Roots _ -> false let result_equality : type a b. a query -> b query -> (a,b) equality option = fun left right -> match left,right with | Dates _,Dates _ -> Some Refl | Roots _,Roots _ -> Some Refl + | Roots_through_grandchildren _,Roots_through_grandchildren _ -> Some Refl | Preview_children _,Preview_children _ -> Some Refl | _ -> None let query_json : type a. a query -> Yojson.Safe.t = function - | Dates {from_day;through_day} -> `List [`String "Dates";`Int(Day.value from_day);`Int(Day.value through_day)] + | Dates {from_day;through_day;coverage_scope} -> + let kind = match coverage_scope with + | Root_membership -> "Dates" + | Root_and_descendant_membership -> "Dates_through_grandchildren" in + `List [`String kind;`Int(Day.value from_day);`Int(Day.value through_day)] | Roots page -> `List [`String "Roots";Uuid.to_yojson page] - | Preview_children parent -> `List [`String "Preview_children";Uuid.to_yojson parent] + | Roots_through_grandchildren {page;tags;statuses} -> + `List [`String "Roots_through_grandchildren"; Uuid.to_yojson page; + `List (List.map Uuid.to_yojson tags); `List (List.map Uuid.to_yojson statuses)] + | Preview_children {parent;overflow_fallback} -> + `List [`String (if overflow_fallback then "Filtered_preview_children" else "Preview_children");Uuid.to_yojson parent] let owner_json (owner:session) = `List [`Intlit(Int64.to_string owner.binding.serial); `String(Int64.to_string(Journal_worker_ids.Runtime.Epoch.to_int64 owner.binding.incarnation.runtime_epoch)); @@ -235,6 +258,7 @@ module Timeline = struct let packet_json : type a. a query -> a packet -> Yojson.Safe.t = fun query packet -> let encode : a -> Yojson.Safe.t = match query with |Dates _->Data.journal_item_to_yojson|Roots _->Data.tree_member_to_yojson + |Roots_through_grandchildren _->Data.tree_member_to_yojson |Preview_children _->Data.child_member_to_yojson in `Assoc ["items",`List(List.map encode(Rrbvec.to_list packet.items));"receipt",receipt_json packet.receipt; "next",(match packet.next with End->`Null|More cursor->cursor_json cursor)] diff --git a/logseq_db_worker/typed_read/worker_pure_read.mli b/logseq_db_worker/typed_read/worker_pure_read.mli index f5e628e7..bbb3de57 100644 --- a/logseq_db_worker/typed_read/worker_pure_read.mli +++ b/logseq_db_worker/typed_read/worker_pure_read.mli @@ -207,10 +207,13 @@ module Timeline : sig [Timeline_check]; each request borrows and releases one immutable snapshot. *) module Day = Logseq_db_worker_contract.Worker_pure_day type worker_error = error + type coverage_scope = Root_membership | Root_and_descendant_membership type _ query = private - | Dates : { from_day : Day.t; through_day : Day.t } -> Data.journal_item query + | Dates : { from_day : Day.t; through_day : Day.t; coverage_scope : coverage_scope } -> Data.journal_item query | Roots : Graph.page_uuid -> Data.tree_member query - | Preview_children : Graph.block_uuid -> Data.child_member query + | Roots_through_grandchildren : { page : Graph.page_uuid; tags : Uuid.t list; statuses : Uuid.t list } + -> Data.tree_member query + | Preview_children : { parent : Graph.block_uuid; overflow_fallback : bool } -> Data.child_member query type invalidation = Owner_changed | Scope_changed type error = | Invalid_request of string @@ -228,6 +231,9 @@ module Timeline : sig (** Extract a membership-only proof obtained in the packet snapshot. *) val equal_coverage : packed_receipt -> packed_receipt -> bool + (** Compare membership proofs by session owner, coverage scope and version. *) + + val coverage_scope : 'a query -> coverage_scope option val maximum_receipts : int (** {1 Minimal usage example} @@ -244,9 +250,17 @@ module Timeline : sig result. *) (** {1 Construction and validation} *) - val dates : from_day:Day.t -> through_day:Day.t -> Data.journal_item query + val dates : coverage_scope:coverage_scope -> from_day:Day.t -> through_day:Day.t -> Data.journal_item query val roots : page:Graph.page_uuid -> Data.tree_member query + val roots_through_grandchildren + : page:Graph.page_uuid -> tags:Uuid.t list -> statuses:Uuid.t list -> Data.tree_member query + (** Returns top-level members only, matching at most the first 10,000 raw + candidates per parent, including the page. Excluded subtrees do not + match. An empty packet can have a continuation. *) + val preview_children : parent:Graph.block_uuid -> Data.child_member query + val filtered_preview_children : parent:Graph.block_uuid -> Data.child_member query + (** Ordinary preview, falling back to the bounded prefix on structural overflow. *) (** {1 Lifecycle and recovery} Cursors and receipts bind the exact session owner, query and write-maintained diff --git a/logseq_overlay_db/lib/database.ml b/logseq_overlay_db/lib/database.ml index 19d05751..34ff0f0b 100644 --- a/logseq_overlay_db/lib/database.ml +++ b/logseq_overlay_db/lib/database.ml @@ -135,7 +135,7 @@ type task_catalog_cache = ; catalog_items : Graph.task_status_definition array } -type timeline_scope = Journal_index | Journal_root_membership | Page_roots of Graph.page_uuid | Parent_children of Graph.block_uuid +type timeline_scope = Journal_index | Journal_root_membership | Journal_root_and_descendant_membership | Page_roots of Graph.page_uuid | Parent_children of Graph.block_uuid type timeline_scope_version = string type journal_position = string type member_position = string @@ -154,6 +154,7 @@ let member_position_of_string value = let timeline_scope_key = function | Journal_index -> "journal" | Journal_root_membership -> "journal-root-membership" + | Journal_root_and_descendant_membership -> "journal-root-and-descendant-membership" | Page_roots uuid -> "roots:" ^ Graph.Uuid.to_string uuid | Parent_children uuid -> "children:" ^ Graph.Uuid.to_string uuid @@ -2265,24 +2266,20 @@ let index_ordered_effects select records = index_effects select records |> Uuid_map.map Rrbvec.of_list ;; -let index_children_effects records = - index_effects - (fun record -> - List.filter_map - (function - | Types.Children_interest parent -> Some parent - | Page_tree_interest _ | Journal_index_interest -> None) - record.effect_footprint.structure_interests - @ - if record_has_active_dependency_shadows record - then - List.map - (fun shadow -> shadow.shadow_parent) - record.dependency_shadows.shadow_blocks - else []) - records +let children_effect_parents record = + List.filter_map + (function + | Types.Children_interest parent -> Some parent + | Page_tree_interest _ | Journal_index_interest -> None) + record.effect_footprint.structure_interests + @ + if record_has_active_dependency_shadows record + then List.map (fun shadow -> shadow.shadow_parent) record.dependency_shadows.shadow_blocks + else [] ;; +let index_children_effects records = index_effects children_effect_parents records + let frozen_outbox (records : outbox_record list) = List.map (fun (record : outbox_record) -> { record with mutation_id = record.mutation_id }) @@ -4630,11 +4627,7 @@ let timeline_member_offset scope version = function | _ -> Error (Types.Invalid_read_request "timeline member position belongs to another query")) ;; -let timeline_direct_members snapshot scope ~parent ~limit ~after = - with_snapshot_read snapshot (fun snapshot -> - if not (valid_page_limit limit) then Error (Types.Invalid_read_request "limit must be between 1 and 200") - else Result.bind (timeline_version_at snapshot scope) (fun version -> - Result.bind (timeline_member_offset scope version after) (fun offset -> +let timeline_direct_candidates ~truncate snapshot parent = let database = Option.get snapshot.authoritative_database in let cache = { hydration = hydration_cache ~index_idents:false database @@ -4643,37 +4636,58 @@ let timeline_direct_members snapshot scope ~parent ~limit ~after = in let identities = Hashtbl.create 64 in let examined = ref 0 in - let add uuid = + let remember uuid = Hashtbl.replace identities (Graph.Uuid.to_string uuid) uuid in + let consume legacy_limit use value = incr examined; - if !examined > maximum_cursor_offset * 2 then raise Exit; - Hashtbl.replace identities (Graph.Uuid.to_string uuid) uuid + if not truncate && !examined > legacy_limit then raise Exit; + use value; + if truncate && !examined = maximum_cursor_offset then raise Exit in - let candidates = try + let add = consume (maximum_cursor_offset * 2) remember in + let complete = try (match tree_entity snapshot cache parent with | None -> () | Some entity -> Datascript.datoms database Datascript.Avet ~a:"block/parent" ~v:(Datascript.Ref entity) () - |> Seq.iter (fun (datom : Datascript.datom) -> - incr examined; - if !examined > maximum_cursor_offset then raise Exit; - Option.iter (fun uuid -> Hashtbl.replace identities (Graph.Uuid.to_string uuid) uuid) - (cached_uuid_of_entity database cache.hydration datom.e))); + |> Seq.iter (consume maximum_cursor_offset (fun (datom : Datascript.datom) -> + Option.iter remember (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) -> if record_is_logically_active record then List.iter add record.effect_footprint.block_uuids; if record_has_active_dependency_shadows record then - List.iter (fun shadow -> if Graph.Uuid.equal shadow.shadow_parent parent then add shadow.shadow_block_uuid) + List.iter (fun shadow -> + if truncate then + consume maximum_cursor_offset (fun shadow -> + if Graph.Uuid.equal shadow.shadow_parent parent then remember shadow.shadow_block_uuid) shadow + else if Graph.Uuid.equal shadow.shadow_parent parent then add shadow.shadow_block_uuid) record.dependency_shadows.shadow_blocks); - if Hashtbl.length identities > maximum_cursor_offset then raise Exit; + Hashtbl.length identities <= maximum_cursor_offset + with Exit -> false + in + 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)) - with Exit -> None - in +;; + +let timeline_direct_members ?(preview_fallback=false) snapshot scope ~parent ~limit ~after = + with_snapshot_read snapshot (fun snapshot -> + if not (valid_page_limit limit) then Error (Types.Invalid_read_request "limit must be between 1 and 200") + else + let version = Result.bind (timeline_version_at snapshot scope) (fun parent_version -> + if preview_fallback then + timeline_version_at snapshot Journal_root_and_descendant_membership + |> Result.map (fun depth_version -> parent_version ^ "/" ^ depth_version) + else Ok parent_version) in + Result.bind version (fun version -> + Result.bind (timeline_member_offset scope version after) (fun offset -> + let candidates = match timeline_direct_candidates ~truncate:false snapshot parent with + | None when preview_fallback -> timeline_direct_candidates ~truncate:true snapshot parent + | result -> result in match candidates with | None -> Error Types.Read_limit_exceeded | Some candidates -> @@ -4694,12 +4708,109 @@ let get_timeline_children snapshot ~parent ~limit ~after = timeline_direct_members snapshot (Parent_children parent) ~parent ~limit ~after ;; +let get_timeline_filtered_preview_children snapshot ~parent ~limit ~after = + timeline_direct_members ~preview_fallback:true snapshot (Parent_children parent) ~parent ~limit ~after +;; + let get_timeline_roots snapshot ~page ~limit ~after = Result.map (fun (items,next) -> List.map (fun (item : Types.child_member) -> Types.{block=item.block; revision=item.revision;depth=0;parent=page}) items,next) (timeline_direct_members snapshot (Page_roots page) ~parent:page ~limit ~after) ;; +let get_timeline_roots_through_grandchildren snapshot ~page ~tags ~statuses ~limit ~after = + let ( let* ) = Result.bind in + let invalid = Error (Types.Invalid_read_request "invalid filtered Timeline position or limits") in + if not (valid_page_limit limit) || List.compare_length_with tags 200 > 0 + || List.compare_length_with statuses 200 > 0 then invalid else + let root_scope = Page_roots page in + let* roots_version = timeline_scope_version snapshot root_scope in + let* coverage = timeline_scope_version snapshot Journal_root_and_descendant_membership in + let query = Digest.to_hex (Digest.string (String.concat ":" + (Graph.Uuid.to_string page :: List.map Graph.Uuid.to_string tags @ ["status"] + @ List.map Graph.Uuid.to_string statuses))) in + let position root child grandchild = + Printf.sprintf "tf1|%s|%s|%s|%d|%d|%d" query roots_version coverage root child grandchild in + let* root, child, grandchild = match after with + | None -> Ok (0, -1, -1) + | Some cursor -> + (match String.split_on_char '|' cursor with + | ["tf1"; key; roots; membership; root; child; grandchild] when key = query -> + if roots <> roots_version || membership <> coverage then Error Types.Stale_read_cursor + else (match int_of_string_opt root, int_of_string_opt child, int_of_string_opt grandchild with + | Some root, Some child, Some grandchild + when root >= 0 && root <= maximum_cursor_offset && child >= -1 + && child <= maximum_cursor_offset && grandchild >= -1 + && grandchild <= maximum_cursor_offset -> Ok (root, child, grandchild) + | _ -> invalid) + | _ -> invalid) in + let ordinary_steps = 16 and wide_steps = 256 in + let wide = ref false and materialized = ref 0 in + let context = lazy (read_context snapshot) in + let read cache parent offset = + let candidates = match !cache with + | Some (previous, result) when Graph.Uuid.equal previous parent -> result + | _ -> + let result = timeline_direct_candidates ~truncate:true snapshot parent in + Option.iter (fun candidates -> + let count = Rrbvec.length candidates in + wide := !wide || count = maximum_cursor_offset; + materialized := !materialized + count) result; + cache := Some (parent, result); + result in + match candidates with + | None -> Error Types.Read_limit_exceeded + | Some candidates -> + let total = Rrbvec.length candidates in + if offset > total then invalid else + let one = Option.bind (Rrbvec.nth_opt candidates offset) (fun candidate -> + Option.map (fun block -> Types.{block; revision=logical_block_revision candidate.tree_uuid (Some block)}) + (read_block (Lazy.force context) candidate.tree_uuid)) in + Ok (one, offset + 1 < total) in + let roots_cache = ref None and children_cache = ref None and grandchildren_cache = ref None in + let matches (record : Types.block_record) = + List.exists (fun tag -> List.exists (Graph.Uuid.equal tag) tags) record.block.tags + || match record.task_status with + | Some (Status_uuid uuid) -> List.exists (Graph.Uuid.equal uuid) statuses + | Some (Legacy_status_ident _) | None -> false in + let rec scan fuel remaining items root child grandchild = + if remaining = 0 || fuel = 0 + || (fuel <= wide_steps - ordinary_steps && not !wide) || !materialized >= 2 * maximum_cursor_offset + then Ok (List.rev items, Some (position root child grandchild)) + else + let* item, more_roots = read roots_cache page root in + let advance items remaining = + if more_roots then scan (fuel - 1) remaining items (root + 1) (-1) (-1) + else Ok (List.rev items, None) in + match item with + | None -> advance items remaining + | Some root_item when not (Graph.Uuid.equal root_item.block.block.page page) -> advance items remaining + | Some root_item -> + let hit () = advance + (Types.{block=root_item.block;revision=root_item.revision;depth=0;parent=page} :: items) + (remaining - 1) in + if child = -1 && matches root_item.block then hit () else + let child = max 0 child in + let parent = root_item.block.block.uuid in + let* item, siblings = read children_cache parent child in + let advance_child () = + if siblings then scan (fuel - 1) remaining items root (child + 1) (-1) + else advance items remaining in + match item with + | None -> advance_child () + | Some item when not (Graph.Uuid.equal item.block.block.page page) -> advance_child () + | Some item -> + if grandchild = -1 && matches item.block then hit () else + let grandchild = max 0 grandchild in + let parent = item.block.block.uuid in + let* item, more = read grandchildren_cache parent grandchild in + match item with + | Some item when Graph.Uuid.equal item.block.block.page page && matches item.block -> hit () + | _ when more -> scan (fuel - 1) remaining items root child (grandchild + 1) + | _ -> advance_child () in + with_snapshot_read snapshot (fun _ -> scan wide_steps limit [] root child grandchild) +;; + (* Writes own invalidation under the owner lock. Dependency cursors are lazy; hydration contexts are discarded after each batch. The visited identity sets contain only this write's affected closure and are released on return. *) @@ -4723,6 +4834,24 @@ let maintain_timeline_scopes database (before : snapshot) (after : snapshot) = |> Seq.filter (fun (report : Datascript.tx_report) -> report.db_after.max_tx > old_db.max_tx) |> Seq.flat_map (fun (report : Datascript.tx_report) -> List.to_seq report.tx_data) in + let raw_parents = Hashtbl.create 16 in + let add_raw_parent uuid = + let key = Graph.Uuid.to_string uuid in + if not (Hashtbl.mem raw_parents key) then ( + Hashtbl.add raw_parents key (); + enqueue (Seq.return (uuid, false))) in + let add_authoritative_parent db entity = + Option.iter add_raw_parent (uuid_of_entity db entity) in + Seq.iter (fun (datom : Datascript.datom) -> + List.iter (fun db -> + match datom.a, datom.v with + | "block/parent", Datascript.Ref entity -> add_authoritative_parent db entity + | "block/uuid", _ -> + add_authoritative_parent db datom.e; + (match one db datom.e "block/parent" with + | Some (Datascript.Ref entity) -> add_authoritative_parent db entity + | _ -> ()) + | _ -> ()) [old_db; new_db]) changed_datoms; let revoked_identities = Hashtbl.create 16 in Seq.iter (fun (datom : Datascript.datom) -> if datom.a = "block/uuid" && not datom.added then @@ -4738,10 +4867,23 @@ let maintain_timeline_scopes database (before : snapshot) (after : snapshot) = (Seq.append (List.to_seq record.effect_footprint.block_uuids) (List.to_seq record.effect_footprint.page_uuids)) in + let raw_overlay_source = function + | None -> None + | Some (record : outbox_record) -> + let blocks = if record_is_logically_active record then record.effect_footprint.block_uuids else [] in + let shadows = if record_has_active_dependency_shadows record + then List.map (fun shadow -> shadow.shadow_parent, shadow.shadow_block_uuid) + record.dependency_shadows.shadow_blocks else [] in + if blocks = [] && shadows = [] then None + else Some (children_effect_parents record, blocks, shadows) in Uuid_map.merge (fun _ old current -> if old <> current then ( Option.iter (fun record -> enqueue (record_jobs record)) old; - Option.iter (fun record -> enqueue (record_jobs record)) current); + Option.iter (fun record -> enqueue (record_jobs record)) current; + let old_source = raw_overlay_source old and new_source = raw_overlay_source current in + if old_source <> new_source then + List.iter (Option.iter (fun (parents, _, _) -> List.iter add_raw_parent parents)) + [old_source; new_source]); None) old_records new_records |> ignore; if old_db != new_db then ( let add_logical_dependents _ (record : outbox_record) = @@ -4822,21 +4964,38 @@ let maintain_timeline_scopes database (before : snapshot) (after : snapshot) = if revoked || block_dto old_context old_block <> block_dto new_context new_block then List.iter mark_parent (List.filter_map Fun.id [parent_of old_block;parent_of new_block]); let candidate context = function - | Some (record : Types.block_record) when Graph.Uuid.equal record.block.parent record.block.page -> - (match journal_dto context (read_page context record.block.page) with - | Some _ -> Some (record.block.page, record.block.order, record.block.tags, record.task_status) - | None -> None) + | Some (record : Types.block_record) -> + let page = record.block.page in + let rec path remaining parent ancestors = + if Graph.Uuid.equal parent page then Some ancestors + else if remaining = 0 then None + else match read_block context parent with + | Some ancestor when Graph.Uuid.equal ancestor.block.page page -> + path (remaining - 1) ancestor.block.parent (parent :: ancestors) + | _ -> None in + Option.bind (path 2 record.block.parent []) (fun ancestors -> + Option.map (fun _ -> page, ancestors, record.block.order, record.block.tags, record.task_status) + (journal_dto context (read_page context page))) | _ -> None in let old_candidate = candidate old_context old_block and new_candidate = candidate new_context new_block in - if old_candidate <> new_candidate - || (revoked && (Option.is_some old_candidate || Option.is_some new_candidate)) - then mark Journal_root_membership; + let changed old_candidate new_candidate = + old_candidate <> new_candidate + || (revoked && (Option.is_some old_candidate || Option.is_some new_candidate)) in + let root_only = function Some (_, [], _, _, _) as candidate -> candidate | _ -> None in + if changed old_candidate new_candidate then mark Journal_root_and_descendant_membership; + if changed (root_only old_candidate) (root_only new_candidate) then mark Journal_root_membership; let old_journal = journal_dto old_context old_page and new_journal = journal_dto new_context new_page in + let scans_children journal = function + | Some (_, ([] | [_]), _, _, _) -> true + | _ -> Option.is_some journal in + if Hashtbl.mem raw_parents key + && (scans_children old_journal old_candidate || scans_children new_journal new_candidate) + then mark Journal_root_and_descendant_membership; if old_journal <> new_journal || (revoked && (Option.is_some old_journal || Option.is_some new_journal)) - then (mark Journal_index; mark Journal_root_membership)); + then (mark Journal_index; mark Journal_root_membership; mark Journal_root_and_descendant_membership)); let rendered_title = function None -> None | Some (page : Types.page_record) -> Some page.page.title in let title_changed = rendered_title old_page <> rendered_title new_page in let deleted db = Option.bind (entity_of_uuid db uuid) (fun entity -> one db entity "logseq.property/deleted-at") in diff --git a/logseq_overlay_db/spec/database.mli b/logseq_overlay_db/spec/database.mli index 08fc43e0..c4f416bb 100644 --- a/logseq_overlay_db/spec/database.mli +++ b/logseq_overlay_db/spec/database.mli @@ -380,7 +380,8 @@ val get_structure Release every borrowed snapshot to release its history roots. *) type timeline_scope = | Journal_index - | Journal_root_membership (** Date membership and visible journal root candidacy. *) + | Journal_root_membership (** Date membership and direct-root candidacy. *) + | Journal_root_and_descendant_membership (** Date membership and candidacy through grandchildren. *) | Page_roots of Graph.page_uuid | Parent_children of Graph.block_uuid @@ -410,10 +411,32 @@ val get_timeline_journals val get_timeline_roots : snapshot -> page:Graph.page_uuid -> limit:int -> after:member_position option -> (Types.tree_member list * member_position option, Types.read_error) result + +(** Scan only roots, their children and their grandchildren. Match any selected + tag or task status and return the ordinary top-level member on the first hit. + Each parent (including the journal page) contributes at most 10,000 raw + entries: authoritative parent datoms in index order, then indexed overlay + footprints and shadow entries in stored order. Duplicates, tombstones and + entries that do not resolve to live direct members still consume slots. + The surviving prefix is sorted in ordinary member order; excluded members + and their descendants cannot match. Other parents continue independently. + A bounded scan may return an empty packet with a continuation. *) +val get_timeline_roots_through_grandchildren + : snapshot -> page:Graph.page_uuid -> tags:Graph.Uuid.t list -> statuses:Graph.Uuid.t list + -> limit:int -> after:member_position option + -> (Types.tree_member list * member_position option, Types.read_error) result + val get_timeline_children : snapshot -> parent:Graph.block_uuid -> limit:int -> after:member_position option -> (Types.child_member list * member_position option, Types.read_error) result +(** Use ordinary direct preview paging, falling back to the bounded candidate + prefix if the ordinary read exceeds its structural limit. Preview members + do not need to match the filter. *) +val get_timeline_filtered_preview_children + : snapshot -> parent:Graph.block_uuid -> limit:int -> after:member_position option + -> (Types.child_member list * member_position option, Types.read_error) result + (** {3 Example: reading one coherent projection} Every read in the callback observes the roots captured by the same snapshot. diff --git a/logseq_overlay_db/test/test_overlay_reads.ml b/logseq_overlay_db/test/test_overlay_reads.ml index 614687d3..1c7c8572 100644 --- a/logseq_overlay_db/test/test_overlay_reads.ml +++ b/logseq_overlay_db/test/test_overlay_reads.ml @@ -1573,10 +1573,139 @@ let timeline_remote_scopes_cover_metadata_moves_and_aba database = | Error Stale_read_cursor -> () | _ -> Alcotest.fail "changed root scope accepted old ordinal"); Database.release_snapshot latest; let preview = version (Database.Parent_children (id 4)) in - apply 10 [add 1 "logseq.property/deleted-at" (J.Int 1234)]; + let coverage = version Database.Journal_root_and_descendant_membership in + apply 10 [add 5 "block/tags" (lookup 2)]; + changed "previously skipped child tag retained filter coverage" coverage Database.Journal_root_and_descendant_membership; + apply 11 [add 1 "logseq.property/deleted-at" (J.Int 1234)]; changed "ancestor recycling retained preview receipt" preview (Database.Parent_children (id 4)) ;; +let timeline_filter_depth database = + let behavior = "filter roots through grandchildren" in + let module J = Transit_core.Json in + let id n = T.uuid (Printf.sprintf "76100000-0000-4000-8000-%012d" n) in + let lookup n = T.status_lookup (id n) in + let add = T.status_add in + let create n fields = + List.map (fun (key,value) -> add (J.Int (31000+n)) key value) + (("block/uuid", J.Uuid (Graph.Uuid.to_string (id n))) :: fields) in + let block n parent = create n + ["block/title",J.String (string_of_int n); "block/parent",lookup parent; + "block/page",lookup 1; "block/order",J.String (Printf.sprintf "%04d" n)] in + let tag n = add (lookup n) "block/tags" (lookup 2) in + let apply cursor operations = T.apply_test_transaction database ~cursor operations in + apply 1 (create 1 ["block/title",J.String "Day";"block/name",J.String "day"; + "block/journal-day",J.Int 20261101] + @ create 2 ["block/title",J.String "Selected";"block/name",J.String "selected"] + @ List.concat_map (fun n -> block n 1) [3;4;5;6] + @ block 7 4 @ block 8 6 @ block 9 8 @ block 10 9 + @ List.concat (List.init 38 (fun index -> block (20+index) 5)) @ block 58 57 + @ [tag 3;add (lookup 7) "logseq.property/status" (J.Keyword "logseq.property/status.todo");tag 58;tag 10]); + let with_snapshot use = + let snapshot = Database.current_snapshot database |> T.require_ok ~behavior in + Fun.protect ~finally:(fun () -> Database.release_snapshot snapshot) (fun () -> use snapshot) in + let read snapshot after = Database.get_timeline_roots_through_grandchildren snapshot + ~page:(id 1) ~limit:2 ~tags:[id 2] ~statuses:[T.builtin_todo_uuid] ~after in + let rec collect snapshot fuel after gathered = + T.require (fuel > 0) "filtered scan did not terminate"; + let items,next = read snapshot after |> T.require_ok ~behavior in + List.iter (fun (item : Types.tree_member) -> + T.require (item.depth = 0 && Graph.Uuid.equal item.parent (id 1)) "matched descendant was promoted") items; + let gathered = gathered @ List.map (fun (item : Types.tree_member) -> item.block.block.uuid) items in + match next with None -> gathered | Some _ -> collect snapshot (fuel-1) next gathered in + with_snapshot (fun snapshot -> + let first, next = read snapshot None |> T.require_ok ~behavior in + T.require (List.length first = 2 && Option.is_some next) "expected first two root hits"; + let sparse, continuation = read snapshot next |> T.require_ok ~behavior in + T.require (sparse = [] && Option.is_some continuation) "late grandchild did not require continuation"; + T.require (collect snapshot 20 None [] = List.map id [3;4;5]) "wrong root membership by depth"; + let previews,_ = Database.get_timeline_children snapshot ~parent:(id 5) ~limit:3 ~after:None + |> T.require_ok ~behavior in + T.require (List.map (fun (item : Types.child_member) -> item.block.block.uuid) previews = List.map id [20;21;22]) + "ordinary preview lost nonmatching siblings"; + apply 2 [add (lookup 58) "block/parent" (lookup 10); add (lookup 10) "block/parent" (lookup 8)]; + T.require (collect snapshot 20 None [] = List.map id [3;4;5]) "old snapshot observed a move"; + with_snapshot (fun latest -> + (match read latest continuation with + | Error Stale_read_cursor -> () | _ -> Alcotest.fail "cross-depth move accepted a stale scan"); + T.require (collect latest 20 None [] = List.map id [3;4;6]) "cross-depth move did not change matching roots")) +;; + +let timeline_filter_parent_cap database = + let behavior = "Timeline filter truncates each parent independently" in + let module J = Transit_core.Json in + let id = T.mutation_uuid in + let lookup n = T.status_lookup (id n) in + let create n fields = + List.map (fun (key, value) -> T.status_add (J.Int (31000 + n)) key value) + (("block/uuid", J.Uuid (Graph.Uuid.to_string (id n))) :: fields) in + let page n = create n ["block/title", J.String (string_of_int n); + "block/name", J.String (string_of_int n)] in + let block n parent = create n + ["block/title", J.String (string_of_int n); "block/parent", lookup parent; + "block/page", lookup 1; "block/order", J.String (Printf.sprintf "%06d" n)] in + let tag n selected = T.status_add (lookup n) "block/tags" (lookup selected) in + let cursor = ref 0 in + let apply operations = + incr cursor; + T.apply_test_transaction database ~cursor:!cursor operations in + apply (page 1 @ page 2 @ page 3 @ page 4 @ page 5 + @ [T.status_add (lookup 1) "block/journal-day" (J.Int 20261101)] + @ block 6 1 @ block 7 1 @ block 8 1 @ block 9 7 @ block 10 8); + let wide start parent = + for batch = 0 to 20 do + let offset = batch * 500 in + apply (List.concat_map (fun i -> block (start + offset + i) parent) + (List.init (min 500 (10_001 - offset)) Fun.id)) + done in + wide 100 6; + wide 20_100 9; + apply (block 40_100 10_100 + @ [tag 101 2; tag 10_099 3; tag 30_099 3; + tag 10_100 4; tag 30_100 4; tag 40_100 5; tag 10 4]); + let snapshot = Database.current_snapshot database |> T.require_ok ~behavior in + let preview_position = Fun.protect ~finally:(fun () -> Database.release_snapshot snapshot) (fun () -> + let read selected after = Database.get_timeline_roots_through_grandchildren snapshot + ~page:(id 1) ~tags:(List.map id selected) ~statuses:[] ~limit:3 ~after + |> T.require_ok ~behavior in + let uuids = List.map (fun (item : Types.tree_member) -> item.block.block.uuid) in + let first, _ = read [2] None in + T.require (uuids first = [id 6]) "early hit did not return the ordinary root"; + let preview, next = Database.get_timeline_filtered_preview_children snapshot + ~parent:(id 6) ~limit:3 ~after:None |> T.require_ok ~behavior in + T.require (List.map (fun (item : Types.child_member) -> item.block.block.uuid) preview + = List.map id [100; 101; 102] && Option.is_some next) + "matched wide root lost its ordinary ordered preview, including nonmatches"; + T.require (Database.get_timeline_children snapshot ~parent:(id 6) ~limit:3 ~after:None + = Error Types.Read_limit_exceeded) "ordinary preview overflow policy changed"; + let rec collect selected fuel after roots = + T.require (fuel > 0) "bounded scan did not terminate"; + let items, next = read selected after in + let roots = List.rev_append (uuids items) roots in + match next with None -> List.rev roots | Some _ -> collect selected (fuel - 1) next roots in + T.require (collect [3] 2000 None [] = [id 6; id 7]) + "raw source entry 10,000 was excluded at child or grandchild depth"; + T.require (collect [4; 5] 2000 None [] = [id 8]) + "raw source entry 10,001 or its descendants matched, or a sibling branch was lost"; + let roots, _ = Database.get_timeline_roots snapshot ~page:(id 1) ~limit:3 ~after:None + |> T.require_ok ~behavior in + T.require (uuids roots = List.map id [6; 7; 8]) "unfiltered roots changed"; + let dates, _ = Database.get_timeline_journals snapshot ~from_day:20261101 ~through_day:20261101 + ~limit:1 ~after:None |> T.require_ok ~behavior in + T.require (List.length dates = 1) "date selection changed"; + let resumed, _ = Database.get_timeline_filtered_preview_children snapshot + ~parent:(id 6) ~limit:3 ~after:next |> T.require_ok ~behavior in + T.require (List.map (fun (item : Types.child_member) -> item.block.block.uuid) resumed + = List.map id [103; 104; 105]) "wide preview did not resume in order"; + next) in + apply [tag 40_100 2]; + let snapshot = Database.current_snapshot database |> T.require_ok ~behavior in + Fun.protect ~finally:(fun () -> Database.release_snapshot snapshot) (fun () -> + T.require (Database.get_timeline_filtered_preview_children snapshot + ~parent:(id 6) ~limit:3 ~after:preview_position = Error Types.Stale_read_cursor) + "wide preview position survived a change to the depth witness") +;; + let timeline_overlay_roots_follow_remote_page_metadata database = let behavior = "timeline overlay roots follow remote page metadata" in let module J = Transit_core.Json in @@ -1761,6 +1890,8 @@ let cases = ; T.database_case "timeline history retirement recovers" timeline_history_retirement_recovers ; T.database_case "timeline large dependency fanout keeps authority" timeline_large_dependency_fanout_keeps_authority ; T.database_case "timeline overlay roots follow remote page metadata" timeline_overlay_roots_follow_remote_page_metadata + ; T.database_case "timeline filter depth and moves" timeline_filter_depth + ; T.database_case "timeline filter per-parent cap" timeline_filter_parent_cap ; T.database_case "timeline remote scopes cover metadata moves and ABA" timeline_remote_scopes_cover_metadata_moves_and_aba ; T.database_case "timeline local scope versions bind payload and snapshots" timeline_scopes_follow_local_payload_and_snapshot ; T.database_case "timeline direct paging survives unrelated scopes" timeline_pages_continue_across_unrelated_scopes diff --git a/logseq_overlay_db/test/test_overlay_sync.ml b/logseq_overlay_db/test/test_overlay_sync.ml index d14c4aa3..b5a46a32 100644 --- a/logseq_overlay_db/test/test_overlay_sync.ml +++ b/logseq_overlay_db/test/test_overlay_sync.ml @@ -1255,7 +1255,8 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database add_page "block/journal-day" (J.Int 20261102); add_child "block/uuid" (J.Uuid(Logseq_db_types.Graph_types.Uuid.to_string(T.mutation_uuid 7795))); add_child "block/title" (J.String "Remote first entry");add_child "block/parent" page_entity; - add_child "block/page" page_entity;add_child "block/order" (J.String "a9")]; + add_child "block/page" page_entity;add_child "block/order" (J.String "a9"); + add_child "logseq.property/status" (T.status_lookup (T.status_uuid 2))]; let snapshot=Database.current_snapshot database |> T.require_ok ~behavior in Fun.protect ~finally:(fun()->Database.release_snapshot snapshot)(fun()-> T.require(match Database.get_outline_blocks snapshot [root_uuid] |> T.require_ok ~behavior with @@ -1285,8 +1286,40 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database let sync=Database.inspect_sync database |> T.require_ok ~behavior in let prepared,crypto=Database.begin_authoritative database ~expected:(sync_view_token sync)batch |> T.require_ok ~behavior in let decrypted=Option.map(fun request->decrypt_submitted_request request behavior)crypto in - (match Database.apply_authoritative database prepared ~decrypted |> T.require_ok ~behavior with - | Authoritative_applied _->()|_->Alcotest.fail "atomic append echo was deferred"); + let settle () = + match Database.apply_authoritative database prepared ~decrypted |> T.require_ok ~behavior with + | Authoritative_applied _ -> () + | Authoritative_deferred _ -> Alcotest.fail "atomic append echo was deferred" in + let with_snapshot use = + let snapshot = Database.current_snapshot database |> T.require_ok ~behavior in + Fun.protect ~finally:(fun () -> Database.release_snapshot snapshot) (fun () -> use snapshot) in + if not remote_day then settle () else + with_snapshot (fun before -> + let read snapshot after = Database.get_timeline_roots_through_grandchildren snapshot + ~page:resolved_page ~tags:[] ~statuses:[T.status_uuid 2] ~limit:1 ~after in + let first, next = read before None |> T.require_ok ~behavior in + let ids = List.map (fun (item : Types.tree_member) -> item.block.block.uuid) in + T.require (ids first = [T.mutation_uuid 7795] && Option.is_some next) + "accepted overlay must yield a real filtered continuation"; + let suffix = read before next |> T.require_ok ~behavior in + T.require (ids (fst suffix) = [root_uuid] && snd suffix = None) "wrong overlay suffix"; + let version snapshot scope = Database.timeline_scope_version snapshot scope |> T.require_ok ~behavior in + let roots snapshot = Database.get_timeline_roots snapshot ~page:resolved_page ~limit:3 ~after:None + |> T.require_ok ~behavior in + settle (); + T.require (read before next = Ok suffix) "settlement changed a retained snapshot"; + with_snapshot (fun after -> + T.require (roots before = roots after) "settlement changed ordinary root DTOs"; + List.iter (fun scope -> + T.require (Database.equal_timeline_scope_version (version before scope) (version after scope)) + "settlement changed an unrelated Timeline proof") + [Database.Journal_index; Journal_root_membership; Page_roots resolved_page; Parent_children root_uuid]; + (match read after next with + | Error Stale_read_cursor -> () + | _ -> Alcotest.fail "authoritative settlement accepted the overlay continuation"); + let fresh, next = read after None |> T.require_ok ~behavior in + T.require (fresh = first && Option.is_some next && read after next = Ok suffix) + "fresh authoritative prefix and continuation changed logical results")); let snapshot=Database.current_snapshot database |> T.require_ok ~behavior in Fun.protect ~finally:(fun()->Database.release_snapshot snapshot)(fun()-> (match Database.get_pages snapshot [resolved_page] |> T.require_ok ~behavior with diff --git a/test/application_view_test.ml b/test/application_view_test.ml index c5b0c204..6829be44 100644 --- a/test/application_view_test.ml +++ b/test/application_view_test.ml @@ -1308,7 +1308,7 @@ let run_favorites_native_visibility ; depth = 0 ; parent = page.uuid })) ~next:(if offset + length < count then Some (string_of_int (offset + length)) else None))) - | Read.Timeline_read {query=(Read.Timeline.Preview_children parent as timeline);_} -> + | Read.Timeline_read {query=(Read.Timeline.Preview_children {parent;_} as timeline);_} -> let items, next = child_items parent in Ok (Ok (fixture_timeline_packet budget timeline ~items ~next:(Option.map G.Cursor.to_string next))) diff --git a/test/journal_graph_runtime_locality_test.ml b/test/journal_graph_runtime_locality_test.ml index fa0fe65c..3a475d95 100644 --- a/test/journal_graph_runtime_locality_test.ml +++ b/test/journal_graph_runtime_locality_test.ml @@ -15,7 +15,8 @@ let query_sample produce = function let fixture_scope : type a. a Read.Timeline.query -> string = function | Read.Timeline.Dates _ -> "dates" | Read.Timeline.Roots page -> "roots:" ^ Graph.Uuid.to_string page - | Read.Timeline.Preview_children parent -> "preview:" ^ Graph.Uuid.to_string parent + | Read.Timeline.Roots_through_grandchildren {page;_} -> "roots:" ^ Graph.Uuid.to_string page + | Read.Timeline.Preview_children {parent;_} -> "preview:" ^ Graph.Uuid.to_string parent ;; let fixture_versions = Hashtbl.create 32 @@ -55,6 +56,11 @@ let tree_sample ~(items : Worker_pure_data.tree_member list) ~next = match query with | Read.Timeline_read {query=(Read.Timeline.Roots _ as timeline);_} -> Read.For_worker.answer budget query (Ok (Ok (fixture_packet budget timeline ~items ~next))) + | Read.Timeline_read {query=(Read.Timeline.Roots_through_grandchildren {tags;statuses;_} as timeline);_} -> + let items = List.filter (fun (item : Worker_pure_data.tree_member) -> + List.exists (fun tag -> List.mem tag tags) item.value.block.tags + || Option.exists (fun status -> List.mem status statuses) item.value.task_status) items in + Read.For_worker.answer budget query (Ok (Ok (fixture_packet budget timeline ~items ~next))) | Read.Tree _ -> let module F = Read.For_worker in Read.For_worker.answer budget query (Ok (F.slice ~items @@ -287,7 +293,7 @@ let load_feed runtime = let rec finish_previews runtime ~children (output:Runtime.output) : Runtime.output = List.fold_left (fun (kept:Runtime.output) id -> match Worker_producer.transport runtime id with - |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Preview_children parent;_} as query));_})-> + |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Preview_children {parent;_};_} as query));_})-> let cursor=fixture_cursor budget query in let limit=Read.For_worker.read_budget_maximum_items budget in let items=List.filter(fun (item:Worker_pure_data.child_member)->item.value.block.parent=parent)children @@ -667,7 +673,7 @@ let test_resync_and_dependent_reads_share_hydration_bound () = ( "tree" , (tree_sample ~items:((List.filter (fun (m:Worker_pure_data.tree_member)->m.depth=0) items : Worker_pure_data.tree_member list)) ~next:(None)) ) | Some(Runtime.Read{query=W.Child_members {parent;_};_}) - | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Preview_children parent;_};_}) -> + | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Preview_children {parent;_};_};_}) -> ( "children" , (children_sample ~parent:(parent) ~scope_revision:("children-2") ~items:([]) ~next:(None)) ) | Some(Runtime.Read{query=W.Outline_block {uuid=id;_};_}) -> @@ -1053,7 +1059,7 @@ let test_older_feed_uses_calendar_upper_bound () = | _ -> Alcotest.fail "earliest date did not complete") else let request = only "older journal request" output.requests in match Runtime.worker_read runtime request with - | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Dates {from_day;through_day};_};_}) -> + | Some(Runtime.Read{query=W.Timeline_read {query=W.Timeline.Dates {from_day;through_day;_};_};_}) -> Alcotest.(check bool) "first valid lower date" true (W.journal_day 10101=Ok from_day); Alcotest.(check bool) "exclusive calendar upper date" true (W.journal_day expected=Ok through_day) | _ -> Alcotest.fail "older feed did not request journals") @@ -2386,8 +2392,10 @@ let target_uuid = uuid "a1000000-0000-4000-9000-000000000050" let target_id = Graph.Uuid.to_string target_uuid let reference = "[[" ^ target_id ^ "]]" -let reference_feed runtime source = +let reference_feed ?(filtered = false) runtime source = set_calendar runtime; + let tags = if filtered then [block_uuid] else [] in + if filtered then Runtime.set_timeline_filter runtime ~tags ~statuses:[] ~days:None; let journals = load_feed runtime in let tree = deliver_sample @@ -2401,7 +2409,7 @@ let reference_feed runtime source = runtime (sample tree - ((tree_sample ~items:(([ { value = { record with block = { block with title = source } } + ((tree_sample ~items:(([ { value = { record with block = { block with title = source; tags } } ; revision = "block-1" ; depth = 0 ; parent = page_uuid @@ -2446,6 +2454,11 @@ let check_target_request runtime output = request ;; +let test_filtered_root_reference () = + let runtime = Runtime.create () in + ignore (reference_feed ~filtered:true runtime reference |> check_target_request runtime) +;; + let test_reference_hydration_and_changes () = let runtime = Runtime.create () in let request = @@ -6776,7 +6789,7 @@ let drive_root_output ?(split_bytes = false) ?(filter_omitted = false) runtime f seen := Runtime.worker_read runtime request :: !seen; let outcome = match Worker_producer.transport runtime request with - |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Dates {from_day=sealed_from_day;through_day=sealed_through_day};_} as query));_})-> + |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Dates {from_day=sealed_from_day;through_day=sealed_through_day;_};_} as query));_})-> let cursor=fixture_cursor budget query in let from_day=Read.For_worker.journal_day_value sealed_from_day in let through_day=Read.For_worker.journal_day_value sealed_through_day in @@ -6792,11 +6805,11 @@ let drive_root_output ?(split_bytes = false) ?(filter_omitted = false) runtime f in Worker_pure_data.{ page = f.owner; journal_day; revision = "page-1" }) selected : Worker_pure_data.journal_item list)) ~next:(next_cursor)) - |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Roots page;_} as query));_})-> + |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=(Read.Timeline.Roots page | Read.Timeline.Roots_through_grandchildren {page;_});_} as query));_})-> let cursor=fixture_cursor budget query in let limit=Read.For_worker.read_budget_maximum_items budget in (match Production_runtime.worker_read runtime request with - | Some (Production_runtime.Read {query=Journal_worker_coordination.Worker_api.Timeline_read {query=Journal_worker_coordination.Worker_api.Timeline.Roots _;_};_})->() + | Some (Production_runtime.Read {query=Journal_worker_coordination.Worker_api.Timeline_read {query=(W.Timeline.Roots _ | W.Timeline.Roots_through_grandchildren _);_};_})->() | _->Alcotest.fail "feed roots bypassed typed coordinator"); if split_bytes && limit > 2 @@ -6811,7 +6824,7 @@ let drive_root_output ?(split_bytes = false) ?(filter_omitted = false) runtime f (fun value -> Worker_pure_data.{ value; revision = "root-1"; depth = 0; parent = page }) (if filter_omitted then List.filter (fun (value:Worker_pure_data.block_record)->value.block.title<>"__pbt-omitted-root__") selected else selected) : Worker_pure_data.tree_member list)) ~next:(next_cursor))) - |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Preview_children parent;_} as query));_})-> + |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(budget,(Read.Timeline_read {query=Read.Timeline.Preview_children {parent;_};_} as query));_})-> let cursor=fixture_cursor budget query in let limit=Read.For_worker.read_budget_maximum_items budget in (match Production_runtime.worker_read runtime request with @@ -8418,7 +8431,7 @@ let test_prefix_preserves_reconciliation ~resync stage () = 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;_};_}) -> + | 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" @@ -8945,7 +8958,7 @@ let test_initial_reconciliation_restarts_prefix () = match Worker_producer.transport runtime request with |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(_,Read.Timeline_read {query=Read.Timeline.Roots _;_});_})-> request - |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(_,Read.Timeline_read {query=Read.Timeline.Dates {from_day=sealed_from_day;through_day=sealed_through_day};_});_})-> + |Ok(Worker_producer.S.Coordination_query{read=Read.Read_query(_,Read.Timeline_read {query=Read.Timeline.Dates {from_day=sealed_from_day;through_day=sealed_through_day;_};_});_})-> let from_day=Read.For_worker.journal_day_value sealed_from_day in let through_day=Read.For_worker.journal_day_value sealed_through_day in let items=if from_day<=day && day<=through_day then @@ -9329,7 +9342,7 @@ let test_timeline_root_filter () = let runtime = Runtime.create ~localtime:Unix.gmtime ~validate_session:Worker_producer.validate_session () in set_calendar runtime; - let fixture = root_fixture 0 65 0 in + let fixture = root_fixture 0 65 3 in let tag = (List.nth fixture.roots 61).block.uuid in let status = (List.nth fixture.roots 62).block.uuid in let roots = List.mapi (fun index (value : Worker_pure_data.block_record) -> @@ -9346,13 +9359,22 @@ let test_timeline_root_filter () = let actual = List.concat_map (fun (day : Journal_graph_projection.day_feed) -> List.map (fun (entry : Journal_graph_projection.timeline_entry) -> Journal_model.id entry.block) day.entries) feed.days in Alcotest.(check (list string)) "only matching roots across sparse packets" - (List.map Graph.Uuid.to_string [tag;status]) actual + (List.map Graph.Uuid.to_string [tag;status]) actual; + let previews = List.concat_map (fun (day : Journal_graph_projection.day_feed) -> + List.map (fun (entry : Journal_graph_projection.timeline_entry) -> + List.map (fun (child : Journal_graph_projection.child_summary) -> child.block_id) + entry.child_summaries) day.entries) feed.days in + let expected = List.map (fun root -> + List.map (fun (child : Worker_pure_data.block_record) -> Graph.Uuid.to_string child.block.uuid) + (List.assoc root fixture.descendants)) [tag;status] in + Alcotest.(check (list (list string))) "matched roots publish ordinary children in order" expected previews ;; let () = Alcotest.run "journal graph runtime locality" - [ ("timeline filters", [Alcotest.test_case "sparse tag or status matches" `Quick test_timeline_root_filter; + [ ("timeline filters", [Alcotest.test_case "filtered roots hydrate references" `Quick test_filtered_root_reference; + Alcotest.test_case "sparse tag or status matches" `Quick test_timeline_root_filter; Alcotest.test_case "skipped day matches before empty publication" `Quick (fun () -> test_filtered_empty_skips_point_proofs false); Alcotest.test_case "skipped day matches after empty publication" `Quick (fun () -> test_filtered_empty_skips_point_proofs true)]) ; ( "status recovery" diff --git a/test/logseq_db_worker_application_integration_test.ml b/test/logseq_db_worker_application_integration_test.ml index 891c3243..ba06f626 100644 --- a/test/logseq_db_worker_application_integration_test.ml +++ b/test/logseq_db_worker_application_integration_test.ml @@ -199,7 +199,7 @@ let seed_visible_block ?(record = record) runtime = let check = Read_fixture.receive runtime preview (fun (Read.Read_query (budget, query)) -> match query with - | Read.Timeline_read { query = (Read.Timeline.Preview_children parent as timeline); _ } -> + | Read.Timeline_read { query = (Read.Timeline.Preview_children {parent;_} as timeline); _ } -> Alcotest.(check bool) "Timeline preview parent" true (Graph.Uuid.equal parent record.block.uuid); Read.For_worker.answer budget query (Ok (Ok (timeline_packet budget timeline []))) From 6d2b5a529a5c964c26f69f400df00e30cbac41a4 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Thu, 26 Nov 2026 19:42:48 +0800 Subject: [PATCH 12/14] Reuse verified date-only Timeline prefixes --- app/journal_graph_feed_plan.ml | 18 +++---- test/journal_graph_runtime_locality_test.ml | 55 +++++++++++++++++++++ 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/app/journal_graph_feed_plan.ml b/app/journal_graph_feed_plan.ml index 58506d2d..680cad8e 100644 --- a/app/journal_graph_feed_plan.ml +++ b/app/journal_graph_feed_plan.ml @@ -186,7 +186,7 @@ let set_filter t ~tags ~statuses ~days = t.days <- days) ;; -let filtered t = t.tags <> [] || t.statuses <> [] || Option.is_some t.days +let has_membership_filter t = t.tags <> [] || t.statuses <> [] let timeline_uuid value = match Graph.Uuid.of_string value with @@ -241,7 +241,7 @@ let make_root_batch t ~ports owner ~page_uuid (page : Projection.page) cursor li min limit (max 1 (refresh.refresh_prefix_limit - Rrbvec.length refresh.refresh_entries)) | _ -> limit in (match owner with - | Feed_roots scan when filtered t && scan.root_start_day = None -> () + | Feed_roots scan when has_membership_filter t && scan.root_start_day = None -> () | _ -> Hashtbl.replace t.root_page_limits page.id (max limit (Option.value ~default:1 (Hashtbl.find_opt t.root_page_limits page.id))); ports.retain_root_interest page ~minimum_limit:limit); @@ -526,7 +526,7 @@ let check t ~ports action = let validate_retained t ~ports ~request_generation ~refresh = if not (has_retained t) then empty else ( t.window_epoch <- Int64.succ t.window_epoch; - check t ~ports (Window {request_generation;refresh;filtered=filtered t})) + check t ~ports (Window {request_generation;refresh;filtered=has_membership_filter t})) ;; let rec next_feed_batch ?(verified=false) t ~ports scan = @@ -807,7 +807,7 @@ let start_feed_scan t ~ports ~cursor ~root_limit ~day_limit ~request_generation ; root_through_day = through_day ; root_proofs = Hashtbl.create 16 ; root_retries = 0 - ; root_reuse = reuse && not (filtered t) + ; root_reuse = reuse && not (has_membership_filter t) ; root_generation = request_generation ; root_continued = Option.exists (fun (_, cursor) -> Option.is_some cursor) after ; root_start_day = start_day @@ -904,7 +904,7 @@ let receive_root_tree t ~ports batch (packet : Worker_pure_data.tree_member Pagi let todo = Rrbvec.filter (fun (m : Projection.tree_member) -> List.mem (Graph.Uuid.to_string m.block.uuid) ids) members in match batch.root_owner with - | Feed_roots scan when filtered t && Rrbvec.is_empty todo + | Feed_roots scan when has_membership_filter t && Rrbvec.is_empty todo && scan.root_start_day = None && not (Rrbvec.exists (fun (day : day_feed) -> day.page.id = batch.root_page.id) scan.root_days) -> (match next_cursor with @@ -916,7 +916,7 @@ let receive_root_tree t ~ports batch (packet : Worker_pure_data.tree_member Pagi scan.root_date_boundary <- Some batch.root_page.day; next_feed_batch t ~ports scan) | _ -> - if filtered t && not (Rrbvec.is_empty todo) then ( + if has_membership_filter t && not (Rrbvec.is_empty todo) then ( let id = batch.root_page.id in Hashtbl.replace t.root_page_limits id (max batch.root_limit (Option.value ~default:1 (Hashtbl.find_opt t.root_page_limits id))); @@ -1053,7 +1053,7 @@ let restart_dates t ~ports scan = ;; let with_coverage t ~ports scan receipt accept = - if not (filtered t) then accept () else + if not (has_membership_filter t) then accept () else match Paging.coverage receipt with | None -> scan_failure scan "Filtered Timeline read returned no coverage witness." | Some proof -> @@ -1230,7 +1230,7 @@ let receive : type a. ?session:Worker.session -> t -> ports:ports | Check validation, Worker.Timeline_check _, checked -> receive_check t ~ports validation checked | Root_dates (scan, params), Worker.Timeline_read {query=Paging.Dates _;_}, Ok packet -> with_coverage t ~ports scan packet.receipt (fun () -> - if not (filtered t) then Hashtbl.replace scan.root_proofs + if not (has_membership_filter t) then Hashtbl.replace scan.root_proofs (Dates_scope (params.from_day, params.through_day)) (Paging.Receipt packet.receipt); let items = packet.items in @@ -1303,7 +1303,7 @@ let receive : type a. ?session:Worker.session -> t -> ports:ports else next_feed_batch t ~ports scan)) | Root_today (scan, params), Worker.Timeline_read {query=Paging.Dates _;_}, Ok packet -> with_coverage t ~ports scan packet.receipt (fun () -> - if not (filtered t) then Hashtbl.replace scan.root_proofs + if not (has_membership_filter t) then Hashtbl.replace scan.root_proofs (Dates_scope (params.from_day, params.through_day)) (Paging.Receipt packet.receipt); let items = packet.items in diff --git a/test/journal_graph_runtime_locality_test.ml b/test/journal_graph_runtime_locality_test.ml index 3a475d95..97df8a38 100644 --- a/test/journal_graph_runtime_locality_test.ml +++ b/test/journal_graph_runtime_locality_test.ml @@ -8572,6 +8572,60 @@ let test_dates_change_preserves_retained_root_prefix () = | _ -> false) seen)) ;; +let test_rolling_dates_refresh_only_invalidated_roots () = + let runtime = Runtime.create ~localtime:Unix.gmtime () in + set_calendar ~clock:1_790_726_400. runtime; + let fixture index day count = + let f = root_fixture index count 0 in + {f with owner={f.owner with kind=Journal_page {journal_day=day}}} in + let today = fixture 0 20260930 1 + and changed_day = fixture 1 20260929 1 + and recent = fixture 2 20260920 1 + and empty_day = fixture 3 20260820 0 + and oldest = fixture 4 20260630 1 + and outside = fixture 5 20260629 1 + and future = fixture 6 20261001 1 in + let fixtures = [future; today; changed_day; recent; empty_day; oldest; outside] in + let rolling = Some (20260630, 20260930) in + let narrow = Some (20260917, 20260930) in + let apply generation ~tags ~statuses days = + Runtime.set_timeline_filter runtime ~tags ~statuses ~days; + drive_roots runtime fixtures (initial_roots runtime generation) in + let check_days label expected (feed : Journal_graph_projection.feed) = + Alcotest.(check (option int)) "Today remains prioritized" (Some 20260930) feed.prioritized_day; + Alcotest.(check (list int)) label expected + (List.map (fun (day : Journal_graph_projection.day_feed) -> day.page.day) feed.days) in + let initial, _ = apply 980L ~tags:[] ~statuses:[] rolling in + check_days "rolling month bounds and empty-day omission" [20260930;20260929;20260920;20260630] initial; + let refreshed, seen = drive_roots runtime fixtures + (changed runtime (window ~scopes:[Worker_pure_data.V2_journal_index_interest; + Worker_pure_data.V2_page_tree_interest changed_day.owner.uuid] ())) in + check_days "refresh preserves chronological window" [20260930;20260929;20260920;20260630] refreshed; + let ordinary_reads seen = List.filter_map (function + | Some (Runtime.Read {query=W.Timeline_read {query=W.Timeline.Roots page;_};_}) -> + Some (Graph.Uuid.to_string page) + | _ -> None) seen in + let rereads = ordinary_reads seen in + Alcotest.(check (list string)) "only the invalidated day rereads roots" + [Graph.Uuid.to_string changed_day.owner.uuid] (List.sort_uniq String.compare rereads); + Alcotest.(check bool) "reconciliation and feed assembly issue at most one root read each" + true (List.length rereads <= 2); + let assert_depth ~tags ~statuses = + let filtered, seen = apply 981L ~tags ~statuses narrow in + check_days "unmatched roots do not leak from retained dates" [] filtered; + Alcotest.(check bool) "membership criteria select depth-aware reads" true + (List.exists (function + | Some (Runtime.Read {query=W.Timeline_read {query=W.Timeline.Roots_through_grandchildren _;_};_}) -> true + | _ -> false) seen); + Alcotest.(check (list string)) "membership criteria do not reuse ordinary reads" [] (ordinary_reads seen) in + assert_depth ~tags:[unrelated_uuid] ~statuses:[]; + assert_depth ~tags:[] ~statuses:[unrelated_uuid]; + let time_only, _ = apply 982L ~tags:[] ~statuses:[] narrow in + check_days "time-only criteria exclude the old date" [20260930;20260929;20260920] time_only; + let restored, _ = apply 983L ~tags:[] ~statuses:[] rolling in + check_days "default restores older in-range rows only" [20260930;20260929;20260920;20260630] restored +;; + let pending_retained_assembly_check runtime fixture = let day = match fixture.owner.kind with Journal_page {journal_day} -> journal_day | _ -> assert false in let root = Runtime.submit runtime (Journal_graph_request.Load_day_blocks @@ -9586,6 +9640,7 @@ let () = Alcotest.test_case "proof failure is explicit" `Quick test_timeline_proof_failure_is_explicit; Alcotest.test_case "paging read error preserves Worker error" `Quick test_timeline_read_failed_preserves_worker_error; Alcotest.test_case "date changes preserve retained prefix" `Quick test_dates_change_preserves_retained_root_prefix; + Alcotest.test_case "rolling dates reread only invalidated roots" `Quick test_rolling_dates_refresh_only_invalidated_roots; Alcotest.test_case "cancel fences verification" `Quick (fun () -> test_verification_reply_is_fenced `Cancel); Alcotest.test_case "refresh fences verification" `Quick (fun () -> test_verification_reply_is_fenced `Refresh); Alcotest.test_case "reset fences verification" `Quick (fun () -> test_verification_reply_is_fenced `Reset); From b8f1e572b69596e1b0d9a2c45096dd5aae1308c9 Mon Sep 17 00:00:00 2001 From: rcmerci Date: Thu, 26 Nov 2026 19:42:48 +0800 Subject: [PATCH 13/14] Batch wide Timeline continuation scans within a raw candidate budget --- logseq_overlay_db/lib/database.ml | 28 +++++--- logseq_overlay_db/test/test_overlay_reads.ml | 70 ++++++++++++++++++++ 2 files changed, 89 insertions(+), 9 deletions(-) diff --git a/logseq_overlay_db/lib/database.ml b/logseq_overlay_db/lib/database.ml index 34ff0f0b..17b60f89 100644 --- a/logseq_overlay_db/lib/database.ml +++ b/logseq_overlay_db/lib/database.ml @@ -4627,7 +4627,7 @@ let timeline_member_offset scope version = function | _ -> Error (Types.Invalid_read_request "timeline member position belongs to another query")) ;; -let timeline_direct_candidates ~truncate snapshot parent = +let timeline_direct_candidates ?(charge = fun _ -> ()) ~truncate snapshot parent = let database = Option.get snapshot.authoritative_database in let cache = { hydration = hydration_cache ~index_idents:false database @@ -4665,6 +4665,7 @@ let timeline_direct_candidates ~truncate snapshot parent = Hashtbl.length identities <= maximum_cursor_offset with Exit -> false in + charge !examined; if not (complete || truncate) then None else Some (Hashtbl.to_seq_values identities |> Rrbvec.of_seq |> Rrbvec.sort Graph.Uuid.compare @@ -4745,17 +4746,20 @@ let get_timeline_roots_through_grandchildren snapshot ~page ~tags ~statuses ~lim | _ -> invalid) | _ -> invalid) in let ordinary_steps = 16 and wide_steps = 256 in - let wide = ref false and materialized = ref 0 in + let wide = ref false and examined_total = ref 0 in + let candidate_budget = (3 * maximum_cursor_offset) + wide_steps in + let exception Candidate_budget_spent in let context = lazy (read_context snapshot) in let read cache parent offset = let candidates = match !cache with | Some (previous, result) when Graph.Uuid.equal previous parent -> result | _ -> - let result = timeline_direct_candidates ~truncate:true snapshot parent in - Option.iter (fun candidates -> - let count = Rrbvec.length candidates in - wide := !wide || count = maximum_cursor_offset; - materialized := !materialized + count) result; + if !examined_total + maximum_cursor_offset > candidate_budget then + raise_notrace Candidate_budget_spent; + let charge examined = + wide := !wide || examined = maximum_cursor_offset; + examined_total := !examined_total + examined in + let result = timeline_direct_candidates ~charge ~truncate:true snapshot parent in cache := Some (parent, result); result in match candidates with @@ -4773,9 +4777,11 @@ let get_timeline_roots_through_grandchildren snapshot ~page ~tags ~statuses ~lim || match record.task_status with | Some (Status_uuid uuid) -> List.exists (Graph.Uuid.equal uuid) statuses | Some (Legacy_status_ident _) | None -> false in + let resume = ref ([], root, child, grandchild) in let rec scan fuel remaining items root child grandchild = + resume := (items, root, child, grandchild); if remaining = 0 || fuel = 0 - || (fuel <= wide_steps - ordinary_steps && not !wide) || !materialized >= 2 * maximum_cursor_offset + || (fuel <= wide_steps - ordinary_steps && not !wide) then Ok (List.rev items, Some (position root child grandchild)) else let* item, more_roots = read roots_cache page root in @@ -4808,7 +4814,11 @@ let get_timeline_roots_through_grandchildren snapshot ~page ~tags ~statuses ~lim | Some item when Graph.Uuid.equal item.block.block.page page && matches item.block -> hit () | _ when more -> scan (fuel - 1) remaining items root child (grandchild + 1) | _ -> advance_child () in - with_snapshot_read snapshot (fun _ -> scan wide_steps limit [] root child grandchild) + with_snapshot_read snapshot (fun _ -> + try scan wide_steps limit [] root child grandchild with + | Candidate_budget_spent -> + let items, root, child, grandchild = !resume in + Ok (List.rev items, Some (position root child grandchild))) ;; (* Writes own invalidation under the owner lock. Dependency cursors are lazy; diff --git a/logseq_overlay_db/test/test_overlay_reads.ml b/logseq_overlay_db/test/test_overlay_reads.ml index 1c7c8572..c8164861 100644 --- a/logseq_overlay_db/test/test_overlay_reads.ml +++ b/logseq_overlay_db/test/test_overlay_reads.ml @@ -1706,6 +1706,75 @@ let timeline_filter_parent_cap database = "wide preview position survived a change to the depth witness") ;; +let timeline_filter_wide_continuations database = + let behavior = "wide root and child scans make bounded packet progress" in + let module J = Transit_core.Json in + let id = T.mutation_uuid in + let lookup n = T.status_lookup (id n) in + let create n fields = + List.map (fun (key, value) -> T.status_add (J.Int (31000 + n)) key value) + (("block/uuid", J.Uuid (Graph.Uuid.to_string (id n))) :: fields) in + let page n = create n ["block/title", J.String (string_of_int n); + "block/name", J.String (string_of_int n)] in + let block n parent = create n + ["block/title", J.String (string_of_int n); "block/parent", lookup parent; + "block/page", lookup 1; "block/order", J.String (Printf.sprintf "%06d" n)] in + let tag n selected = T.status_add (lookup n) "block/tags" (lookup selected) in + let cursor = ref 0 in + let apply operations = + incr cursor; + T.apply_test_transaction database ~cursor:!cursor operations in + apply (page 1 @ page 2 @ page 3 @ page 4 + @ [T.status_add (lookup 1) "block/journal-day" (J.Int 20261101)]); + let wide start parent = + for batch = 0 to 20 do + let offset = batch * 500 in + apply (List.concat_map (fun i -> block (start + offset + i) parent) + (List.init (min 500 (10_001 - offset)) Fun.id)) + done in + wide 100 1; + wide 20_100 100; + apply [tag 30_099 2; tag 101 2; tag 101 3; tag 30_100 4; tag 10_100 4]; + let with_snapshot f = + let snapshot = Database.current_snapshot database |> T.require_ok ~behavior in + Fun.protect ~finally:(fun () -> Database.release_snapshot snapshot) (fun () -> f snapshot) in + let read snapshot selected after = Database.get_timeline_roots_through_grandchildren snapshot + ~page:(id 1) ~tags:(List.map id selected) ~statuses:[] ~limit:1 ~after in + let ids = List.map (fun (item : Types.tree_member) -> + T.require (item.depth = 0 && item.parent = id 1) "descendant was promoted"; + item.block.block.uuid) in + let through_another_root snapshot selected expected = + let rec collect packets after hits = + T.require (packets < 48) "did not reach second root in the first %d packets" packets; + let items, next = read snapshot selected after |> T.require_ok ~behavior in + let hits = hits @ ids items in + if List.mem (id 101) hits then ( + Printf.printf "second root, tag %d: %d packets\n%!" (List.hd selected) (packets + 1); + T.require (hits = expected) "wrong ordered roots before second root") + else ( + T.require (Option.is_some next && next <> after) "continuation ended or stalled"; + collect (packets + 1) next hits) in + collect 0 None [] in + with_snapshot (fun pinned -> + let first, position = read pinned [2] None |> T.require_ok ~behavior in + T.require (first = [] && Option.is_some position) "expected sparse first packet"; + through_another_root pinned [2] [id 100; id 101]; + through_another_root pinned [3] [id 101]; + let rec collect_cap packets after = + T.require (packets < 90) "cap scan did not terminate"; + let items, next = read pinned [4] after |> T.require_ok ~behavior in + T.require (items = []) "a raw candidate past the parent cap matched"; + match next with None -> () | Some _ -> collect_cap (packets + 1) next in + collect_cap 0 None; + apply [tag 20_100 2]; + with_snapshot (fun latest -> + T.require (read latest [2] position = Error Types.Stale_read_cursor) "old continuation stayed valid"; + let items, _ = read latest [2] None |> T.require_ok ~behavior in + T.require (ids items = [id 100]) "fresh snapshot missed new early match"); + let items, _ = read pinned [2] None |> T.require_ok ~behavior in + T.require (items = []) "pinned snapshot observed later write") +;; + let timeline_overlay_roots_follow_remote_page_metadata database = let behavior = "timeline overlay roots follow remote page metadata" in let module J = Transit_core.Json in @@ -1892,6 +1961,7 @@ let cases = ; T.database_case "timeline overlay roots follow remote page metadata" timeline_overlay_roots_follow_remote_page_metadata ; T.database_case "timeline filter depth and moves" timeline_filter_depth ; T.database_case "timeline filter per-parent cap" timeline_filter_parent_cap + ; T.database_case "timeline wide continuation progress" timeline_filter_wide_continuations ; T.database_case "timeline remote scopes cover metadata moves and ABA" timeline_remote_scopes_cover_metadata_moves_and_aba ; T.database_case "timeline local scope versions bind payload and snapshots" timeline_scopes_follow_local_payload_and_snapshot ; T.database_case "timeline direct paging survives unrelated scopes" timeline_pages_continue_across_unrelated_scopes From 7e5b4d8b610cd00ed541a9c65f9092dc923cd03f Mon Sep 17 00:00:00 2001 From: rcmerci Date: Thu, 26 Nov 2026 20:32:53 +0800 Subject: [PATCH 14/14] Keep Timeline settlement and draft fault fixtures deterministic --- logseq_overlay_db/test/test_overlay_sync.ml | 45 ++++++++++++--------- test/application_view_test.ml | 27 +++++++++++-- 2 files changed, 50 insertions(+), 22 deletions(-) diff --git a/logseq_overlay_db/test/test_overlay_sync.ml b/logseq_overlay_db/test/test_overlay_sync.ml index 651e7b47..15fa11ca 100644 --- a/logseq_overlay_db/test/test_overlay_sync.ml +++ b/logseq_overlay_db/test/test_overlay_sync.ml @@ -1237,9 +1237,11 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database let page=T.mutation_uuid 7790 and root_uuid=T.mutation_uuid 7791 and child_uuid=T.mutation_uuid 7792 in let task = T.uuid "00000002-1282-1814-5700-000000000000" in let plain_uuid = T.mutation_uuid 7796 in - let root:Types.append_node={uuid=root_uuid;title="Atomic wire root";task_status=Some(T.status_uuid 2); + let root_status = if remote_day then None else Some (T.status_uuid 2) in + let child_status = if remote_day then None else Some (T.status_uuid 3) in + let root:Types.append_node={uuid=root_uuid;title="Atomic wire root";task_status=root_status; children=Rrbvec.of_list - [{uuid=child_uuid;title="Atomic wire child";task_status=Some(T.status_uuid 3);children=Rrbvec.empty}; + [{uuid=child_uuid;title="Atomic wire child";task_status=child_status;children=Rrbvec.empty}; {uuid=plain_uuid;title="Plain child";task_status=None;children=Rrbvec.empty}]} in let check_tags stage = let snapshot = Database.current_snapshot database |> T.require_ok ~behavior in @@ -1257,20 +1259,24 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database ~expected mutation |> T.require_ok ~behavior in let proof=Database.commit_local_intent database intent |> T.require_ok ~behavior in let local=Database.intent_commit_outcome proof in + let earlier_root_uuid = T.mutation_uuid 7797 and tail_root_uuid = T.mutation_uuid 7795 in let resolved_page=if not remote_day then page else ( let module J=Transit_core.Json in let web=T.mutation_uuid 7794 in - let page_entity=J.String "remote-web-day" and child_entity=J.String "remote-first-entry" in + let page_entity=J.String "remote-web-day" in let add_page attribute value=T.status_add page_entity attribute value in - let add_child attribute value=T.status_add child_entity attribute value in + let remote_root uuid title order = + let add = T.status_add (J.String title) in + [add "block/uuid" (J.Uuid (Logseq_db_types.Graph_types.Uuid.to_string uuid)); + add "block/title" (J.String title); add "block/parent" page_entity; + add "block/page" page_entity; add "block/order" (J.String order); + add "logseq.property/status" (T.status_lookup (T.status_uuid 2))] in T.apply_test_transaction database ~cursor:2 - [add_page "block/uuid" (J.Uuid(Logseq_db_types.Graph_types.Uuid.to_string web)); - add_page "block/title" (J.String "Web day");add_page "block/name" (J.String "web-remote-day"); - add_page "block/journal-day" (J.Int 20261102); - add_child "block/uuid" (J.Uuid(Logseq_db_types.Graph_types.Uuid.to_string(T.mutation_uuid 7795))); - add_child "block/title" (J.String "Remote first entry");add_child "block/parent" page_entity; - add_child "block/page" page_entity;add_child "block/order" (J.String "a9"); - add_child "logseq.property/status" (T.status_lookup (T.status_uuid 2))]; + ([add_page "block/uuid" (J.Uuid(Logseq_db_types.Graph_types.Uuid.to_string web)); + add_page "block/title" (J.String "Web day");add_page "block/name" (J.String "web-remote-day"); + add_page "block/journal-day" (J.Int 20261102)] + @ remote_root earlier_root_uuid "Remote first entry" "a8" + @ remote_root tail_root_uuid "Remote tail entry" "a9"); let snapshot=Database.current_snapshot database |> T.require_ok ~behavior in Fun.protect ~finally:(fun()->Database.release_snapshot snapshot)(fun()-> T.require(match Database.get_outline_blocks snapshot [root_uuid] |> T.require_ok ~behavior with @@ -1310,19 +1316,19 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database Fun.protect ~finally:(fun () -> Database.release_snapshot snapshot) (fun () -> use snapshot) in if not remote_day then settle () else with_snapshot (fun before -> - let read snapshot after = Database.get_timeline_roots_through_grandchildren snapshot - ~page:resolved_page ~tags:[] ~statuses:[T.status_uuid 2] ~limit:1 ~after in + let read ?(limit=1) snapshot after = Database.get_timeline_roots_through_grandchildren snapshot + ~page:resolved_page ~tags:[] ~statuses:[T.status_uuid 2] ~limit ~after in let first, next = read before None |> T.require_ok ~behavior in let ids = List.map (fun (item : Types.tree_member) -> item.block.block.uuid) in - T.require (ids first = [T.mutation_uuid 7795] && Option.is_some next) + T.require (ids first = [earlier_root_uuid] && Option.is_some next) "accepted overlay must yield a real filtered continuation"; - let suffix = read before next |> T.require_ok ~behavior in - T.require (ids (fst suffix) = [root_uuid] && snd suffix = None) "wrong overlay suffix"; + let suffix = read ~limit:2 before next |> T.require_ok ~behavior in + T.require (ids (fst suffix) = [tail_root_uuid] && snd suffix = None) "wrong overlay suffix"; let version snapshot scope = Database.timeline_scope_version snapshot scope |> T.require_ok ~behavior in let roots snapshot = Database.get_timeline_roots snapshot ~page:resolved_page ~limit:3 ~after:None |> T.require_ok ~behavior in settle (); - T.require (read before next = Ok suffix) "settlement changed a retained snapshot"; + T.require (read ~limit:2 before next = Ok suffix) "settlement changed a retained snapshot"; with_snapshot (fun after -> T.require (roots before = roots after) "settlement changed ordinary root DTOs"; List.iter (fun scope -> @@ -1333,7 +1339,7 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database | Error Stale_read_cursor -> () | _ -> Alcotest.fail "authoritative settlement accepted the overlay continuation"); let fresh, next = read after None |> T.require_ok ~behavior in - T.require (fresh = first && Option.is_some next && read after next = Ok suffix) + T.require (fresh = first && Option.is_some next && read ~limit:2 after next = Ok suffix) "fresh authoritative prefix and continuation changed logical results")); if not remote_day then check_tags "authoritative echo"; let snapshot=Database.current_snapshot database |> T.require_ok ~behavior in @@ -1345,7 +1351,8 @@ let atomic_append_submits_and_replays_complete_tree ?(remote_day=false) database | [Present_block{value=root;_};Present_block{value=child;_}]-> T.require(root.block.parent=resolved_page && child.block.parent=root_uuid && child.block.page=resolved_page) "echo changed atomic tree ownership"; - T.require(root.task_status=Some(Status_uuid(T.status_uuid 2)) && child.task_status=Some(Status_uuid(T.status_uuid 3))) + T.require(root.task_status=Option.map (fun uuid -> Types.Status_uuid uuid) root_status + && child.task_status=Option.map (fun uuid -> Types.Status_uuid uuid) child_status) "echo lost atomic statuses" | _->Alcotest.fail "echo lost atomic blocks"); let sync=Database.inspect_sync database |> T.require_ok ~behavior in diff --git a/test/application_view_test.ml b/test/application_view_test.ml index 6829be44..5eebac19 100644 --- a/test/application_view_test.ml +++ b/test/application_view_test.ml @@ -8883,9 +8883,30 @@ let () = Fun.protect ~finally:(fun()->remove support) (fun()-> let before_capture_send () = let owned=Filename.concat support "JournalDrafts-v1" in - let account=Filename.concat owned (Array.get(Sys.readdir owned)0) in - let manifest=Filename.concat account "state.json" in - Unix.unlink manifest;Unix.mkdir manifest 0o700 in + let deadline = Unix.gettimeofday () +. 5. in + let rec await_picker_checkpoint () = + let checkpoint = + if not (Sys.file_exists owned) then None else + match Sys.readdir owned with + | [| account |] -> + let manifest = Filename.concat (Filename.concat owned account) "state.json" in + if not (Sys.file_exists manifest) then None else + let open Yojson.Safe.Util in + let drafts = Yojson.Safe.from_file manifest |> member "drafts" |> to_list in + if List.exists (fun draft -> + List.map (fun asset -> asset |> member "title" |> to_string) + (draft |> member "assets" |> to_list) + = ["First attachment"; "Second attachment"]) drafts + then Some manifest else None + | _ -> None in + match checkpoint with + | Some manifest -> manifest + | None when Unix.gettimeofday () < deadline -> + Unix.sleepf 0.001; + await_picker_checkpoint () + | None -> Alcotest.fail "picker draft checkpoint was not published" in + let manifest = await_picker_checkpoint () in + Unix.unlink manifest; Unix.mkdir manifest 0o700 in try run_favorites_native_visibility ~single_graph_shape:true ~support_directory:support ~check_capture_imports:true ~before_capture_send ~check_draft_write_failure:true ()