Retire inactive windows without invoking stopped runtimes
Verify Tessera GUI / verify (push) Failing after 7m31s

This commit is contained in:
2026-10-21 21:02:52 +08:00
parent e3e46068eb
commit dff49770fa
10 changed files with 440 additions and 48 deletions
+9
View File
@@ -86,3 +86,12 @@ Explicit reset drops the VM. Successful PUT replaces it with the fresh program;
actual Console transcript; source history is never rerun to reconstruct memory.
The Aster pin includes independent Assignment syntax and generic opt-in assign_from support.
Live reference tests cover alias updates, nested mounts, cycle rejection, detached branch release and unmount/remount.
Stopped runtimes have a separate host-only secondary-window teardown path. It detaches
Mounts and releases window/Page roots without executing source lifecycle callbacks,
and does not resume the failed VM. Preserved old-generation pictures can be closed
without borrowing a new Console VM's same-number resource. Secondary viewport inputs
are filtered by their published runtime generation. Native window/surface failures
are returned to the host diagnostics rather than panicking the event loop; main
window initialization errors propagate to process exit. The stopped-window and
cross-generation regression sources are compiled, not locally executed.
+171 -2
View File
@@ -430,10 +430,93 @@ struct Worker {
next_session: u64,
}
impl Worker {
fn close_inactive_window(
&mut self,
input: &crate::events::Input,
epoch: u64,
namespace: &Arc<RwLock<NamespaceState>>,
notify: &Notify,
) -> Response<std::io::Cursor<Vec<u8>>> {
if input.window == crate::window::MAIN_WINDOW {
return error_response(
StatusCode(409),
"close the primary shell with its OS window control",
);
}
let owns_runtime = self.repl.as_ref().is_some_and(|(owner, runtime)| {
*owner == epoch && runtime.id == input.session && input.session != 0
});
let mut discarded = false;
if owns_runtime {
let result = catch_unwind(AssertUnwindSafe(|| {
self.repl
.as_mut()
.expect("owned runtime")
.1
.retire_window(input.window)
}));
if !matches!(result, Ok(Ok(()))) {
// Never keep a half-cleaned VM live or borrow another generation.
self.repl = None;
discarded = true;
}
}
let Ok(mut current) = namespace.write() else {
return error_response(StatusCode(500), "namespace lock poisoned");
};
if current.submission != epoch {
return superseded(epoch);
}
let Some(view) = current.document.windows.get(&input.window) else {
return error_response(StatusCode(409), "window is no longer active");
};
if view.frame.session != input.session {
return error_response(
StatusCode(409),
"window belongs to another runtime generation",
);
}
let mut document = current.document.clone();
document.windows.remove(&input.window);
if discarded {
document.frame.session = 0;
document.frame.focus = None;
for view in document.windows.values_mut() {
view.frame.session = 0;
view.frame.focus = None;
}
current.runtime_session = 0;
current.window_commands.clear();
}
match current.commit(epoch, document) {
Ok(Some(_)) => {}
Ok(None) => return superseded(epoch),
Err(error) => return error_response(StatusCode(500), error.to_string()),
}
current.window_viewports.remove(&input.window);
drop(current);
notify();
json(
StatusCode(200),
serde_json::json!({"ok":true,"execution":"window-retire","window":input.window,"callbacks":false,"runtime_discarded":discarded}),
)
}
fn refresh_viewport(&mut self, namespace: &Arc<RwLock<NamespaceState>>, notify: &Notify) {
let (epoch, viewports) = match namespace.read() {
Ok(current) => {
let mut viewports = current.window_viewports.clone();
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);
}
@@ -571,6 +654,24 @@ impl Worker {
};
&document.frame
};
if input.kind == "window-close"
&& frame.window == input.window
&& frame.session == input.session
{
let owns = self.repl.as_ref().is_some_and(|(owner, runtime)| {
*owner == epoch && runtime.id == input.session && input.session != 0
});
let stopped = frame.fault.is_some()
|| !owns
|| self
.repl
.as_ref()
.is_some_and(|(_, runtime)| runtime.is_faulted());
if stopped {
drop(current);
return self.close_inactive_window(&input, epoch, namespace, notify);
}
}
if frame.window != input.window
|| frame.session != input.session
|| (input.kind != "window-close" && frame.layout_version != input.layout_version)
@@ -935,7 +1036,7 @@ declarations, explicit first `self` parameters, positional field construction an
member assignment. Inherited methods bind the actual receiver; overridden methods
are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Traits and annotation checking remain pending. Native Block/Page methods use the same type method tables and binding path.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), setTitle(text) and focus(). Requests project to their actual native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Existing-window drag/drop, release-point placement and faulted-VM cleanup remain pending.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), setTitle(text) and focus(). Requests project to their actual native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Existing-window drag/drop, release-point placement and full application-exit notifications remain pending.
Source measure and arrange overrides execute bottom-up and top-down in one read-only VM layout call. Structural Mount links exist before first measurement; bounds queries reject premature geometry. Native base layout uses current occurrence child measurements, and Arrangement must assign every stable child slot exactly once. Layout dependencies changed by lifecycle hooks trigger another pass before publication. Page constraints now use the current logical window viewport. Column/Button propagate cross-axis width and Row propagates cross-axis height; desired sizes are clamped. ui.viewport() provides a managed snapshot whose private input participates in rendering dependencies. Native resize updates are coalesced on the same worker without adding source inputs. Source measurement caches use Mount/method/children/constraints and actual subcall object reads, including returned-result decoding; Mount-reading methods conservatively bypass caching. ui.stats() exposes sourceMeasureHits/sourceMeasureMisses outside read-only rendering. General constraint negotiation, wrapping and scrolling remain pending.
@@ -1059,6 +1160,74 @@ mod tests {
time::Duration,
};
#[test]
fn preserved_picture_close_does_not_retire_same_number_in_fresh_console_vm() {
let (_, mut picture) = endor_host::ReplSession::load(
include_str!("../examples/windows.endor"),
"app.main",
1,
150,
)
.unwrap();
picture.frame.session = 0;
for view in picture.windows.values_mut() {
view.frame.session = 0;
}
let mut fresh = endor_host::ReplSession::new(151).unwrap();
assert!(
fresh
.execute("pending=Window()\nui.window().resize(0,600)", "app.main")
.is_err()
);
assert!(fresh.accepts_window(2));
let namespace = Arc::new(RwLock::new(NamespaceState {
document: picture,
submission: 1,
runtime_session: 151,
..NamespaceState::default()
}));
let mut worker = Worker {
repl: Some((1, fresh)),
next_session: 151,
};
let notify: Notify = Arc::new(|| {});
namespace.write().unwrap().window_viewports.insert(
2,
crate::layout::Size {
width: 800.0,
height: 600.0,
},
);
worker.refresh_viewport(&namespace, &notify);
assert_eq!(
namespace.read().unwrap().document.windows[&2].frame.session,
0
);
let response = worker.close_inactive_window(
&crate::events::Input {
window: 2,
session: 0,
layout_version: 0,
mount: 0,
kind: "window-close".into(),
point: None,
press_point: None,
},
1,
&namespace,
&notify,
);
assert_eq!(response.status_code(), StatusCode(200));
assert!(namespace.read().unwrap().document.windows.is_empty());
let runtime = &mut worker.repl.as_mut().unwrap().1;
assert_eq!(runtime.id, 151);
assert!(runtime.accepts_window(2));
assert_eq!(
runtime.execute("pending.id()", "app.main").unwrap().value,
"2"
);
}
struct TestServer {
server: Arc<Server>,
address: SocketAddr,
+96 -43
View File
@@ -32,6 +32,7 @@ pub enum AppEvent {
pub struct TesseraApp {
resource: u64,
native_session: u64,
native_error: Option<String>,
children: std::collections::BTreeMap<u64, TesseraApp>,
proxy: EventLoopProxy<AppEvent>,
window: Option<Arc<Window>>,
@@ -62,6 +63,7 @@ impl TesseraApp {
Ok(Self {
resource: crate::window::MAIN_WINDOW,
native_session: 0,
native_error: None,
children: std::collections::BTreeMap::new(),
proxy: proxy.clone(),
window: None,
@@ -137,6 +139,10 @@ impl TesseraApp {
child.resource = id;
child.native_session = session;
child.resumed(event_loop);
if let Some(error) = &child.native_error {
self.developer_tools.input_error = error.clone();
self.developer_tools.open = true;
}
child.document_updated(event_loop);
self.children.insert(id, child);
}
@@ -211,11 +217,19 @@ impl TesseraApp {
namespace.viewport = Some(size);
namespace.window_viewports.insert(self.resource, size);
if self.resource == crate::window::MAIN_WINDOW {
let session = namespace.runtime_session;
namespace.window_viewports.retain(|id, _| {
*id == crate::window::MAIN_WINDOW || self.children.contains_key(id)
*id == crate::window::MAIN_WINDOW
|| self
.children
.get(id)
.is_some_and(|child| session != 0 && child.native_session == session)
});
for (id, child) in &self.children {
if let Ok(local) = child.namespace.read()
if child.native_session == session
&& session != 0
&& let Ok(local) = child.namespace.read()
&& local.document.frame.session == session
&& let Some(size) = local.viewport
{
namespace.window_viewports.insert(*id, size);
@@ -520,20 +534,81 @@ impl TesseraApp {
false
}
fn create_native(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
if self.window.is_some() {
return Ok(());
}
let attributes = WindowAttributes::default()
.with_title(if self.resource == crate::window::MAIN_WINDOW {
"Tessera".into()
} else {
format!("Endor Window {}", self.resource)
})
.with_inner_size(if self.resource == crate::window::MAIN_WINDOW {
LogicalSize::new(1_280.0, 800.0)
} else {
LogicalSize::new(960.0, 640.0)
})
.with_min_inner_size(LogicalSize::new(720.0, 480.0))
.with_max_inner_size(LogicalSize::new(
crate::window::MAX_WINDOW_DIMENSION,
crate::window::MAX_WINDOW_DIMENSION,
));
let window = Arc::new(event_loop.create_window(attributes)?);
let context = Context::new(window.clone()).map_err(|error| anyhow::anyhow!("{error}"))?;
let surface =
Surface::new(&context, window.clone()).map_err(|error| anyhow::anyhow!("{error}"))?;
window.set_ime_allowed(true);
self.window = Some(window.clone());
self.context = Some(context);
self.surface = Some(surface);
self.apply_window_commands(event_loop);
self.publish_viewport();
window.request_redraw();
self.native_error = None;
Ok(())
}
pub fn exit_result(&self) -> anyhow::Result<()> {
if let Some(error) = &self.native_error {
anyhow::bail!("{error}");
}
Ok(())
}
fn redraw(&mut self) {
match self.try_redraw() {
Ok(()) => {
if self.window.is_some() && self.surface.is_some() {
self.native_error = None;
}
}
Err(error) => {
let message = format!("Window {} redraw failed: {error:#}", self.resource);
if self.native_error.as_ref() != Some(&message) {
self.native_error = Some(message.clone());
let _ = self.proxy.send_event(AppEvent::RuntimeFailed { message });
}
}
}
}
fn try_redraw(&mut self) -> anyhow::Result<()> {
let guest_cursor = self.guest_hit().is_some() || self.tab_hit().is_some();
let (Some(window), Some(surface)) = (self.window.as_ref(), self.surface.as_mut()) else {
return;
return Ok(());
};
let size = window.inner_size();
let (Some(width), Some(height)) =
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
else {
return;
return Ok(());
};
let Ok(namespace) = self.namespace.read() else {
return;
return Ok(());
};
let scene = scene::build_scene(
size.width,
@@ -565,51 +640,29 @@ impl TesseraApp {
surface
.resize(width, height)
.expect("resize software surface");
let mut buffer = surface.buffer_mut().expect("acquire software buffer");
.map_err(|error| anyhow::anyhow!("{error}"))?;
let mut buffer = surface
.buffer_mut()
.map_err(|error| anyhow::anyhow!("{error}"))?;
SoftwareRenderer::render(&scene.display_list, &mut buffer, size.width, size.height);
buffer.present().expect("present software-rendered frame");
buffer
.present()
.map_err(|error| anyhow::anyhow!("{error}"))?;
Ok(())
}
}
impl ApplicationHandler<AppEvent> for TesseraApp {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
let attributes = WindowAttributes::default()
.with_title(if self.resource == crate::window::MAIN_WINDOW {
"Tessera".into()
} else {
format!("Endor Window {}", self.resource)
})
.with_inner_size(if self.resource == crate::window::MAIN_WINDOW {
LogicalSize::new(1_280.0, 800.0)
} else {
LogicalSize::new(960.0, 640.0)
})
.with_min_inner_size(LogicalSize::new(720.0, 480.0))
.with_max_inner_size(LogicalSize::new(
crate::window::MAX_WINDOW_DIMENSION,
crate::window::MAX_WINDOW_DIMENSION,
if let Err(error) = self.create_native(event_loop) {
self.native_error = Some(format!(
"Window {} initialization failed: {error:#}",
self.resource
));
let window = Arc::new(
event_loop
.create_window(attributes)
.expect("create Tessera window"),
);
let context = Context::new(window.clone()).expect("create software-rendering context");
let surface =
Surface::new(&context, window.clone()).expect("create software-rendering surface");
window.set_ime_allowed(true);
self.window = Some(window.clone());
self.context = Some(context);
self.surface = Some(surface);
self.apply_window_commands(event_loop);
self.publish_viewport();
window.request_redraw();
if self.resource == crate::window::MAIN_WINDOW {
event_loop.exit();
}
}
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: AppEvent) {
+4
View File
@@ -43,6 +43,10 @@ impl NamespaceState {
pub fn publish_window_commands(&mut self, session: u64, commands: Vec<crate::window::Command>) {
if self.runtime_session != session {
self.window_commands.clear();
// The primary shell survives VM replacement. Secondary native
// resources belong to their originating runtime generation.
self.window_viewports
.retain(|id, _| *id == crate::window::MAIN_WINDOW);
}
self.runtime_session = session;
if session == 0 {
+91
View File
@@ -622,6 +622,17 @@ impl ReplSession {
result
}
pub fn retire_window(&mut self, id: u64) -> Result<()> {
// This path is exclusively host cleanup after the domain has stopped.
// No language functions, layout, paint or lifecycle hooks may run here.
self.faulted = true;
self.bridge.retire_window(&mut self.candidate.vm, id)?;
self.documents.remove(&id);
let _ = self.take_window_commands()?;
self.bridge
.reclaim(&mut self.candidate.vm, &mut self.candidate.roots)
}
pub fn accepts_window(&self, id: u64) -> bool {
self.bridge.accepts_window(id)
}
@@ -938,6 +949,86 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn stopped_window_teardown_detaches_mounts_without_running_source_hooks() {
let source = r#"class WatchedPage: Page {
marker: Object
function onUnmount(self: WatchedPage, mount: Mount): Unit { self.marker.increment() }
}
class Failure {
function run(self: Failure, event: Event): Unit { ui.window().resize(0,600) }
}
marker=ui.state(0)
mainPage=Page()
mainPage.render(TextBlock("main"))
other=Window()
button=Button("fail")
failure=Failure()
connection=button.on("click",failure.run)
page=WatchedPage(marker)
page.render(button)
page.open(other)"#;
let (mut session, initial) = ReplSession::load(source, "app.main", 1, 140).unwrap();
session
.execute("held=button.mounts().at(0)", "app.main")
.unwrap();
let globals = session.candidate.globals.unwrap();
let lookup = |session: &ReplSession, name: &str| match session
.candidate
.vm
.dict_get(globals, &Value::Text(name.into()))
.unwrap()
.unwrap()
{
Value::Object(object) => object,
_ => panic!("object"),
};
let held = lookup(&session, "held");
let window = lookup(&session, "other");
let marker = lookup(&session, "marker");
let mount = session
.candidate
.vm
.payload::<crate::mount::Mount>(held, "Mount")
.unwrap()
.geometry
.id;
assert!(
session
.dispatch(&crate::events::Input {
window: 2,
session: 140,
layout_version: initial.windows[&2].frame.layout_version,
mount,
kind: "click".into(),
point: None,
press_point: None
})
.is_err()
);
assert!(session.is_faulted());
session.retire_window(2).unwrap();
assert!(!session.accepts_window(2));
assert!(
!session
.candidate
.vm
.payload::<crate::mount::Mount>(held, "Mount")
.unwrap()
.mounted
);
assert!(
crate::window::pages(session.candidate.vm.object_store(), window)
.unwrap()
.is_empty()
);
assert_eq!(
session.candidate.vm.get_attr(marker, "value").unwrap(),
Value::Number(0.into())
);
assert!(session.execute("42", "app.main").is_err());
}
#[test]
fn native_windows_share_business_state_move_pages_and_release_closed_contexts() {
let (mut session, initial) = ReplSession::load(
+1 -1
View File
@@ -44,5 +44,5 @@ fn main() -> Result<()> {
let activity = api::start(namespace.clone(), event_loop.create_proxy())?;
let mut app = TesseraApp::new(namespace, activity, event_loop.create_proxy())?;
event_loop.run_app(&mut app)?;
Ok(())
app.exit_result()
}
+28
View File
@@ -407,6 +407,34 @@ impl NativeCallable for Sync {
}
impl MountTable {
/// A faulted domain cannot run user onUnmount callbacks. Still detach every
/// context and release its owning dictionary through the normal heap barrier.
pub fn retire(&mut self, vm: &mut Vm, desktop: ObjectRef) -> Result<(), VmError> {
for weak in self.ordered().into_iter().rev() {
if let Some(object) = vm.upgrade(weak)? {
let result = (|| {
let mut mount = vm.payload::<Mount>(object, "Mount")?.clone();
mount.mounted = false;
mount.layout = None;
mount.parent = None;
mount.first_child = None;
mount.next_sibling = None;
vm.replace_payload(object, mount)?;
vm.set_attr(object, "mounted", Value::Bool(false))
})();
vm.release(object)?;
result?;
}
}
let dictionary = vm.new_dict()?;
let result = vm.set_attr(desktop, "mounts", Value::Object(dictionary));
vm.release(dictionary)?;
result?;
self.active.clear();
self.order.clear();
Ok(())
}
pub fn ordered(&self) -> Vec<WeakObjectRef> {
self.order
.iter()
+27
View File
@@ -1294,6 +1294,33 @@ impl UiBridge {
state.current = id;
Ok(())
}
pub fn retire_window(&self, vm: &mut Vm, id: u64) -> Result<()> {
if id == crate::window::MAIN_WINDOW {
bail!("the primary shell is closed by the OS window control");
}
let mut state = self
.session
.lock()
.map_err(|_| anyhow::anyhow!("UI session poisoned"))?;
let Some(view) = state.presentations.get_mut(&id) else {
return Ok(());
};
let desktop = view.desktop;
let window = object(Some(&vm.get_attr(desktop, "window")?))?;
view.mounts.retire(vm, desktop)?;
crate::window::retire(vm, window)?;
vm.set_attr(desktop, "pending", Value::Nil)?;
vm.set_attr(desktop, "focus", Value::Nil)?;
vm.set_attr(desktop, "focusRequested", Value::Bool(false))?;
// Draining is not publication: failed-domain effects are discarded.
let _ = crate::window::take_commands(vm, window)?;
let windows = object(Some(&vm.get_attr(state.master, "windows")?))?;
vm.dict_delete(windows, &Value::Text(id.to_string()))?;
state.presentations.remove(&id);
state.current = crate::window::MAIN_WINDOW;
Ok(())
}
pub fn finish_closed(&self, vm: &mut Vm) -> Result<()> {
let mut state = self
.session
+9
View File
@@ -365,3 +365,12 @@ pub fn close(cx: &mut NativeContext<'_>, window: ObjectRef) -> Result<(), VmErro
cx.replace_payload(window, data)?;
enqueue(cx, window, Action::Close)
}
/// Host teardown for a stopped VM: no binding, dispatch or source execution.
pub fn retire(vm: &mut Vm, window: ObjectRef) -> Result<(), VmError> {
let mut data = vm.payload::<ManagedWindow>(window, "Window")?.clone();
vm.dict_clear(data.tabs)?;
data.pages.clear();
data.closed = true;
vm.replace_payload(window, data)
}