feat: park idle task refresh and bound delivery to one callback per turn

This commit is contained in:
2026-10-23 01:50:56 +08:00
parent 5a1cf9d702
commit bd5c91ba99
6 changed files with 58 additions and 12 deletions
+3
View File
@@ -182,3 +182,6 @@ Cancellation checkpoints own explicit VM roots until restored or released. Initi
source_layout uses the same resumable node driver for trees over 64 occurrences even when measure/arrange are intrinsic. Small intrinsic trees retain LayoutRuntime::frame. The larger path keeps LayoutRuntime measurement caches and yields between node calls; structural extraction, bytecode preparation, a single node, settling and paint remain atomic.
Worker idle polls use ReplSession::poll_tasks_incremental with the current viewport map. Scheduler::poll accepts a checked 1..=64 work limit, counting both delivery and ineligible-task cancellation; idle uses one, synchronous compatibility uses 64. Once delivery begins layout, further tasks and window-command projection wait until the saved refresh completes. The viewport stamp allows cancellation of task-induced pending layout without repeating callback effects.
+11 -2
View File
@@ -563,7 +563,16 @@ impl Worker {
if runtime.has_pending_refresh() {
return Ok((None, Vec::new()));
}
let completed = runtime.poll_tasks()?;
let completed = if drain {
runtime.poll_tasks()?
} else {
runtime.poll_tasks_incremental(&viewports)?
};
if runtime.has_pending_refresh() {
// A complete earlier resize may publish; task effects and their
// native commands wait until the task's refresh has settled.
return Ok((resized, Vec::new()));
}
Ok((completed.or(resized), runtime.take_window_commands()?))
}));
let mut current = match namespace.write() {
@@ -1165,7 +1174,7 @@ source_layout::start now returns either Complete(Draft) or Pending(Work). The ho
UiBridge::begin_layout_frame/resume_layout_frame now expose PendingLayout around the source job. This bridge-level continuation also owns its target window, page snapshot, tab projection, viewport restoration and retained lifecycle hook root. Only the Complete branch projects scroll/focus, captures dependency versions, merges derived caches, commits Mount geometry and runs deferred hooks. Resume restores the saved window context, and failure releases hook roots. ReplSession uses this protocol through its saved refresh state. Viewport refresh supports cross-worker-turn scheduling and prepared-Mount rollback; callers must not drop a pending bridge layout as a substitute for cancellation.
Viewport refresh now advances through ReplSession's saved refresh state on worker idle turns. A turn advances one traversal stage or a 256-instruction layout quantum; a pending job shortens the next worker wait to 1 ms. Tasks/window commands and document publication wait for complete refresh. ui.stats().refreshYields reports cooperative idle returns. Mutating requests first drain the existing job, so they cannot run inside its read-only scope. Mutating requests are serialized; newer viewport targets coalesce by cancelling unpublished layout. Initial loads, explicit REPL/event refresh and task callbacks still drain synchronously; native Rust measurement/paint calls remain atomic.
Viewport refresh now advances through ReplSession's saved refresh state on worker idle turns. A turn advances one traversal stage or a 256-instruction layout quantum; a pending job shortens the next worker wait to 1 ms. Tasks/window commands and document publication wait for complete refresh. ui.stats().refreshYields reports cooperative idle returns. Mutating requests first drain the existing job, so they cannot run inside its read-only scope. Mutating requests are serialized; newer viewport targets coalesce by cancelling unpublished layout. Initial loads, explicit REPL/event refresh and task callback execution remains atomic; its idle-triggered layout yields across worker turns; native Rust measurement/paint calls remain atomic.
Runtime mutation entry points reject direct calls while refresh work is pending, before executing source or changing metadata; task polling defers. The API worker drains the saved refresh before accepting those mutations, keeping the runtime usable. Incremental refresh keeps the prior complete document map until a stable pass, including across window traversal boundaries where no VM read-only frame is currently active.
+30 -3
View File
@@ -792,6 +792,21 @@ impl ReplSession {
/// Deliver ready work on the owning VM worker, never from the GUI or a
/// provider thread. A failed callback stops the same shared fault domain.
pub fn poll_tasks(&mut self) -> Result<Option<RenderDocument>> {
self.poll_tasks_mode(None)
}
/// Idle delivery starts at most one callback, then parks its layout work.
pub fn poll_tasks_incremental(
&mut self,
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
) -> Result<Option<RenderDocument>> {
self.poll_tasks_mode(Some(viewports))
}
fn poll_tasks_mode(
&mut self,
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
) -> Result<Option<RenderDocument>> {
if self.has_pending_refresh() {
return Ok(None);
}
@@ -804,11 +819,23 @@ impl ReplSession {
}
let mut completed = false;
let result = (|| {
if self.bridge.poll_tasks(&mut self.candidate.vm)? == 0 {
let limit = if viewports.is_some() { 1 } else { 64 };
if self.bridge.poll_tasks(&mut self.candidate.vm, limit)? == 0 {
return Ok(None);
}
completed = true;
self.refresh_document()
if let Some(viewports) = viewports {
let progress = self.poll_refresh(true)?;
if let Some(work) = &mut self.refresh {
work.viewports = Some(viewports.clone());
}
Ok(match progress {
RefreshProgress::Pending => None,
RefreshProgress::Complete(document) => document.map(|document| *document),
})
} else {
self.refresh_document()
}
})();
if result.is_err() {
self.faulted = true;
@@ -816,7 +843,7 @@ impl ReplSession {
self.take_window_commands()?;
self.bridge.discard_pending(&mut self.candidate.vm)?;
}
if completed || result.is_err() {
if (completed || result.is_err()) && !self.has_pending_refresh() {
self.bridge
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
}
+6 -2
View File
@@ -399,7 +399,8 @@ pub struct Scheduler {
impl Scheduler {
/// Mutation boundaries collect unreachable owner/callback cycles before
/// this weak lookup. Idle timer polling does not rescan the entire heap.
pub fn poll(&self, vm: &mut Vm) -> Result<usize> {
pub fn poll(&self, vm: &mut Vm, limit: usize) -> Result<usize> {
anyhow::ensure!((1..=MAX_READY).contains(&limit), "invalid task poll limit");
let snapshot = self
.index
.lock()
@@ -408,6 +409,9 @@ impl Scheduler {
let now = Instant::now();
let mut work = 0;
for weak in snapshot {
if work >= limit {
break;
}
let Some(reference) = vm.upgrade(weak)? else {
continue;
};
@@ -428,7 +432,7 @@ impl Scheduler {
work += 1;
return finish(vm, reference, State::Cancelled);
}
if task.due > now || work >= MAX_READY {
if task.due > now {
return Ok(());
}
work += 1;
+2 -2
View File
@@ -1799,8 +1799,8 @@ fn project_tabs(
}
impl UiBridge {
pub fn poll_tasks(&self, vm: &mut Vm) -> Result<usize> {
self.tasks.poll(vm)
pub fn poll_tasks(&self, vm: &mut Vm, limit: usize) -> Result<usize> {
self.tasks.poll(vm, limit)
}
pub fn cancel_tasks(&self, vm: &mut Vm) -> Result<usize> {
self.tasks.cancel_all(vm)