Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 114 additions & 14 deletions crates/ui/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,43 @@ use engine::error::{AppError, StorageError};

use crate::inputs::Waker;

/// A frame: a call past it is named in the log of a debug build.
const SLOW_CALL_MS: u128 = 16;
/// What a call's line says before it answers, read on the UI thread as it is queued.
struct Call {
queue: &'static str,
/// The api function that asked: `notes::get_note`.
name: &'static str,
/// The action being applied, or none.
action: Option<u64>,
}

impl Call {
/// Once, as it answers: its outcome is `ok` or the error's code, never its detail.
fn answered<T>(&self, started: Instant, answer: &Result<T, AppError>) {
let Self { queue, name, action } = self;
let action = action.map_or_else(|| "-".to_owned(), |number| format!("#{number}"));
let took = started.elapsed().as_millis();
match answer {
Ok(_) => log::debug!("{queue} {action} {name} {took} ms ok"),
Err(error) => log::debug!("{queue} {action} {name} {took} ms {:?}", error.code),
}
}
}

/// `ui::api::notes::get_note::{{closure}}` is `notes::get_note`.
fn call_name<J>(job: &J) -> &'static str {
let full = std::any::type_name_of_val(job);
let name = full.strip_prefix("ui::api::").unwrap_or(full);
name.split("::{{closure}}").next().unwrap_or(name)
}

fn timed<T>(
call: Call,
job: impl FnOnce(&Engine) -> Result<T, AppError> + Send + 'static,
) -> impl FnOnce(&Engine) -> Result<T, AppError> + Send + 'static {
let name = std::any::type_name_of_val(&job);
move |engine| {
let started = Instant::now();
let answer = job(engine);
if cfg!(debug_assertions) && started.elapsed().as_millis() > SLOW_CALL_MS {
log::info!("{name} took {:?}", started.elapsed());
}
call.answered(started, &answer);
answer
}
}
Expand All @@ -42,6 +66,8 @@ pub struct Backend {
in_flight: Arc<InFlight>,
/// The person's actions applied in this session: the last one's number.
actions: AtomicU64,
/// The number of the one being applied; 0 between them.
applying: AtomicU64,
}

