Compare commits
3 Commits
ef44d7cb18
...
470454caa6
| Author | SHA1 | Date | |
|---|---|---|---|
| 470454caa6 | |||
| 7289df036f | |||
| dfc69b4777 |
@@ -499,7 +499,7 @@ Flex main-axis policy: flexBasis is "auto" by default (zero basis when flex > 0,
|
||||
When an occurrence's cross-axis constraint changes during settling, its preferred main-axis size is invalidated and remeasured. Any obsolete native flex allocation on that axis is removed for the replacement measurement, so narrowing a nested Column can increase wrapped text height. Source arrange allocations remain explicit. Preferred-size presence and values participate in convergence/cycle detection.
|
||||
|
||||
|
||||
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). Viewport and idle-task refresh park Pending across worker turns; newer viewport targets can cancel and replace unpublished work. Explicit source/event inputs still drain synchronously. Native callbacks are not preempted. Only the completed settled frame is published.
|
||||
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). Viewport and idle-task refresh park Pending across worker turns; newer viewport targets can cancel and replace unpublished work. Source/event callbacks execute atomically; their refresh can park across worker turns. 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. The worker can park viewport and idle-task refresh jobs; cancellation restores still-pending Mount preparation.
|
||||
@@ -511,7 +511,7 @@ UiBridge::begin_layout_frame/resume_layout_frame now expose PendingLayout around
|
||||
ReplSession now owns a resumable RefreshWork containing window traversal, pending bridge layout, unpublished per-window documents and the cumulative refresh work budget. poll_refresh advances one refresh stage or VM quantum; only a complete stable pass replaces the session's full document map. Synchronous callers drain the same state machine. Failure stops the domain, releases any pending bridge work and preserves the externally published picture. refreshYields counts cooperative refresh returns, not wall-clock time. Only still-pending Mount preparation is rolled back; completed callbacks remain committed.
|
||||
|
||||
|
||||
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 and explicit REPL/event refresh still drain synchronously. Idle task delivery starts at most one ready callback per turn and parks its subsequent layout; callbacks themselves and individual 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 still drain synchronously. Explicit REPL/event refresh can park across worker turns. Idle task delivery starts at most one ready callback per turn and parks its subsequent layout; callbacks themselves and individual 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.
|
||||
@@ -530,3 +530,9 @@ Large intrinsic layout trees (more than 64 occurrences) now use the resumable pe
|
||||
|
||||
|
||||
Idle timer delivery now processes at most one ready callback (or one ineligible task cancellation) before starting an incremental refresh. No further task is delivered while that refresh is pending. Viewport changes can replace its unfinished layout without replaying the completed task callback. Task effects and native window commands publish only after settling; a previously completed resize may publish separately. Explicit input still drains pending work first. Synchronous host callers retain a maximum of 64 task deliveries per poll.
|
||||
|
||||
|
||||
REPL and event mutations now have incremental refresh entry points. They execute source/callbacks once, retain scalar response metadata, then park layout with the current viewport target. While pending, mutation, command extraction and garbage collection wait; layout can be retargeted by a newer native size. Synchronous helpers remain for host regression coverage. Discarding a ReplSession explicitly cancels any still-pending bridge layout before the Candidate releases service/global roots. This does not preempt source/callback execution, structural preparation or paint.
|
||||
|
||||
|
||||
The API worker now owns a pending HTTP request plus its scalar result while REPL/event layout is parked. It advances the layout with current native viewport targets and responds only after the stable full-window publication and command extraction. Later mutation requests remain queued; GET /code can observe the last complete publication. A newer accepted PUT invalidates queued inputs but lets the already-running owner settle before candidate construction, so failed replacement can preserve its consistent heap. DELETE revokes that owner and prevents late publication. This queue ordering does not roll back already-executed source effects.
|
||||
|
||||
+7
-1
@@ -163,7 +163,7 @@ UiBridge::begin_layout_frame/resume_layout_frame now expose PendingLayout around
|
||||
ReplSession now owns a resumable RefreshWork containing window traversal, pending bridge layout, unpublished per-window documents and the cumulative refresh work budget. poll_refresh advances one refresh stage or VM quantum; only a complete stable pass replaces the session's full document map. Synchronous callers drain the same state machine. Failure stops the domain, releases any pending bridge work and preserves the externally published picture. refreshYields counts cooperative refresh returns, not wall-clock time. Only still-pending Mount preparation is rolled back; completed callbacks remain committed.
|
||||
|
||||
|
||||
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 and explicit REPL/event refresh still drain synchronously. 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 loads still drain synchronously. Explicit REPL/event refresh can park 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.
|
||||
@@ -185,3 +185,9 @@ source_layout uses the same resumable node driver for trees over 64 occurrences
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
||||
REPL and event mutations now have incremental refresh entry points. They execute source/callbacks once, retain scalar response metadata, then park layout with the current viewport target. While pending, mutation, command extraction and garbage collection wait; layout can be retargeted by a newer native size. Synchronous helpers remain for host regression coverage. Discarding a ReplSession explicitly cancels any still-pending bridge layout before the Candidate releases service/global roots. This does not preempt source/callback execution, structural preparation or paint.
|
||||
|
||||
|
||||
The API worker now owns a pending HTTP request plus its scalar result while REPL/event layout is parked. It advances the layout with current native viewport targets and responds only after the stable full-window publication and command extraction. Later mutation requests remain queued; GET /code can observe the last complete publication. A newer accepted PUT invalidates queued inputs but lets the already-running owner settle before candidate construction, so failed replacement can preserve its consistent heap. DELETE revokes that owner and prevents late publication. This queue ordering does not roll back already-executed source effects.
|
||||
|
||||
+252
-49
@@ -92,7 +92,20 @@ fn start_server_observed(
|
||||
.name("tessera-endor-worker".into())
|
||||
.spawn(move || {
|
||||
let mut worker = Worker::default();
|
||||
let mut pending: Option<(BuildRequest, Box<PendingInput>)> = None;
|
||||
loop {
|
||||
if let Some((job, input)) = pending.take() {
|
||||
match worker.resume_request(&job, input, &worker_namespace, &worker_notify) {
|
||||
RequestProgress::Pending(input) => {
|
||||
pending = Some((job, input));
|
||||
thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
RequestProgress::Complete(response) => {
|
||||
let _ = job.request.respond(response);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
worker.refresh_viewport(&worker_namespace, &worker_notify);
|
||||
let wait = if worker
|
||||
.repl
|
||||
@@ -105,8 +118,12 @@ fn start_server_observed(
|
||||
};
|
||||
match receiver.recv_timeout(wait) {
|
||||
Ok(job) => {
|
||||
let response = worker.run(&job, &worker_namespace, &worker_notify);
|
||||
let _ = job.request.respond(response);
|
||||
match worker.begin_request(&job, &worker_namespace, &worker_notify) {
|
||||
RequestProgress::Pending(input) => pending = Some((job, input)),
|
||||
RequestProgress::Complete(response) => {
|
||||
let _ = job.request.respond(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
@@ -433,6 +450,45 @@ fn submit(
|
||||
}
|
||||
}
|
||||
|
||||
type HttpResponse = Response<std::io::Cursor<Vec<u8>>>;
|
||||
type InputOutcome =
|
||||
std::thread::Result<Result<(endor_host::ReplResult, Vec<crate::window::Command>)>>;
|
||||
|
||||
struct PendingInput {
|
||||
epoch: u64,
|
||||
id: u64,
|
||||
event: bool,
|
||||
result: endor_host::ReplResult,
|
||||
}
|
||||
|
||||
enum RequestProgress {
|
||||
Pending(Box<PendingInput>),
|
||||
Complete(HttpResponse),
|
||||
}
|
||||
|
||||
fn current_viewports(
|
||||
current: &NamespaceState,
|
||||
) -> std::collections::BTreeMap<u64, crate::layout::Size> {
|
||||
let mut viewports: std::collections::BTreeMap<_, _> = current
|
||||
.window_viewports
|
||||
.iter()
|
||||
.filter(|(id, _)| {
|
||||
**id == crate::window::MAIN_WINDOW
|
||||
|| (current.runtime_session != 0
|
||||
&& current
|
||||
.document
|
||||
.windows
|
||||
.get(id)
|
||||
.is_some_and(|view| view.frame.session == current.runtime_session))
|
||||
})
|
||||
.map(|(id, size)| (*id, *size))
|
||||
.collect();
|
||||
if let Some(viewport) = current.viewport {
|
||||
viewports.insert(crate::window::MAIN_WINDOW, viewport);
|
||||
}
|
||||
viewports
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Worker {
|
||||
repl: Option<(u64, endor_host::ReplSession)>,
|
||||
@@ -523,21 +579,7 @@ impl Worker {
|
||||
) {
|
||||
let (epoch, viewports) = match namespace.read() {
|
||||
Ok(current) => {
|
||||
let mut viewports: std::collections::BTreeMap<_, _> = current
|
||||
.window_viewports
|
||||
.iter()
|
||||
.filter(|(id, _)| {
|
||||
**id == crate::window::MAIN_WINDOW
|
||||
|| (current.runtime_session != 0
|
||||
&& current.document.windows.get(id).is_some_and(|view| {
|
||||
view.frame.session == current.runtime_session
|
||||
}))
|
||||
})
|
||||
.map(|(id, size)| (*id, *size))
|
||||
.collect();
|
||||
if let Some(viewport) = current.viewport {
|
||||
viewports.insert(crate::window::MAIN_WINDOW, viewport);
|
||||
}
|
||||
let viewports = current_viewports(¤t);
|
||||
(current.submission, viewports)
|
||||
}
|
||||
Err(_) => return,
|
||||
@@ -626,17 +668,17 @@ impl Worker {
|
||||
}
|
||||
}
|
||||
|
||||
fn run(
|
||||
fn begin_request(
|
||||
&mut self,
|
||||
job: &BuildRequest,
|
||||
namespace: &Arc<RwLock<NamespaceState>>,
|
||||
notify: &Notify,
|
||||
) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
) -> RequestProgress {
|
||||
if job.kind == RequestKind::Code {
|
||||
return self.replace_program(job, namespace, notify);
|
||||
return RequestProgress::Complete(self.replace_program(job, namespace, notify));
|
||||
}
|
||||
if job.kind == RequestKind::Expression {
|
||||
return build(job, namespace, notify);
|
||||
return RequestProgress::Complete(build(job, namespace, notify));
|
||||
}
|
||||
// Mutating requests serialize behind a pending refresh. Idle polling
|
||||
// parks between quanta, but input never interleaves heap mutation with
|
||||
@@ -644,10 +686,15 @@ impl Worker {
|
||||
self.refresh_viewport_mode(namespace, notify, true);
|
||||
let epoch = match namespace.read() {
|
||||
Ok(current) => current.submission,
|
||||
Err(_) => return error_response(StatusCode(500), "namespace lock is poisoned"),
|
||||
Err(_) => {
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(500),
|
||||
"namespace lock is poisoned",
|
||||
));
|
||||
}
|
||||
};
|
||||
if epoch != job.submission {
|
||||
return superseded(job.submission);
|
||||
return RequestProgress::Complete(superseded(job.submission));
|
||||
}
|
||||
if job.kind == RequestKind::ResetRepl {
|
||||
self.repl = None;
|
||||
@@ -662,15 +709,20 @@ impl Worker {
|
||||
current.window_commands.clear();
|
||||
}
|
||||
notify();
|
||||
return json(
|
||||
return RequestProgress::Complete(json(
|
||||
StatusCode(200),
|
||||
serde_json::json!({"ok":true,"execution":"repl-reset","persistent":true,"session_reset":true,"message":"Console memory cleared; displayed page preserved"}),
|
||||
);
|
||||
));
|
||||
}
|
||||
let event = if job.kind == RequestKind::Event {
|
||||
let input: crate::events::Input = match serde_json::from_str(&job.source) {
|
||||
Ok(input) => input,
|
||||
Err(error) => return error_response(StatusCode(400), error.to_string()),
|
||||
Err(error) => {
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(400),
|
||||
error.to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
if !matches!(
|
||||
input.kind.as_str(),
|
||||
@@ -683,20 +735,31 @@ impl Worker {
|
||||
| "tab-drop"
|
||||
| "window-close"
|
||||
) {
|
||||
return error_response(StatusCode(400), "unsupported event kind");
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(400),
|
||||
"unsupported event kind",
|
||||
));
|
||||
}
|
||||
if let Err(message) = input.validate() {
|
||||
return error_response(StatusCode(400), message);
|
||||
return RequestProgress::Complete(error_response(StatusCode(400), message));
|
||||
}
|
||||
let current = match namespace.read() {
|
||||
Ok(current) => current,
|
||||
Err(_) => return error_response(StatusCode(500), "namespace lock poisoned"),
|
||||
Err(_) => {
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(500),
|
||||
"namespace lock poisoned",
|
||||
));
|
||||
}
|
||||
};
|
||||
let frame = if input.window == crate::window::MAIN_WINDOW {
|
||||
¤t.document.frame
|
||||
} else {
|
||||
let Some(document) = current.document.windows.get(&input.window) else {
|
||||
return error_response(StatusCode(409), "window is no longer active");
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(409),
|
||||
"window is no longer active",
|
||||
));
|
||||
};
|
||||
&document.frame
|
||||
};
|
||||
@@ -715,7 +778,9 @@ impl Worker {
|
||||
.is_some_and(|(_, runtime)| runtime.is_faulted());
|
||||
if stopped {
|
||||
drop(current);
|
||||
return self.close_inactive_window(&input, epoch, namespace, notify);
|
||||
return RequestProgress::Complete(
|
||||
self.close_inactive_window(&input, epoch, namespace, notify),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(target) = &input.tab_drop {
|
||||
@@ -739,10 +804,10 @@ impl Worker {
|
||||
.as_ref()
|
||||
.is_none_or(|(_, runtime)| !runtime.accepts_tab_drop(&input))
|
||||
{
|
||||
return error_response(
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(409),
|
||||
"drop targets an obsolete or inactive frame",
|
||||
);
|
||||
));
|
||||
}
|
||||
}
|
||||
if frame.window != input.window
|
||||
@@ -769,10 +834,10 @@ impl Worker {
|
||||
|| (input.kind != "window-close" && !runtime.accepts_window(input.window))
|
||||
})
|
||||
{
|
||||
return error_response(
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(409),
|
||||
"event targets an obsolete or inactive frame",
|
||||
);
|
||||
));
|
||||
}
|
||||
Some(input)
|
||||
} else {
|
||||
@@ -785,7 +850,12 @@ impl Worker {
|
||||
{
|
||||
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 viewport = namespace.read().ok().and_then(|current| current.viewport);
|
||||
match endor_host::ReplSession::new_with_viewport(self.next_session, viewport) {
|
||||
@@ -797,28 +867,159 @@ impl Worker {
|
||||
}
|
||||
self.repl = Some((epoch, session));
|
||||
}
|
||||
Err(error) => return error_response(StatusCode(500), error.to_string()),
|
||||
Err(error) => {
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(500),
|
||||
error.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let viewports = match namespace.read() {
|
||||
Ok(current) => current_viewports(¤t),
|
||||
Err(_) => {
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(500),
|
||||
"namespace lock is poisoned",
|
||||
));
|
||||
}
|
||||
};
|
||||
let session = &mut self.repl.as_mut().expect("initialized REPL").1;
|
||||
let id = session.id;
|
||||
let result = catch_unwind(AssertUnwindSafe(|| -> Result<_> {
|
||||
let result = if let Some(event) = &event {
|
||||
session.dispatch(event)?
|
||||
session.dispatch_incremental(event, &viewports)?
|
||||
} else {
|
||||
session.execute(&job.source, &job.namespace)?
|
||||
session.execute_incremental(&job.source, &job.namespace, &viewports)?
|
||||
};
|
||||
Ok((result, session.take_window_commands()?))
|
||||
let commands = if session.has_pending_refresh() {
|
||||
Vec::new()
|
||||
} else {
|
||||
session.take_window_commands()?
|
||||
};
|
||||
Ok((result, commands))
|
||||
}));
|
||||
let faulted = session.is_faulted();
|
||||
if session.has_pending_refresh() {
|
||||
if let Ok(Ok((result, _))) = result {
|
||||
return RequestProgress::Pending(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;
|
||||
}
|
||||
RequestProgress::Complete(self.finish_input(
|
||||
job,
|
||||
namespace,
|
||||
notify,
|
||||
epoch,
|
||||
id,
|
||||
event.is_some(),
|
||||
faulted,
|
||||
result,
|
||||
))
|
||||
}
|
||||
|
||||
fn resume_request(
|
||||
&mut self,
|
||||
job: &BuildRequest,
|
||||
mut input: Box<PendingInput>,
|
||||
namespace: &Arc<RwLock<NamespaceState>>,
|
||||
notify: &Notify,
|
||||
) -> RequestProgress {
|
||||
let viewports = match namespace.read() {
|
||||
Ok(current)
|
||||
if current.submission == input.epoch || current.runtime_session == input.id =>
|
||||
{
|
||||
current_viewports(¤t)
|
||||
}
|
||||
Ok(_) => {
|
||||
self.repl = None;
|
||||
return RequestProgress::Complete(superseded(job.submission));
|
||||
}
|
||||
Err(_) => {
|
||||
self.repl = None;
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(500),
|
||||
"namespace lock is poisoned",
|
||||
));
|
||||
}
|
||||
};
|
||||
let Some((epoch, session)) = &mut self.repl else {
|
||||
return RequestProgress::Complete(error_response(
|
||||
StatusCode(409),
|
||||
"input runtime was discarded",
|
||||
));
|
||||
};
|
||||
if *epoch != input.epoch || session.id != input.id {
|
||||
return RequestProgress::Complete(superseded(job.submission));
|
||||
}
|
||||
let resumed = catch_unwind(AssertUnwindSafe(|| -> Result<_> {
|
||||
let document = session.resize_windows_incremental(&viewports, false)?;
|
||||
if session.has_pending_refresh() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some((document, session.take_window_commands()?)))
|
||||
}));
|
||||
let faulted = session.is_faulted();
|
||||
let result = match resumed {
|
||||
Ok(Ok(None)) => return RequestProgress::Pending(input),
|
||||
Ok(Ok(Some((document, commands)))) => {
|
||||
input.result.document = document;
|
||||
Ok(Ok((input.result, commands)))
|
||||
}
|
||||
Ok(Err(error)) => Ok(Err(error)),
|
||||
Err(panic) => Err(panic),
|
||||
};
|
||||
RequestProgress::Complete(self.finish_input(
|
||||
job,
|
||||
namespace,
|
||||
notify,
|
||||
input.epoch,
|
||||
input.id,
|
||||
input.event,
|
||||
faulted,
|
||||
result,
|
||||
))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish_input(
|
||||
&mut self,
|
||||
job: &BuildRequest,
|
||||
namespace: &Arc<RwLock<NamespaceState>>,
|
||||
notify: &Notify,
|
||||
epoch: u64,
|
||||
id: u64,
|
||||
event: bool,
|
||||
faulted: bool,
|
||||
result: InputOutcome,
|
||||
) -> HttpResponse {
|
||||
let Ok(mut current) = namespace.write() else {
|
||||
return error_response(StatusCode(500), "namespace lock is poisoned");
|
||||
};
|
||||
if current.submission != epoch {
|
||||
drop(current);
|
||||
self.repl = None;
|
||||
return superseded(job.submission);
|
||||
}
|
||||
let epoch = if current.submission != epoch {
|
||||
if current.runtime_session != id {
|
||||
drop(current);
|
||||
self.repl = None;
|
||||
return superseded(job.submission);
|
||||
}
|
||||
// Accepted PUTs invalidate queued inputs, not a mutation already
|
||||
// executing on this owner. Settle it before building the candidate
|
||||
// so a failed replacement can preserve a consistent live heap.
|
||||
if let Some((owner, runtime)) = &mut self.repl
|
||||
&& runtime.id == id
|
||||
{
|
||||
*owner = current.submission;
|
||||
}
|
||||
current.submission
|
||||
} else {
|
||||
epoch
|
||||
};
|
||||
match result {
|
||||
Ok(Ok((result, commands))) => {
|
||||
let projected = !commands.is_empty();
|
||||
@@ -838,11 +1039,11 @@ impl Worker {
|
||||
}
|
||||
json(
|
||||
StatusCode(200),
|
||||
serde_json::json!({"ok":true,"execution":if event.is_some() { "event" } else { "repl" },"persistent":true,"session":id,"input":result.input,"value":result.value,"bindings":result.bindings,"rendered":rendered,"revision":revision}),
|
||||
serde_json::json!({"ok":true,"execution":if event { "event" } else { "repl" },"persistent":true,"session":id,"input":result.input,"value":result.value,"bindings":result.bindings,"rendered":rendered,"revision":revision}),
|
||||
)
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
if event.is_some() || faulted {
|
||||
if event || faulted {
|
||||
let mut document = current.document.clone();
|
||||
// Preserve the first failure of this VM; subsequent
|
||||
// rejected Console input must not hide the callback cause.
|
||||
@@ -1090,7 +1291,7 @@ its pending render is discarded; previous displayed page is preserved.
|
||||
|
||||
Session limits: 256 executed inputs, 1 MiB transcript, 10000 cumulative AST nodes,
|
||||
4096 retained visual objects and 64 retained pages. Aster collects unreachable objects/cycles between inputs; there is no fixed UI pool. No VM handles cross to the window.
|
||||
A newer accepted complete-source PUT or code DELETE invalidates queued Console inputs.
|
||||
A newer accepted complete-source PUT or code DELETE invalidates queued Console inputs. A running input settles before a queued PUT candidate is built; code DELETE revokes that runtime immediately.
|
||||
A successful PUT retains its fresh VM as the live program for Console and GUI events;
|
||||
a failed PUT preserves the previous program. DELETE releases the live context.
|
||||
GET /code returns the source of the displayed snapshot: exact submitted source for
|
||||
@@ -1174,7 +1375,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 and explicit REPL/event refresh still drain synchronously. 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 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.
|
||||
|
||||
|
||||
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.
|
||||
@@ -1185,6 +1386,8 @@ New viewport targets now coalesce pending refresh work. The runtime cancels only
|
||||
|
||||
Cancellation checkpoints own explicit VM roots until restored or released. Initial presentations may have no mount dictionary; cancellation restores that absence too. Saved metadata values retain object-valued attributes. A pending refresh can restart while keeping already completed window drafts; no onMount/onUnmount callback is replayed merely because the viewport target changed. Mount-owned tasks are cancelled immediately before an actual onUnmount callback, never during abandoned preparation.
|
||||
|
||||
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.
|
||||
|
||||
## UI host object
|
||||
|
||||
Positional arguments only:
|
||||
|
||||
+189
-18
@@ -355,7 +355,26 @@ impl ReplSession {
|
||||
refresh: None,
|
||||
})
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub fn execute(&mut self, source: &str, namespace: &str) -> Result<ReplResult> {
|
||||
self.execute_mode(source, namespace, None)
|
||||
}
|
||||
|
||||
pub fn execute_incremental(
|
||||
&mut self,
|
||||
source: &str,
|
||||
namespace: &str,
|
||||
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
|
||||
) -> Result<ReplResult> {
|
||||
self.execute_mode(source, namespace, Some(viewports))
|
||||
}
|
||||
|
||||
fn execute_mode(
|
||||
&mut self,
|
||||
source: &str,
|
||||
namespace: &str,
|
||||
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
|
||||
) -> Result<ReplResult> {
|
||||
self.require_idle_refresh()?;
|
||||
if self.faulted {
|
||||
bail!(
|
||||
@@ -466,7 +485,7 @@ impl ReplSession {
|
||||
retained?;
|
||||
rendered_value = repr?;
|
||||
}
|
||||
let document = self.refresh_document()?;
|
||||
let document = self.refresh_after_mutation(viewports)?;
|
||||
Ok(ReplResult {
|
||||
value: rendered_value,
|
||||
document,
|
||||
@@ -487,8 +506,10 @@ impl ReplSession {
|
||||
.push_str(" (error; earlier statements may remain live)");
|
||||
}
|
||||
}
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
if !self.has_pending_refresh() {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -504,6 +525,23 @@ impl ReplSession {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn refresh_after_mutation(
|
||||
&mut self,
|
||||
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
|
||||
) -> Result<Option<RenderDocument>> {
|
||||
let Some(viewports) = viewports else {
|
||||
return self.refresh_document();
|
||||
};
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_document(&mut self) -> Result<Option<RenderDocument>> {
|
||||
loop {
|
||||
match self.poll_refresh(false)? {
|
||||
@@ -824,18 +862,7 @@ impl ReplSession {
|
||||
return Ok(None);
|
||||
}
|
||||
completed = true;
|
||||
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()
|
||||
}
|
||||
self.refresh_after_mutation(viewports)
|
||||
})();
|
||||
if result.is_err() {
|
||||
self.faulted = true;
|
||||
@@ -901,7 +928,24 @@ impl ReplSession {
|
||||
self.faulted
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn dispatch(&mut self, input: &crate::events::Input) -> Result<ReplResult> {
|
||||
self.dispatch_mode(input, None)
|
||||
}
|
||||
|
||||
pub fn dispatch_incremental(
|
||||
&mut self,
|
||||
input: &crate::events::Input,
|
||||
viewports: &std::collections::BTreeMap<u64, crate::layout::Size>,
|
||||
) -> Result<ReplResult> {
|
||||
self.dispatch_mode(input, Some(viewports))
|
||||
}
|
||||
|
||||
fn dispatch_mode(
|
||||
&mut self,
|
||||
input: &crate::events::Input,
|
||||
viewports: Option<&std::collections::BTreeMap<u64, crate::layout::Size>>,
|
||||
) -> Result<ReplResult> {
|
||||
self.require_idle_refresh()?;
|
||||
if self.faulted {
|
||||
bail!("runtime stopped after a callback or rendering failure");
|
||||
@@ -915,7 +959,7 @@ impl ReplSession {
|
||||
self.bridge.select_window(input.window)?;
|
||||
let result = (|| {
|
||||
self.bridge.dispatch(&mut self.candidate.vm, input)?;
|
||||
let document = self.refresh_document()?;
|
||||
let document = self.refresh_after_mutation(viewports)?;
|
||||
Ok(ReplResult {
|
||||
value: "nil".into(),
|
||||
document,
|
||||
@@ -934,11 +978,28 @@ impl ReplSession {
|
||||
self.faulted = true;
|
||||
self.bridge.discard_pending(&mut self.candidate.vm)?;
|
||||
}
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
if !self.has_pending_refresh() {
|
||||
self.bridge
|
||||
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)?;
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReplSession {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mut work) = self.refresh.take()
|
||||
&& let Some(pending) = work.pending.take()
|
||||
{
|
||||
// Close the read-only continuation and checkpoint roots before
|
||||
// Candidate releases the globals/services of a discarded domain.
|
||||
let _ = self
|
||||
.bridge
|
||||
.cancel_layout_frame(&mut self.candidate.vm, *pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shift_node_lines(node: &mut CodeNode, offset: usize) {
|
||||
node.start_line += offset;
|
||||
node.end_line += offset;
|
||||
@@ -4174,6 +4235,116 @@ page.render(block)
|
||||
assert_eq!(source_measure_stat(&mut session, "layoutCancels"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_input_retains_value_and_never_replays_source_while_retargeting() {
|
||||
let children = std::iter::repeat_n("item", 80)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let source = format!(
|
||||
"count = ui.state(0)\nitem = RectBlock(2,20)\npage = Page()\npage.render(Row(0,0,{children}))"
|
||||
);
|
||||
let (mut session, initial) = ReplSession::load(&source, "app.main", 275, 1).unwrap();
|
||||
let first = std::collections::BTreeMap::new();
|
||||
let result = session
|
||||
.execute_incremental(
|
||||
"count.increment()\nitem.width = 3\ncount.value",
|
||||
"app.main",
|
||||
&first,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.value, "1");
|
||||
assert!(result.document.is_none());
|
||||
assert!(session.has_pending_refresh());
|
||||
assert!(session.take_window_commands().is_err());
|
||||
assert!(session.execute("count.increment()", "app.main").is_err());
|
||||
for _ in 0..20 {
|
||||
session.resize_windows_incremental(&first, false).unwrap();
|
||||
if session.candidate.vm.has_suspended_call() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(session.candidate.vm.has_suspended_call());
|
||||
assert_eq!(
|
||||
session.documents[&crate::window::MAIN_WINDOW]
|
||||
.frame
|
||||
.layout_version,
|
||||
initial.frame.layout_version
|
||||
);
|
||||
let latest = std::collections::BTreeMap::from([(
|
||||
crate::window::MAIN_WINDOW,
|
||||
crate::layout::Size {
|
||||
width: 900.0,
|
||||
height: 650.0,
|
||||
},
|
||||
)]);
|
||||
session.resize_windows_incremental(&latest, false).unwrap();
|
||||
let settled = session.resize_windows(&latest).unwrap().unwrap();
|
||||
assert_eq!(settled.frame.mounts.last().unwrap().x, 237.0);
|
||||
assert_eq!(result.value, "1");
|
||||
assert_eq!(
|
||||
session.execute("count.value", "app.main").unwrap().value,
|
||||
"1"
|
||||
);
|
||||
assert_eq!(source_measure_stat(&mut session, "layoutCancels"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_event_runs_callback_once_before_publishing_its_layout() {
|
||||
let children = std::iter::repeat_n("item", 80)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let source = format!(
|
||||
"count = ui.state(0)\nitem = RectBlock(2,20)\nbutton = Button(\"increment\")\nbutton.onClick(count.increment)\npage = Page()\npage.render(Column(0,0,button,ui.textOf(count,\"value\"),Row(0,0,{children})))"
|
||||
);
|
||||
let (mut session, initial) = ReplSession::load(&source, "app.main", 276, 1).unwrap();
|
||||
let mount = initial
|
||||
.frame
|
||||
.mounts
|
||||
.iter()
|
||||
.find(|mount| mount.interactive)
|
||||
.unwrap();
|
||||
let input = crate::events::Input {
|
||||
window: crate::window::MAIN_WINDOW,
|
||||
session: session.id,
|
||||
layout_version: initial.frame.layout_version,
|
||||
mount: mount.id,
|
||||
kind: "click".into(),
|
||||
point: None,
|
||||
press_point: None,
|
||||
delta: None,
|
||||
tab_drop: None,
|
||||
screen_position: None,
|
||||
};
|
||||
let viewports = std::collections::BTreeMap::new();
|
||||
let result = session.dispatch_incremental(&input, &viewports).unwrap();
|
||||
assert!(result.document.is_none());
|
||||
assert!(session.has_pending_refresh());
|
||||
assert_eq!(
|
||||
session.documents[&crate::window::MAIN_WINDOW]
|
||||
.frame
|
||||
.layout_version,
|
||||
initial.frame.layout_version
|
||||
);
|
||||
let mut complete = false;
|
||||
for _ in 0..1000 {
|
||||
if session
|
||||
.resize_windows_incremental(&viewports, false)
|
||||
.unwrap()
|
||||
.is_some()
|
||||
{
|
||||
complete = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(complete);
|
||||
assert!(!session.has_pending_refresh());
|
||||
assert_eq!(
|
||||
session.execute("count.value", "app.main").unwrap().value,
|
||||
"1"
|
||||
);
|
||||
assert!(source_measure_stat(&mut session, "refreshYields") > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_intrinsic_layout_yields_and_retargets_without_geometry_loss() {
|
||||
let children = std::iter::repeat_n("item", 80)
|
||||
|
||||
Reference in New Issue
Block a user