From 020b914658c27f607ce52c17af8b958bc4c8f2db Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Fri, 23 Oct 2026 01:07:33 +0800 Subject: [PATCH] refactor: own resumable layout drafts in explicit host work objects --- README.md | 3 + src/README.md | 3 + src/api.rs | 3 + src/source_layout.rs | 184 +++++++++++++++++++++++++++++++++---------- 4 files changed, 150 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 71fcd68..7397d6d 100644 --- a/README.md +++ b/README.md @@ -500,3 +500,6 @@ When an occurrence's cross-axis constraint changes during settling, its preferre The source layout driver now uses Aster's resumable read-only call API with a soft quantum of 256 instructions. Pauses retain the same VM frames, operand/local roots, return contracts and read tracking; total instruction/frame limits still apply across slices. ui.stats().layoutSlices counts slices in the most recent solve (native fast path: 1). The worker currently resumes Pending immediately after yielding its OS time slice. Parking the solve across worker turns, scheduling other work and handling newer inputs before completion are not implemented yet. Native callbacks are not preempted. Only the completed settled frame is published. + + +source_layout::start now returns either Complete(Draft) or Pending(Work). The host-owned Work retains the unpublished frame, derived runtime/cache snapshots, convergence plan and prepare root without borrowing caller frame/cache variables. Work::resume consumes the saved job and advances the same VM continuation; Work::cancel closes that continuation and releases the prepare root without merging a draft. A second start is rejected while any read-only execution is active. Every pending Work must be resumed or explicitly cancelled with its owning VM; dropping it is not cancellation. The current layout_frame adapter still drains jobs synchronously. Mount preparation/lifecycle cancellation and parking jobs in the execution worker remain unfinished. diff --git a/src/README.md b/src/README.md index 33096fa..a633f5f 100644 --- a/src/README.md +++ b/src/README.md @@ -152,3 +152,6 @@ When an occurrence's cross-axis constraint changes during settling, its preferre The source layout driver now uses Aster's resumable read-only call API with a soft quantum of 256 instructions. Pauses retain the same VM frames, operand/local roots, return contracts and read tracking; total instruction/frame limits still apply across slices. ui.stats().layoutSlices counts slices in the most recent solve (native fast path: 1). The worker currently resumes Pending immediately after yielding its OS time slice. Parking the solve across worker turns, scheduling other work and handling newer inputs before completion are not implemented yet. Native callbacks are not preempted. Only the completed settled frame is published. + + +source_layout::start now returns either Complete(Draft) or Pending(Work). The host-owned Work retains the unpublished frame, derived runtime/cache snapshots, convergence plan and prepare root without borrowing caller frame/cache variables. Work::resume consumes the saved job and advances the same VM continuation; Work::cancel closes that continuation and releases the prepare root without merging a draft. A second start is rejected while any read-only execution is active. Every pending Work must be resumed or explicitly cancelled with its owning VM; dropping it is not cancellation. The current layout_frame adapter still drains jobs synchronously. Mount preparation/lifecycle cancellation and parking jobs in the execution worker remain unfinished. diff --git a/src/api.rs b/src/api.rs index 1010b1c..ad023e3 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1130,6 +1130,9 @@ When an occurrence's cross-axis constraint changes during settling, its preferre The source layout driver now uses Aster's resumable read-only call API with a soft quantum of 256 instructions. Pauses retain the same VM frames, operand/local roots, return contracts and read tracking; total instruction/frame limits still apply across slices. ui.stats().layoutSlices counts slices in the most recent solve (native fast path: 1). The worker currently resumes Pending immediately after yielding its OS time slice. Parking the solve across worker turns, scheduling other work and handling newer inputs before completion are not implemented yet. Native callbacks are not preempted. Only the completed settled frame is published. + +source_layout::start now returns either Complete(Draft) or Pending(Work). The host-owned Work retains the unpublished frame, derived runtime/cache snapshots, convergence plan and prepare root without borrowing caller frame/cache variables. Work::resume consumes the saved job and advances the same VM continuation; Work::cancel closes that continuation and releases the prepare root without merging a draft. A second start is rejected while any read-only execution is active. Every pending Work must be resumed or explicitly cancelled with its owning VM; dropping it is not cancellation. The current layout_frame adapter still drains jobs synchronously. Mount preparation/lifecycle cancellation and parking jobs in the execution worker remain unfinished. + ## UI host object Positional arguments only: diff --git a/src/source_layout.rs b/src/source_layout.rs index 26b5d50..23c7ba4 100644 --- a/src/source_layout.rs +++ b/src/source_layout.rs @@ -686,15 +686,84 @@ impl NativeCallable for Prepare { } } -pub fn render( +/// An unpublished layout frame and derived caches. These are merged only after +/// the driver completes; they are not another copy of application state. +pub struct Draft { + pub frame: Frame, + pub runtime: LayoutRuntime, + pub cache: Cache, + pub reads: BTreeSet, +} + +#[must_use = "pending layout work must be resumed or cancelled with its owning VM"] +pub enum Progress { + Pending(Work), + Complete(Draft), +} + +/// Host-owned continuation. No borrowed frame/cache references cross a pause. +/// The prepare handle owns one root until completion or explicit cancellation. +pub struct Work { + state: Draft, + plan: Shared, + prepare: ObjectRef, + desktop: ObjectRef, + slices: usize, +} + +impl Work { + pub fn resume(mut self, vm: &mut Vm, slice: usize) -> Result { + self.slices += 1; + let progress = vm.resume_read_only_call(slice); + self.accept(vm, progress) + } + + pub fn cancel(self, vm: &mut Vm) -> Result<()> { + let cancelled = vm.cancel_read_only_call(); + let released = vm.release(self.prepare); + cancelled?; + released?; + Ok(()) + } + + fn accept( + self, + vm: &mut Vm, + progress: Result, + ) -> Result { + match progress { + Ok(endor_core::ExecutionProgress::Pending { .. }) => Ok(Progress::Pending(self)), + Ok(endor_core::ExecutionProgress::Complete { value, reads, .. }) => { + vm.release(self.prepare)?; + finish(vm, self, value, reads) + } + Err(error) => { + // An invalid quantum can fail without discarding the VM's + // continuation. No failed job may strand a read-only scope. + let diagnostic = crate::endor_host::runtime_error(vm, error); + self.cancel(vm)?; + Err(diagnostic) + } + } + } +} + +pub fn start( vm: &mut Vm, desktop: ObjectRef, mounts: Vec, root: Arc, - frame: &mut Frame, - runtime: &mut LayoutRuntime, - cache: &mut Cache, -) -> Result> { + mut state: Draft, + slice: usize, +) -> Result { + anyhow::ensure!(slice > 0, "layout slice must be positive"); + anyhow::ensure!( + !vm.has_suspended_call() && !vm.object_store().is_read_only(), + "cannot start layout while another read-only execution is active" + ); + let frame = &mut state.frame; + let runtime = &mut state.runtime; + let cache = &mut state.cache; cache.hits = 0; cache.misses = 0; let live: HashSet<_> = mounts.iter().copied().collect(); @@ -741,7 +810,8 @@ pub fn render( native.layout_version = frame.layout_version; runtime.version = frame.layout_version; *frame = native; - return Ok(BTreeSet::new()); + state.reads.clear(); + return Ok(Progress::Complete(state)); } anyhow::ensure!( nodes.len() == mounts.len() && nodes.len() == frame.mounts.len(), @@ -795,39 +865,33 @@ pub fn render( }, vec![desktop], ))?; - let mut slices = 1; - let result = (|| { - let mut progress = vm.start_read_only_call( - prepare, - &[], - endor_core::ExecutionLimits { - max_frames: 128, - max_instructions: 1_000_000, - }, - 256, - )?; - loop { - match progress { - endor_core::ExecutionProgress::Complete { value, reads, .. } => { - return Ok((value, reads)); - } - endor_core::ExecutionProgress::Pending { .. } => { - // The VM owns the continuation and keeps its read-only - // dependency scope intact. Worker-level parking follows. - std::thread::yield_now(); - slices += 1; - progress = vm.resume_read_only_call(256)?; - } - } - } - })(); - vm.release(prepare)?; - let (value, reads) = result.map_err(|error| crate::endor_host::runtime_error(vm, error))?; + let work = Work { + state, + plan, + prepare, + desktop, + slices: 1, + }; + let progress = vm.start_read_only_call( + prepare, + &[], + endor_core::ExecutionLimits { + max_frames: 128, + max_instructions: 1_000_000, + }, + slice, + ); + work.accept(vm, progress) +} + +fn finish(vm: &mut Vm, mut work: Work, value: Value, reads: Vec) -> Result { vm.release_value(value)?; - let mut plan = plan + let mut plan = work + .plan .lock() .map_err(|_| anyhow::anyhow!("layout plan poisoned"))?; - plan.runtime.slices = slices; + plan.runtime.slices = work.slices; + let frame = &mut work.state.frame; frame.commands.clear(); for (index, mount) in frame.mounts.iter_mut().enumerate() { let [x, y, width, height] = @@ -843,23 +907,57 @@ pub fn render( frame.commands.push(command); } } - *runtime = plan.runtime.clone(); - *cache = plan.cache.clone(); + work.state.runtime = plan.runtime.clone(); + work.state.cache = plan.cache.clone(); if !plan.custom { - return Ok(BTreeSet::new()); + work.state.reads.clear(); + return Ok(Progress::Complete(work.state)); } - let registry = match vm.get_attr(desktop, "types")? { + let registry = match vm.get_attr(work.desktop, "types")? { Value::Object(object) => object, _ => anyhow::bail!("missing type registry"), }; - Ok(reads + work.state.reads = reads .into_iter() .filter(|object| { - *object != desktop + *object != work.desktop && *object != registry && vm .object(*object) .is_ok_and(|object| !object.payload().as_any().is::()) }) - .collect()) + .collect(); + Ok(Progress::Complete(work.state)) +} + +pub fn render( + vm: &mut Vm, + desktop: ObjectRef, + mounts: Vec, + root: Arc, + frame: &mut Frame, + runtime: &mut LayoutRuntime, + cache: &mut Cache, +) -> Result> { + let state = Draft { + frame: frame.clone(), + runtime: runtime.clone(), + cache: cache.clone(), + reads: BTreeSet::new(), + }; + let mut progress = start(vm, desktop, mounts, root, state, 256)?; + loop { + match progress { + Progress::Pending(work) => { + std::thread::yield_now(); + progress = work.resume(vm, 256)?; + } + Progress::Complete(state) => { + *frame = state.frame; + *runtime = state.runtime; + *cache = state.cache; + return Ok(state.reads); + } + } + } }