impl Backend {
Expand All @@ -57,13 +83,22 @@ impl Backend {
.enable_all()
.build()?;
let engine = Arc::new(Engine::new(paths, events, runtime.handle().clone()));
Ok(Self { engine, runtime, waker, in_flight: Arc::default(), actions: AtomicU64::new(0) })
let (actions, applying) = (AtomicU64::new(0), AtomicU64::new(0));
Ok(Self { engine, runtime, waker, in_flight: Arc::default(), actions, applying })
}

/// The number of the action about to be applied, from 1: what it asks of the core is said to
/// be its doing.
pub fn next_action(&self) -> u64 {
self.actions.fetch_add(1, Ordering::Relaxed) + 1
/// `apply` under the next action's number, from 1: the calls it queues are said to be its
/// doing.
pub fn as_action(&self, apply: impl FnOnce(u64)) {
let number = self.actions.fetch_add(1, Ordering::Relaxed) + 1;
self.applying.store(number, Ordering::Relaxed);
apply(number);
self.applying.store(0, Ordering::Relaxed);
}

fn call<J>(&self, queue: &'static str, job: &J) -> Call {
let action = Some(self.applying.load(Ordering::Relaxed)).filter(|number| *number != 0);
Call { queue, name: call_name(job), action }
}

pub fn engine(&self) -> &Arc<Engine> {
Expand All @@ -77,7 +112,7 @@ impl Backend {
) -> Pending<T> {
let (pending, answer) = self.pending();
// Queued here, on the caller's thread: a task would reach the queue in its own time.
let answered = engine::db::submit(&self.engine, timed(job));
let answered = engine::db::submit(&self.engine, timed(self.call("db", &job), job));
self.runtime.spawn(async move { answer.send(answered.await) });
pending
}
Expand All @@ -89,6 +124,7 @@ impl Backend {
) -> Pending<T> {
let (pending, answer) = self.pending();
let engine = Arc::clone(&self.engine);
let job = timed(self.call("compute", &job), job);
rayon::spawn(move || answer.send(job(&engine)));
pending
}
Expand All @@ -102,9 +138,12 @@ impl Backend {
let (pending, answer) = self.pending();
let engine = Arc::clone(&self.engine);
let handle = self.runtime.handle().clone();
let call = self.call("spawn", &job);
self.runtime.spawn(async move {
let result = handle.spawn(job(engine)).await;
answer.send(result.unwrap_or_else(|_| Err(unanswered())));
let started = Instant::now();
let result = handle.spawn(job(engine)).await.unwrap_or_else(|_| Err(unanswered()));
call.answered(started, &result);
answer.send(result);
});
pending
}
Expand Down Expand Up @@ -282,6 +321,67 @@ mod tests {
assert!(ctx.has_requested_repaint());
}

/// What `ui::backend` said, on any thread, of the calls named by `name`: a test's own path
/// names its calls alone.
fn calls_of(heard: &testing::Heard, name: &str) -> Vec<String> {
let ours = heard.lines().into_iter().filter(|line| line.target == "ui::backend");
ours.map(|line| line.text).filter(|text| text.contains(name)).collect()
}

/// `db #3 notes::get 2 ms ok` without its duration.
fn timeless(line: &str) -> String {
let words: Vec<&str> = line.split(' ').collect();
[&words[..3], &words[5..]].concat().join(" ")
}

#[test]
fn each_call_is_logged_as_it_answers_under_the_action_that_queued_it() {
let heard = testing::listen();
let (backend, _profile) = testing::backend();
let mut number = 0;

backend.as_action(|applied| {
number = applied;
drop(backend.db(|_| Ok(1)));
drop(backend.compute(|_| Ok(2)));
drop(backend.spawn(|_| async { Ok(3) }));
});
drop(backend.db(|_| Ok(4)));
backend.settle();

let test = "ui::backend::tests::each_call_is_logged_as_it_answers_under_the_action_that_queued_it";
let mut said: Vec<String> = calls_of(heard, test).iter().map(|line| timeless(line)).collect();
said.sort();
let mut wanted = [
format!("compute #{number} {test} ok"),
format!("db #{number} {test} ok"),
format!("db - {test} ok"),
format!("spawn #{number} {test} ok"),
];
wanted.sort();
assert_eq!(said, wanted);
assert!(calls_of(heard, test).iter().all(|line| line.split(' ').nth(4) == Some("ms")));
}

#[test]
fn a_call_is_named_by_its_api_function_and_a_failure_by_its_code_alone() {
const TITLE: &str = "sentinel-title-91d2";
let heard = testing::listen();
let (backend, _profile) = testing::backend();

drop(crate::api::notes::get(&backend, TITLE.to_owned()));
drop(backend.db(|_| Err::<(), AppError>(StorageError::File(TITLE.to_owned()).into())));
backend.settle();

let test = "ui::backend::tests::a_call_is_named_by_its_api_function_and_a_failure_by_its_code_alone";
let failed: Vec<String> = calls_of(heard, test).iter().map(|line| timeless(line)).collect();
assert_eq!(failed, [format!("db - {test} FileAccess")]);
let got: Vec<String> = calls_of(heard, " notes::get ").iter().map(|line| timeless(line)).collect();
assert!(got.contains(&"db - notes::get Locked".to_owned()), "{got:?}");
let lines = heard.lines();
assert!(lines.iter().all(|line| !line.text.contains(TITLE)), "the detail stays out of the log");
}

#[test]
fn an_answer_dropped_without_a_word_is_still_an_answer() {
let (backend, _profile) = testing::backend();
Expand Down
6 changes: 4 additions & 2 deletions crates/ui/src/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,8 +509,10 @@ impl AppState {
/// The person's action, numbered and logged, then applied: what the frame's loop and the
/// outside (the tray, a second launch) call. `apply` logs nothing: an action may apply another.
pub fn act(&mut self, action: Action, ctx: &egui::Context, backend: &Backend) {
action.log(backend.next_action());
self.apply(action, ctx, backend);
backend.as_action(|number| {
action.log(number);
self.apply(action, ctx, backend);
});
}

/// At the end of the frame, in the order the actions were pushed.
Expand Down
1 change: 1 addition & 0 deletions docs/architecture/backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ one after the other run in that order. Handing the job to a task that queued it
of them swap. A panic ends the process (D18), so no queue answers for one; an `Answer`
dropped without a word — a task dropped as the runtime stops — still answers `Unavailable`,
so **no `Pending` is ever left unanswered**. Dropping a `Pending` does not stop work begun on the database.
Every call, on any queue, is logged as it answers (→ "What the core was asked").

Creating or unlocking a library is a `spawn` that runs the vault's db job and then starts
`index::fill`, which fills the index a slice a job behind the gate. What the core says unasked
Expand Down
22 changes: 22 additions & 0 deletions docs/architecture/logs.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,28 @@ a drawing's picture —, is at `trace`, by the list `FREQUENT` beside `name`, so
reads as what the person did; `ui::action=trace` in `DEVNOTES_LOG` shows it. In a session's log, what
follows `#412` was done by that action or after it, and its number goes up by one each time.

## What the core was asked

Each call of the interface to the core is logged once, at `debug`, as it answers, under
`ui::backend`: its queue, the action that queued it, the `ui::api` function that asked, how long it
ran, and its outcome.

```text
2026-12-04 10:12:05.033 DEBUG [db] ui::backend: db #412 notes::get 2 ms ok
2026-12-04 10:12:05.348 DEBUG [devnotes-network] ui::backend: spawn #415 http::send 312 ms HttpTimeout
2026-12-04 10:12:06.001 DEBUG [db] ui::backend: db - notes::query 4 ms ok
```

`Backend::as_action` holds the number of the action being applied while `AppState::act` applies it:
a call queued then says `#412`, one queued outside an action (an answer adopted, a frame's own read)
says `-`. The name is the job's type, trimmed of `ui::api::` and of its closures; a call made
outside `ui::api` keeps its whole path. The duration is the job's own, without the wait in its
queue. The outcome is `ok` or the error's code alone: its detail may hold what was typed, and a
service function that fails says nothing more. A session thus reads as an action, then its calls.

No call is a warning for its duration alone: a large library makes the slowest ones slow on every
call, and a list of exceptions would be one more thing to keep.

## Changing the levels for one run

`DEVNOTES_LOG`, in `flexi_logger`'s syntax, replaces the levels for one run, in any build:
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ on the machine's GPU (`DEVNOTES_E2E_GPU`) and painting every frame (`DEVNOTES_E2
`e2e` flavour cannot be a release build, so that one runs at `CARGO_PROFILE_DEV_OPT_LEVEL=3`.
`app --features profiling` serves egui's frames to `puffin_viewer` (a debug build at
`CARGO_PROFILE_DEV_OPT_LEVEL=3`: a release build refuses it); `puffin_egui` stops at egui
0.33. A debug build logs every `Backend` database call past 16 ms.
0.33. Each call to the core is logged at `debug` with its duration (→ "What the core was asked").

⚠️ The budgets are for a four-core laptop on integrated graphics; this machine is Windows 11,
Ryzen 7 9800X3D, RTX 5070 Ti. A frame here is a CPU frame (pass and tessellation, the
Expand Down