feat: park PUT candidate layout while preserving the live runtime

This commit is contained in:
2026-10-23 10:52:23 +08:00
parent 799fe9f3c7
commit d521568d73
3 changed files with 131 additions and 43 deletions
+3
View File
@@ -539,3 +539,6 @@ The API worker now owns a pending HTTP request plus its scalar result while REPL
Complete-source candidates now separate one-time compilation/source execution from initial layout. load_incremental owns the isolated VM while its first layout is pending; the current live VM stays separate. Cancellation uses the same Mount checkpoint/continuation cleanup as later refresh. Synchronous load helpers remain for host regression coverage. This does not yet slice parsing, compilation, source execution, structural preparation or paint.
The API keeps the old runtime alongside a pending PUT candidate. Newer submissions cancel only the obsolete candidate; failures restore the published runtime's submission owner. Background epoch checks distinguish accepted replacements from DELETE revocation, so queued/superseded candidates do not destroy the previous live heap. Candidate resumption reads only the primary shell viewport, avoiding reuse of an old secondary window's dimensions for a new VM's resource with the same numeric ID. Success publishes the complete candidate document and commands together, then replaces the old runtime.
+3
View File
@@ -194,3 +194,6 @@ The API worker now owns a pending HTTP request plus its scalar result while REPL
Complete-source candidates now separate one-time compilation/source execution from initial layout. load_incremental owns the isolated VM while its first layout is pending; the current live VM stays separate. Cancellation uses the same Mount checkpoint/continuation cleanup as later refresh. Synchronous load helpers remain for host regression coverage. This does not yet slice parsing, compilation, source execution, structural preparation or paint.
The API keeps the old runtime alongside a pending PUT candidate. Newer submissions cancel only the obsolete candidate; failures restore the published runtime's submission owner. Background epoch checks distinguish accepted replacements from DELETE revocation, so queued/superseded candidates do not destroy the previous live heap. Candidate resumption reads only the primary shell viewport, avoiding reuse of an old secondary window's dimensions for a new VM's resource with the same numeric ID. Success publishes the complete candidate document and commands together, then replaces the old runtime.
+125 -43
View File
@@ -92,7 +92,7 @@ fn start_server_observed(
.name("tessera-endor-worker".into())
.spawn(move || {
let mut worker = Worker::default();
let mut pending: Option<(BuildRequest, Box<PendingInput>)> = None;
let mut pending: Option<(BuildRequest, PendingRequest)> = None;
loop {
if let Some((job, input)) = pending.take() {
match worker.resume_request(&job, input, &worker_namespace, &worker_notify) {
@@ -127,10 +127,10 @@ fn start_server_observed(
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
if worker.repl.as_ref().is_some_and(|(epoch, _)| {
if worker.repl.as_ref().is_some_and(|(epoch, runtime)| {
worker_namespace
.read()
.is_ok_and(|current| current.submission != *epoch)
.is_ok_and(|current| current.submission != *epoch && current.runtime_session != runtime.id)
}) {
worker.repl = None;
}
@@ -454,6 +454,12 @@ type HttpResponse = Response<std::io::Cursor<Vec<u8>>>;
type InputOutcome =
std::thread::Result<Result<(endor_host::ReplResult, Vec<crate::window::Command>)>>;
type CandidateOutcome = std::thread::Result<Result<(
endor_host::ReplSession,
crate::document::RenderDocument,
Vec<crate::window::Command>,
)>>;
struct PendingInput {
epoch: u64,
id: u64,
@@ -461,8 +467,13 @@ struct PendingInput {
result: endor_host::ReplResult,
}
enum PendingRequest {
Input(Box<PendingInput>),
Candidate(Box<endor_host::ReplSession>),
}
enum RequestProgress {
Pending(Box<PendingInput>),
Pending(PendingRequest),
Complete(HttpResponse),
}
@@ -588,7 +599,9 @@ impl Worker {
return;
};
if *owner != epoch {
self.repl = None;
if let Ok(current) = namespace.read() {
self.preserve_live_owner(&current);
}
return;
}
let id = runtime.id;
@@ -675,7 +688,7 @@ impl Worker {
notify: &Notify,
) -> RequestProgress {
if job.kind == RequestKind::Code {
return RequestProgress::Complete(self.replace_program(job, namespace, notify));
return self.begin_program_request(job, namespace, notify);
}
if job.kind == RequestKind::Expression {
return RequestProgress::Complete(build(job, namespace, notify));
@@ -902,12 +915,12 @@ impl Worker {
let faulted = session.is_faulted();
if session.has_pending_refresh() {
if let Ok(Ok((result, _))) = result {
return RequestProgress::Pending(Box::new(PendingInput {
return RequestProgress::Pending(PendingRequest::Input(Box::new(PendingInput {
epoch,
id,
event: event.is_some(),
result,
}));
})));
}
// A failed start must never leave a request waiting on a broken VM.
self.repl = None;
@@ -925,6 +938,19 @@ impl Worker {
}
fn resume_request(
&mut self,
job: &BuildRequest,
pending: PendingRequest,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> RequestProgress {
match pending {
PendingRequest::Input(input) => self.resume_input(job, input, namespace, notify),
PendingRequest::Candidate(runtime) => self.resume_candidate(job, runtime, namespace, notify),
}
}
fn resume_input(
&mut self,
job: &BuildRequest,
mut input: Box<PendingInput>,
@@ -967,7 +993,7 @@ impl Worker {
}));
let faulted = session.is_faulted();
let result = match resumed {
Ok(Ok(None)) => return RequestProgress::Pending(input),
Ok(Ok(None)) => return RequestProgress::Pending(PendingRequest::Input(input)),
Ok(Ok(Some((document, commands)))) => {
input.result.document = document;
Ok(Ok((input.result, commands)))
@@ -1083,46 +1109,104 @@ impl Worker {
}
}
fn replace_program(
/// An accepted PUT changes the submission, but does not revoke the old
/// runtime. DELETE clears runtime_session and does revoke it.
fn preserve_live_owner(&mut self, current: &NamespaceState) {
if let Some((epoch, runtime)) = &mut self.repl {
if current.runtime_session == runtime.id {
*epoch = current.submission;
} else {
self.repl = None;
}
}
}
fn begin_program_request(
&mut self,
job: &BuildRequest,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> Response<std::io::Cursor<Vec<u8>>> {
if namespace
.read()
.is_ok_and(|current| current.submission != job.submission)
{
return superseded(job.submission);
}
) -> RequestProgress {
let viewport = match namespace.read() {
Ok(current) if current.submission == job.submission => current.viewport,
Ok(current) => {
self.preserve_live_owner(&current);
return RequestProgress::Complete(superseded(job.submission));
}
Err(_) => return RequestProgress::Complete(error_response(StatusCode(500), "namespace lock poisoned")),
};
self.next_session = match self.next_session.checked_add(1) {
Some(id) => id,
None => return error_response(StatusCode(500), "session identities exhausted"),
None => return RequestProgress::Complete(error_response(StatusCode(500), "session identities exhausted")),
};
let id = self.next_session;
let result = catch_unwind(AssertUnwindSafe(|| {
let viewport = namespace
.read()
.map_err(|_| anyhow::anyhow!("namespace lock poisoned"))?
.viewport;
let (runtime, document) = if viewport.is_some() {
endor_host::ReplSession::load_with_viewport(
&job.source,
&job.namespace,
job.submission,
id,
viewport,
)?
} else {
endor_host::ReplSession::load(&job.source, &job.namespace, job.submission, id)?
};
let commands = runtime.take_window_commands()?;
Ok::<_, anyhow::Error>((runtime, document, commands))
let started = catch_unwind(AssertUnwindSafe(|| {
endor_host::ReplSession::load_incremental(&job.source, &job.namespace, job.submission, id, viewport)
}));
let result = match started {
Ok(Ok((runtime, None))) => return RequestProgress::Pending(PendingRequest::Candidate(Box::new(runtime))),
Ok(Ok((runtime, Some(document)))) => {
match runtime.take_window_commands() {
Ok(commands) => Ok(Ok((runtime, document, commands))),
Err(error) => Ok(Err(error)),
}
}
Ok(Err(error)) => Ok(Err(error)),
Err(panic) => Err(panic),
};
RequestProgress::Complete(self.finish_candidate(job, namespace, notify, id, result))
}
fn resume_candidate(
&mut self,
job: &BuildRequest,
mut runtime: Box<endor_host::ReplSession>,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> RequestProgress {
let viewports = match namespace.read() {
Ok(current) if current.submission == job.submission => {
// Secondary native resources still belong to the old VM. Only
// the primary shell's current viewport applies to a candidate.
current.viewport.map(|size| (crate::window::MAIN_WINDOW, size)).into_iter().collect()
}
Ok(current) => {
self.preserve_live_owner(&current);
return RequestProgress::Complete(superseded(job.submission));
}
Err(_) => return RequestProgress::Complete(error_response(StatusCode(500), "namespace lock poisoned")),
};
let id = runtime.id;
let resumed = catch_unwind(AssertUnwindSafe(|| -> Result<_> {
let document = runtime.resize_windows_incremental(&viewports, false)?;
if runtime.has_pending_refresh() {
return Ok(None);
}
let document = document.ok_or_else(|| anyhow::anyhow!("program did not publish a Page"))?;
Ok(Some((document, runtime.take_window_commands()?)))
}));
let result = match resumed {
Ok(Ok(None)) => return RequestProgress::Pending(PendingRequest::Candidate(runtime)),
Ok(Ok(Some((document, commands)))) => Ok(Ok((*runtime, document, commands))),
Ok(Err(error)) => Ok(Err(error)),
Err(panic) => Err(panic),
};
RequestProgress::Complete(self.finish_candidate(job, namespace, notify, id, result))
}
fn finish_candidate(
&mut self,
job: &BuildRequest,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
id: u64,
result: CandidateOutcome,
) -> HttpResponse {
let Ok(mut current) = namespace.write() else {
return error_response(StatusCode(500), "namespace lock poisoned");
};
if current.submission != job.submission {
self.preserve_live_owner(&current);
return superseded(job.submission);
}
match result {
@@ -1144,11 +1228,7 @@ impl Worker {
failed => {
// The candidate never mutated the displayed program's heap.
// Restore that program's event epoch when a replacement fails.
if let Some((epoch, runtime)) = &mut self.repl
&& current.document.frame.session == runtime.id
{
*epoch = job.submission;
}
self.preserve_live_owner(&current);
drop(current);
match failed {
Ok(Err(error)) => compile_error(error),
@@ -1369,13 +1449,13 @@ 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. Synchronous ReplSession operations drain the same saved refresh state. Mount preparation/lifecycle cancellation and parking jobs in the execution worker remain unfinished.
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. Synchronous ReplSession operations drain the same saved refresh state. The worker parks refresh jobs; cancellation restores still-pending Mount preparation.
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 still drain synchronously. Explicit REPL/event refresh parks across worker turns. Idle tasks deliver at most one callback per turn and park subsequent layout; callbacks and individual native nodes remain atomic. Large intrinsic trees use the sliced driver; small intrinsic trees keep the fast path.
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 source execution remains atomic; initial layout parks across worker turns. Explicit REPL/event refresh parks across worker turns. Idle tasks deliver at most one callback per turn and park subsequent layout; callbacks and individual native nodes remain atomic. Large intrinsic trees use the sliced driver; small intrinsic trees keep the fast path.
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.
@@ -1388,6 +1468,8 @@ Cancellation checkpoints own explicit VM roots until restored or released. Initi
REPL/event requests retain their HTTP request and scalar result until the complete window set settles. The worker advances one stage/quantum per turn, takes current native viewport targets each time and keeps later mutations queued. GET /code keeps returning the last complete publication. Response metadata and native commands publish together after settling; no source/event callback is replayed. A running input can finish before a newer queued PUT, preserving a consistent old runtime if that candidate fails; DELETE revokes the owner and prevents its late publication. Source execution/callbacks and structural preparation/paint remain atomic.
Complete-source PUT also parks an isolated candidate VM during initial layout. The worker retains its HTTP request and the prior live VM, advances one candidate stage/quantum per turn and commits only after its full window set settles. New PUT/DELETE submissions discard obsolete candidates and explicitly cancel their pending layout. Failure keeps the prior live owner; accepting a replacement alone does not revoke that owner. Candidate viewport updates use only the surviving primary shell; secondary native resource IDs and sizes still belong to the old VM until successful publication. Parsing, compilation, source execution, structural preparation and paint remain atomic.
## UI host object
Positional arguments only: